Created
July 20, 2021 14:49
-
-
Save erkanzileli/9d14486d33155976ce80fa610310f099 to your computer and use it in GitHub Desktop.
Generates a kubeconfig using the current context. Purpose is use static token instead of certificate files in kubeconfig
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/sh | |
kubectl -n kube-system create serviceaccount cluster-admin | |
cat <<EOF | kubectl apply -f - | |
apiVersion: rbac.authorization.k8s.io/v1 | |
kind: ClusterRoleBinding | |
metadata: | |
name: cluster-admin | |
roleRef: | |
apiGroup: rbac.authorization.k8s.io | |
kind: ClusterRole | |
name: cluster-admin | |
subjects: | |
- kind: ServiceAccount | |
name: cluster-admin | |
namespace: kube-system | |
EOF | |
export USER_TOKEN_NAME=$(kubectl -n kube-system get serviceaccount cluster-admin -o=jsonpath='{.secrets[0].name}') | |
export USER_TOKEN_VALUE=$(kubectl -n kube-system get secret/${USER_TOKEN_NAME} -o=go-template='{{.data.token}}' | base64 --decode) | |
export CURRENT_CONTEXT=$(kubectl config current-context) | |
export CURRENT_CLUSTER=$(kubectl config view --raw -o=go-template='{{range .contexts}}{{if eq .name "'''${CURRENT_CONTEXT}'''"}}{{ index .context "cluster" }}{{end}}{{end}}') | |
export CLUSTER_SERVER=$(kubectl config view --raw -o=go-template='{{range .clusters}}{{if eq .name "'''${CURRENT_CLUSTER}'''"}}{{ .cluster.server }}{{end}}{{ end }}') | |
export CLUSTER_CA=$(kubectl config view --raw -o=go-template='{{range .clusters}}{{if eq .name "'''${CURRENT_CLUSTER}'''"}}{{with index .cluster "certificate-authority-data" }}{{.}}{{end}}{{ end }}{{ end }}') | |
if [ -z $CLUSTER_CA ]; then | |
export CLUSTER_CA_FILE=$(kubectl config view --raw -o=go-template='{{range .clusters}}{{if eq .name "'''${CURRENT_CLUSTER}'''"}}{{with index .cluster "certificate-authority" }}{{.}}{{end}}{{ end }}{{ end }}') | |
export CLUSTER_CA=$(cat $CLUSTER_CA_FILE | base64) | |
fi | |
cat <<EOF >cluster-admin-config | |
apiVersion: v1 | |
kind: Config | |
current-context: ${CURRENT_CONTEXT} | |
contexts: | |
- name: ${CURRENT_CONTEXT} | |
context: | |
cluster: ${CURRENT_CONTEXT} | |
user: cluster-admin | |
namespace: kube-system | |
clusters: | |
- name: ${CURRENT_CONTEXT} | |
cluster: | |
certificate-authority-data: ${CLUSTER_CA} | |
server: ${CLUSTER_SERVER} | |
users: | |
- name: cluster-admin | |
user: | |
token: ${USER_TOKEN_VALUE} | |
EOF | |
kubectl --kubeconfig $(pwd)/cluster-admin-config get po -A |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment