Kubernetes API curl Access

In the situation that issue k8s instructions from inside the container, usually we use curl command to do that (if you have kubectl binary in container’s execution path, you can use kubectl command as well).

First you need credentials and api server information:

1
2
3
4
5
## MY_POD_NAMESPACE
NAMESPACE=$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace)
K8S=https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT
CACERT=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)

You can get these all from environment variables, when create the pod, k8s has already injected these information into the containers.

Of course, if the service account you use does not have full privilege, the API access is limited.

then for example, get the detail of current pod:

1
2
3
4
5
6
7
8
9
10
11
12
POD_NAME="$MY_POD_NAME"
NS="$MY_POD_NAMESPACE"
OUT_FILE=$(mktemp /tmp/pod-schedule.XXXX)

## http_code is the return status code
http_code=$(curl -w "%{http_code}" -sS --cacert $CACERT -H "Content-Type: application/json" -H "Accept: application/json, */*" -H "Authorization: Bearer $TOKEN" "$K8S/api/v1/namespaces/$NS/pods/$POD_NAME" -o $OUT_FILE)

if [[ $http_code -ne 200 ]]; then
echo "{\"result\": \"Failure\", \"httpReturnCode\":$http_code}" |${JQ} '.'
exit 1
fi
image=$(cat $OUT_FILE |jq '.spec.containers[] | select(.name=="xxx") | .image')

How do I know the curl path to request?

1
kubectl get pod -v 10

this will show you verbose message (curl under the hood), then you can get the path and use it in your curl command.

Not all kubectl commands are clearly with curl, for example kubectl exec, still need some efforts to know.

references: https://blog.openshift.com/executing-commands-in-pods-using-k8s-api/ https://docs.okd.io/latest/rest_api/api/v1.Pod.html#Post-api-v1-namespaces-namespace-pods-name-exec

0%