Kubernetes API by examples

February 11, 2020 - Last updated: February 14, 2020

I been playing with the Kubernetes API and I woud like to post and update with the time some examples.

For my case I have a service account which has complete access to a particular namespace, the service account is called demo-user.

To do some test I created a pod and I configured the service account to the pod, so I can get the credentials inside the container and query the API with the service account.

You can create a pod on the fly and attach to the console, but for the example I created a manifest with a container running just a tail -f to not exit, the Docker image is an Alpine image with curl command installed.

My pod manifest debug.yaml.

apiVersion: v1
kind: Pod
  name: debug
  namespace: demo
  restartPolicy: Never
  serviceAccountName: demo-user
  - name: debug
    image: ellerbrock/alpine-bash-curl-ssl
    command: ["sh", "-c", "tail -f /dev/null"]

Deploy the pod manifest and attach to the container.

kubectl apply -f debug.yaml
kubectl exec -ti debug -n demo -- bash

Once inside the container get the token and certificate to authenticate trough the API.

# Point to the internal API server hostname

# Path to ServiceAccount token

# Read this Pod's namespace

# Read the ServiceAccount bearer token

# Reference the internal certificate authority (CA)

# Explore the API with TOKEN
curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" \
    -X GET ${APISERVER}/api


Get all the pods.

curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" \ 
    -X GET ${APISERVER}/api/v1/namespaces/${NAMESPACE}/pods

Get all the pods running.

curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" \ 
    -X GET ${APISERVER}/api/v1/namespaces/${NAMESPACE}/pods?fieldSelector=status.phase=Running

Get all the pods NOT running.

curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" \ 
    -X GET ${APISERVER}/api/v1/namespaces/${NAMESPACE}/pods?fieldSelector=status.phase!=Running


Related posts