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