Created
February 10, 2021 15:21
-
-
Save harivemula/22c65721edbfe2119194bf1b6ebd30a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
# version: 1.0 | |
# Generate kubeconfig file from service account token | |
# Usage ./k8s-sa-kubeconfig.sh <namespace> <service account name> | |
TEMPDIR=$( mktemp -d ) | |
trap "{ rm -rf $TEMPDIR ; exit 255; }" EXIT | |
SA_SECRET=$( kubectl get sa -n $1 $2 -o jsonpath='{.secrets[0].name}' ) | |
# Pull the bearer token and cluster CA from the service account secret. | |
BEARER_TOKEN=$( kubectl get secrets -n $1 $SA_SECRET -o jsonpath='{.data.token}' | base64 -d ) | |
kubectl get secrets -n $1 $SA_SECRET -o jsonpath='{.data.ca\.crt}' | base64 -d > $TEMPDIR/ca.crt | |
CURR_CONTEXT=$( kubectl config current-context ) | |
CLUSTER=$( kubectl config view -o jsonpath='{.contexts[?(@.name=="'$CURR_CONTEXT'")].context.cluster}' ) | |
CLUSTER_URL=$( kubectl config view -o jsonpath='{.clusters[?(@.name=="'$CLUSTER'")].cluster.server}' ) | |
KUBECONFIG=kubeconfig-$1-$2 | |
kubectl config --kubeconfig=$KUBECONFIG \ | |
set-cluster \ | |
$CLUSTER \ | |
--server=$CLUSTER_URL \ | |
--certificate-authority=$TEMPDIR/ca.crt \ | |
--embed-certs=true | |
kubectl config --kubeconfig=$KUBECONFIG \ | |
set-credentials $2 --token=$BEARER_TOKEN | |
kubectl config --kubeconfig=$KUBECONFIG \ | |
set-context $CLUSTER \ | |
--cluster=$CLUSTER \ | |
--user=$2 | |
kubectl config --kubeconfig=$KUBECONFIG \ | |
use-context $CLUSTER | |
echo "kubeconfig written to file \"$KUBECONFIG\"" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment