2

I have a container where I used a bitnami/kubectl image.
Now I want to run a few kubectl commands inside that container.

How kubectl container aware of my kubeconfig file?
I know that I can mount the local kubeconfig file into containers and use it.

But is there any other way possible to access kubeconfig without using it as a volume mount?

I went throug the documentation of RBAC in Kubernetes.
Does configure role and role-binding alone is enough to run kubectl apply and kubectl delete commands successfully even without mounting kubeconfig file?

It would be really helpful if someone helps me with this.
Thanks in advance!

CodeWizard
  • 128,036
  • 21
  • 144
  • 167
anonymous user
  • 257
  • 5
  • 23
  • Think there is a small misunderstanding in role and role binding in combination with kubeconfig. You still need to authenticate yourself somehow at the cluster. The cluster itself will check, if you have the given authorization to run a specific command based on the roles and rolebinding which are given. In my eyes it's the easiest way to mount the kubeconfig file. Another idea could be service accounts with the right permissions. With those you could get access to whatever you need. – Manuel Jul 05 '22 at 19:35

2 Answers2

3

Now I want to run a few kubectl commands inside that container.

  • Why do you need it inside the container?

kubectl is your CLI to "communicate" with the cluster, the commands are passed to the kube-api, parsed, and executed usually by Admission controller.

Not clear why you need to run kubectl commands inside the container, since kubectl use your kubeconfig file for the communication (it will read the certificate path to the certificate data) and will be able to connect to your cluster.


How to run K8S API in your container?

  #!/bin/sh

  #################################
  ## Access the internal K8S API ##
  #################################
  # Point to the internal API server hostname
  API_SERVER_URL=https://kubernetes.default.svc

  # Path to ServiceAccount token
  # The service account is mapped by the K8S API server in the pods
  SERVICE_ACCOUNT_FOLDER=/var/run/secrets/kubernetes.io/serviceaccount

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

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

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

  # Explore the API with TOKEN and the Certificate
  curl -X GET \
       --cacert ${CACERT} \
       --header "Authorization: Bearer ${TOKEN}" \
       ${API_SERVER_URL}/api
CodeWizard
  • 128,036
  • 21
  • 144
  • 167
2

You can use kubectl without your kubeconfig file. Your pod is launched with a service account. And all kubectl commands will be executed with the service account privileges. So you have to use rbac to grant access rights to that service account first.

Roman Geraskin
  • 161
  • 1
  • 2