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
metadata:
  name: debug
  namespace: demo
spec:
  restartPolicy: Never
  serviceAccountName: demo-user
  containers:
  - 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
APISERVER=https://kubernetes.default.svc

# Path to ServiceAccount token
SERVICEACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount

# Read this Pod's namespace
NAMESPACE=$(cat ${SERVICEACCOUNT}/namespace)

# Read the ServiceAccount bearer token
TOKEN=$(cat ${SERVICEACCOUNT}/token)

# Reference the internal certificate authority (CA)
CACERT=${SERVICEACCOUNT}/ca.crt

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

PODs

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

Links