How to run kubectl commands inside a container?

I would use kubernetes api, you just need to install curl, instead of kubectl and the rest is restful.

curl http://localhost:8080/api/v1/namespaces/default/pods

Im running above command on one of my apiservers. Change the localhost to apiserver ip address/dns name.

Depending on your configuration you may need to use ssl or provide client certificate.

In order to find api endpoints, you can use --v=8 with kubectl.

example:

kubectl get pods --v=8

Resources:

Kubernetes API documentation

Update for RBAC:

I assume you already configured rbac, created a service account for your pod and run using it. This service account should have list permissions on pods in required namespace. In order to do that, you need to create a role and role binding for that service account.

Every container in a cluster is populated with a token that can be used for authenticating to the API server. To verify, Inside the container run:

cat /var/run/secrets/kubernetes.io/serviceaccount/token

To make request to apiserver, inside the container run:

curl -ik \
     -H "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)" \
     https://kubernetes.default.svc.cluster.local/api/v1/namespaces/default/pods

Leave a Comment