Skip to content

Instantly share code, notes, and snippets.

@gswallow
Last active March 16, 2022 23:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gswallow/75a83328900a187bdd31b4fb5761b4fb to your computer and use it in GitHub Desktop.
Save gswallow/75a83328900a187bdd31b4fb5761b4fb to your computer and use it in GitHub Desktop.
Creates a namespace and an admin-level account for that namespace.
#!/bin/bash
if [ "$(uname -s)" == "Darwin" ]; then
b64="base64 -D"
else
b64="base64"
fi
project_name=$1
context=$(kubectl config current-context)
cluster=$(kubectl config get-contexts $context --no-headers=true | awk '{print $3}')
server=$(kubectl config view -o jsonpath='{.clusters[?(@.name == "'$cluster'")].cluster.server}')
if ( ! kubectl get ns $project_name 2> /dev/null ); then
kubectl create ns $project_name
kubectl config set-context --current --namespace=$project_name
context="${project_name}/${context#*/}"
fi
if ( ! kubectl get sa svc.${project_name}.admin 2> /dev/null ); then
kubectl create sa svc.${project_name}.admin -n $project_name
fi
if ( ! kubectl get rolebinding ${project_name}.admin 2> /dev/null ); then
kubectl create rolebinding ${project_name}.admin --clusterrole=admin --serviceaccount=$project_name:svc.$project_name.admin --namespace=$project_name
fi
token_secret=$(kubectl get sa svc.${project_name}.admin -n $project_name -oyaml | egrep -o '\S+admin-token\S+')
ca=$(kubectl get secret $token_secret -n $project_name -ojsonpath='{.data.ca\.crt}')
token=$(kubectl get secret $token_secret -n $project_name -ojsonpath='{.data.token}' | eval $b64 -)
cat > ${cluster}-${project_name}.kubeconfig <<EOF
apiVersion: v1
kind: Config
clusters:
- name: ${server}
cluster:
certificate-authority-data: ${ca}
server: ${server}
contexts:
- name: ${context}
context:
cluster: ${server}
namespace: ${project_name}
user: svc.${project_name}.admin
current-context: ${context}
preferences: {}
users:
- name: svc.${project_name}.admin
user:
token: ${token}
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment