Skip to content

Instantly share code, notes, and snippets.

@jeesmon
Last active July 19, 2022 19:27
Show Gist options
  • Save jeesmon/5f90ee125d61af53a6339cd024a2c80b to your computer and use it in GitHub Desktop.
Save jeesmon/5f90ee125d61af53a6339cd024a2c80b to your computer and use it in GitHub Desktop.

Ever needed an option to run oc or kubectl command from within a pod in the cluster with proper permissions and without hard coding your (short-lived) token? With right RBAC, you can do the authn for oc/kubectl using your service account token. This token will be automatically mounted on the pod together with CA cert and you can login to oc/kubectl like this:

oc login --token="$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)" \
  --server='https://kubernetes.default' \
  --certificate-authority='/var/run/secrets/kubernetes.io/serviceaccount/ca.crt'

Another option:

API_SERVER=https://kubernetes.default.svc
SERVICE_ACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount
NAMESPACE=$(cat ${SERVICE_ACCOUNT}/namespace)
TOKEN=$(cat ${SERVICE_ACCOUNT}/token)
CA_CERT=${SERVICE_ACCOUNT}/ca.crt

export KUBECONFIG=~/.kube/test
kubectl config set-credentials test --token=${TOKEN}
kubectl config set-cluster test --server=${API_SERVER} --certificate-authority=${CA_CERT}
kubectl config set-context test --user=test --namespace=${NAMESPACE} --cluster test
kubectl config use-context test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment