Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use curl to access the Kubernetes API from within a pod?

I am using Kubernetes 1.8.6 on Google Kubernetes Engine and have a pod running Alpine as part of a StatefulSet.

I have logged into my pod using kubectl exec -it my-pod-0 -- /bin/sh and then run the following commands at the prompt:

$ CA_CERT=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
$ TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
$ NAMESPACE=$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace)
$ curl --cacert $CA_CERT -H "Authorization: Bearer $TOKEN" "https://kubernetes
/api/v1/namespaces/$NAMESPACE/services/"

Unfortunately a 403 Forbidden error is returned:

{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {

  },
  "status": "Failure",
  "message": "services is forbidden: User \"system:serviceaccount:default:default\" cannot list services in the namespace \"default\": Unknown user \"system:serviceaccount:default:default\"",
  "reason": "Forbidden",
  "details": {
    "kind": "services"
  },
  "code": 403

What am I doing wrong?

like image 330
Dan Avatar asked Jan 17 '18 23:01

Dan


People also ask

How do I access API from Kubernetes pod?

From inside the pod, kubernetes api server can be accessible directly on "https://kubernetes.default". By default it uses the "default service account" for accessing the api server. So, we also need to pass a "ca cert" and "default service account token" to authenticate with the api server. Save this answer.

How do I run curl command from within a Kubernetes pod?

To do that, I use the kubectl run command, which creates a single Pod. Kubernetes will now pull the curlimages/curl image, start the Pod, and drop you into a terminal session. So now you can use curl! Make sure you run curl in the same Kubernetes namespace which you want to debug.


1 Answers

You're not doing anything wrong. That pod's service account (specified in the pod's serviceAccountName) simply doesn't have any API permissions.

You can grant a view role to that service account like this:

kubectl create rolebinding default-viewer \
  --clusterrole=view \
  --serviceaccount=default:default \
  --namespace=default

See https://kubernetes.io/docs/admin/authorization/rbac/#service-account-permissions for more details about granting permissions to service accounts.

like image 72
Jordan Liggitt Avatar answered Oct 16 '22 05:10

Jordan Liggitt