Created
November 24, 2023 10:58
-
-
Save flymop/da667ecbab43a721b21a9d29a9b502c5 to your computer and use it in GitHub Desktop.
create a service account and bind it with cluster-admin role, then export as a kubeconfig
This file contains hidden or 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 | |
# create a service account and bind it with cluster-admin role, then export as a kubeconfig | |
# typically used when creating a new minikube/kind cluster | |
set -ex | |
set -o pipefail | |
NAMESPACE=$1 | |
SA_ACCOUNT_NAME=$2 | |
EXPORT_KUBECONFIG_PATH=$3 | |
# create sa | |
kubectl create sa ${SA_ACCOUNT_NAME} --namespace ${NAMESPACE} | |
# create cluster-rolebinding | |
kubectl create clusterrolebinding ${SA_ACCOUNT_NAME}-rolebinding \ | |
--clusterrole=cluster-admin --serviceaccount=${NAMESPACE}:${SA_ACCOUNT_NAME} | |
# create sa token | |
kubectl apply -f - <<EOF | |
apiVersion: v1 | |
kind: Secret | |
metadata: | |
name: ${SA_ACCOUNT_NAME}-token | |
namespace: ${NAMESPACE} | |
annotations: | |
kubernetes.io/service-account.name: ${SA_ACCOUNT_NAME} | |
type: kubernetes.io/service-account-token | |
EOF | |
# construct kubeconfig for service account | |
TOKEN=`kubectl -n ${NAMESPACE} get secret ${SA_ACCOUNT_NAME}-token -o jsonpath='{.data.token}' | base64 --decode` | |
CLUSTER_SERVER=$(kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}') | |
CLUSTER_NAME=$(kubectl config view --minify -o jsonpath='{.clusters[0].name}') | |
kubectl config set-credentials ${SA_ACCOUNT_NAME} --token=${TOKEN} --kubeconfig ${EXPORT_KUBECONFIG_PATH} | |
kubectl config set-cluster ${CLUSTER_NAME} --server=${CLUSTER_SERVER} --insecure-skip-tls-verify=true --kubeconfig ${EXPORT_KUBECONFIG_PATH} | |
kubectl config set-context ${CLUSTER_NAME} --user=${SA_ACCOUNT_NAME} --cluster=default-cluster --kubeconfig ${EXPORT_KUBECONFIG_PATH} | |
kubectl config use-context ${CLUSTER_NAME} --kubeconfig ${EXPORT_KUBECONFIG_PATH} | |
# add reverse-proxy to export the bridge IP address and change the kubeconfig server addr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment