Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vdboor/b5beb9570a4919b4428ccb4557727a95 to your computer and use it in GitHub Desktop.
Save vdboor/b5beb9570a4919b4428ccb4557727a95 to your computer and use it in GitHub Desktop.
Create a service account and generate a kubeconfig file for it - this will also set the default namespace for the user
#!/bin/bash
# Add user to k8s 1.6 using service account, no RBAC (must create RBAC after this script)
if [[ -z “$1” ]] || [[ -z “$2” ]];then
echo “usage: $0 <username> <environment (stg|prod)>”
exit 1
fi
USER=$1
environment=$2
NAMESPACE=services-${environment}
KUBECFG_FILE_NAME=/tmp/k8s-${USER}-${ENVIRONMENT}-conf
S3_LOCATION=”s3://some-bucket/k8-configs/${KUBECFG_FILE_NAME}”
echo “Creating a service account: ${USER}-${ENVIRONMENT}”
kubectl create sa ${USER}-${ENVIRONMENT}
echo -e “\nGetting secret of service account ${USER}-${ENVIRONMENT}”
SECRET=$(kubectl get sa ${USER}-${ENVIRONMENT} -o json | jq -r .secrets[].name)
echo “secret = ${SECRET}”
echo -e “\nExtracting ca.crt from secret”
kubectl get secret ${SECRET} -o json | jq -r ‘.data[“ca.crt”]’ | base64 -D > ca.crt
echo -e “\nGetting user token”
USER_TOKEN=$(kubectl get secret ${SECRET} -o json | jq -r ‘.data[“token”]’ | base64 -D)
c=`kubectl config current-context`
echo -e “\nSetting current context to: $c”
cluster_name=`kubectl config get-contexts $c | awk ‘{print $3}’ | tail -n 1`
echo “cluster_name: ${CLUSTER_NAME}”
endpoint=`kubectl config view -o jsonpath=”{.clusters[?(@.name == \”${CLUSTER_NAME}\”)].cluster.server}”`
echo “endpoint: ${endpoint}”
# Set up the config
echo -e “\nPreparing k8s-${USER}-${ENVIRONMENT}-conf”
echo “Setting a cluster entry in kubeconfig”
# $KUBECONFIG environment variable sets the config in file path
KUBECONFIG=${KUBECFG_FILE_NAME} kubectl config set-cluster ${CLUSTER_NAME} \
 — embed-certs=true \
 — server=${ENDPOINT} \
 — certificate-authority=./ca.crt
echo “Setting a user entry in kubeconfig”
KUBECONFIG=${KUBECFG_FILE_NAME} kubectl config set-credentials ${USER}-${ENVIRONMENT}-${CLUSTER_NAME#cluster-} — token=${USER_TOKEN}
echo “Setting a context entry in kubeconfig”
KUBECONFIG=${KUBECFG_FILE_NAME} kubectl config set-context ${USER}-${ENVIRONMENT}-${CLUSTER_NAME#cluster-} \
 — cluster=${CLUSTER_NAME} \
 — user=${USER}-${ENVIRONMENT}-${CLUSTER_NAME#cluster-} \
 — namespace=${NAMESPACE}
echo “Setting the current-context in the kubeconfig file”
KUBECONFIG=${KUBECFG_FILE_NAME} kubectl config use-context ${USER}-${ENVIRONMENT}-${CLUSTER_NAME#cluster-}
echo “Uploading ${KUBECFG_FILE_NAME} to ${S3_LOCATION}”
aws s3 cp $KUBECFG_FILE_NAME $S3_LOCATION
echo “done! Test with: “
echo “KUBECONFIG=${KUBECFG_FILE_NAME} kubectl get pods”
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment