how to use openapi with labelSelector? - kubernetes

I want to use OpenAPI to get and filter pod, but labelSelector is not working. There is no result.
curl -k -H "Authorization: Bearer ${my_token}" --silent https://192.168.35.60:6443/api/v1/namespaces/default/pods?labelSelector=app%3Dactivemq&limit=500
kubectl get pod -l app=activemq --v 8

Related

Kubernetes: How to get other pods' name from within a pod?

I'd like to find out the other pods' name running in the same single-host cluster. All pods are single-application containers. I have pod A (written in Java) that acts as a TCP/IP server and a few other pods (written in C++) connect to the server.
In pod A, I can get IP address of clients (other pods). How do I get their pods' name? I can't run kubectl commands because pod A has no kubectl installed.
Thanks,
You can directly call kube-apiserver with cURL.
First you need to have a serviceaccount binded to clusterrole to be able to send requests to apiserver.
kubectl create clusterrole listpods --verb=get,list,watch --resource=pods
kubectl create clusterrolebinding listpods --clusterrole=listpods --serviceaccount=default:default
Get a shell inside a container
kubectl exec -it deploy/YOUR_DEPLOYMENT -- sh
Define necessary parameters for your cURL, run below commands inside container
APISERVER=https://kubernetes.default.svc
SERVICEACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount
NAMESPACE=$(cat ${SERVICEACCOUNT}/namespace)
TOKEN=$(cat ${SERVICEACCOUNT}/token)
CACERT=${SERVICEACCOUNT}/ca.crt
Send pods list request to apiserver
curl -s -k -H "Authorization: Bearer $TOKEN" -H 'Accept: application/json' $APISERVER/api/v1/pods | jq "[ .items[] | .metadata.name ]"
Done ! It will return you a json list of "kubectl get pods"
For more examples, you can check OpenShift RestAPI Reference. Also, if you are planning to do some programmatic stuff, I advice you to checkout official kubernetes-clients.
Credits for jq improvement to #moonkotte

how to "stop" and "start" kubernetes API deployments /pod

I have a requirement to stop deployment by label name and start it again, via the API
also I need to do that for a group of deployments so I added label for each of them
so i know how to filter the deploymnet by desire label. but I found that if I would like to stop deployment from running, I do need to scale it down and changed the replica number to 0
is there any other option to do that via API? because now I should need to keep the replica for start (scale-up again) but this is a parameter that not easy to keep in a lifecycle of a service
so now the best option that I found is smth like :
PAYLOAD='[{"op":"replace","path":"/spec/replicas","value":"3"}]'
curl -X PATCH -d$PAYLOAD -H 'Content-Type: application/json-patch+json' $API_URL
but I am asking if there is smth else and if there is a group "stop /start" like in docker swarm that you can just run docker stack rm for example
If you would like to run kubectl scale deployments mydeployment --replicas=0 via API call, you can run below command
$ curl -k \
-X PUT \
-d #- \
-H "Authorization: Bearer $TOKEN" \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
https://$ENDPOINT/apis/apps/v1/namespaces/$NAMESPACE/deployments/$NAME/scale <<'EOF'
{
"kind": "Scale",
"apiVersion": "apps/v1beta1",
...
}
EOF
More examples can be found in Openshift RestAPI documentations.
How about a solution where you store number of replicas in annoatation:
export DEPLOYMENT_NAME=xxx
kubectl annotate deployments $DEPLOYMENT_NAME replicas-before=$(kubectl get deployments.apps $DEPLOYMENT_NAME -ojsonpath="{.spec.replicas}")
kubectl scale deployment --replicas 0 $DEPLOYMENT_NAME
kubectl scale deployment --replicas $(kubectl get deployments.apps nginx -ojsonpath="{.metadata.annotations.replicas-before}") $DEPLOYMENT_NAME
This does not require additional saving the state externally. You save the current state in an annotation in this example called replicas-before, and then scale down the deployment to 0. If you want to restore the number or replicas, just read the replicas from annotation and scale the deployment up to this value.
I know you asked for a solution using k8s api. Just run the kubectl command with -v=10 and see what api requests are being sent.

Rollout restart statefulset using kubectl proxy

I have started kubectl proxy from within my pods and am able to access kubernetes APIs. I have a need to restart my statefulset.
Using kubectl, I would done this:
kubectl rollout restart statefulset my-statefulset
However, I would like to do this using the REST APIs. For instance, I can delete my pods, using this:
curl -XDELETE localhost:8080/api/v1/namespaces/default/pods
Is there any equivalent REST endpoint that I can use to rollout restart a statefulset?
I run your command kubectl rollout restart statefulset my-statefulset --v 10 and notice the output logs.
I figured out kubectl makes a patch request when I apply above command. And I am able to do that patch request using curl like following
curl -k --data '{"spec":{"template":{"metadata":{"annotations":{"kubectl.kubrnetes.io/restartedAt":"'"$(date +%Y-%m-%dT%T%z)"'"}}}}}'\
-XPATCH -H "Accept: application/json, */*" -H "Content-Type: application/strategic-merge-patch+json"\
localhost:8080/apis/apps/v1/namespaces/default/statefulsets/my-statefulset

How to access kubernetes cluster using masterurl

I am trying to connect to kubernetes cluster using master url. However, I encounter an error when attempting the following command
Command: config, ConfigErr clientcmd.BuildConfigFromFlags("https://192.168.99.100:8443","")
Error: Get "https://192.168.99.100:8443/api/v1/namespaces": x509: certificate signed by unknown authority
Has anyone else encountered this and/or know how to solve this error?
Get the kube-apiserver endpoint by describing the service
kubectl describe svc kubernetes
This will list the endpoint for your APIServer like this:
Endpoints: 172.17.0.6:6443
Get the token to access the APIServer like this:
TOKEN=$(kubectl get secret $(kubectl get serviceaccount default -o jsonpath='{.secrets[0].name}') -o jsonpath='{.data.token}' | base64 --decode )
Query the APIServer with the retreived token:
curl -v https://172.17.0.6:6443/api/v1/nodes -k --header "Authorization:Bearer $TOKEN" --insecure
config, ConfigErr = clientcmd.BuildConfigFromFlags(masterurl,"")
config.BearerToken=token
config.Insecure=true
use this code to make it work.it worked for me

Is it possible to execute kubectl commands via curl?

is it possible to execute kubectl commands as a curl by simply hitting GKE kube master api for some resources and get json back ?
Kubernetes is an entirely API-based system ,to interact with the Kubernetes API you need a ServiceAccount (obtained through a Cluster Role and a RoleBinding).
Here you can find the documentation for Google Kubernetes Engine API: https://cloud.google.com/kubernetes-engine/docs/reference/rest
Also as side note, might be usefully:
https://kubernetes.io/docs/tasks/administer-cluster/access-cluster-api/#accessing-the-kubernetes-api
Kubernetes is REST API based and can be called via curl.
https://kubernetes.io/docs/tasks/administer-cluster/access-cluster-api/#accessing-the-kubernetes-api
Kubectl internally does curl to Kubernetes API which can be verified via running below command and searching for curl and you can execute the same curl command. In the below example kubectl is using certificate for authentication and executing curl against Kubernetes API.
kubectl get nodes --v=10
curl -k -v -XGET -H "Accept: application/json;as=Table;v=v1beta1;g=meta.k8s.io, application/json" -H "User-Agent: kubectl/v1.17.0 (darwin/amd64) kubernetes/70132b0" 'https://127.0.0.1:32768/api/v1/nodes?limit=500'
But to call Kubernetes REST API you can either use a client certificate or a JWT bearer token. A service account which has a bearer token is the recommended way to communicate to Kubernetes API from a pod.
Kubernetes API.