Last active
July 29, 2025 20:24
-
-
Save dsavchenko/28bd81bd1c9acec82b9ce1680c4a899a to your computer and use it in GitHub Desktop.
Script to add k8s user
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 | |
| # Script to add k8s admin user | |
| # Credit: https://www.frakkingsweet.com/adding-a-full-admin-user-in-kubernetes/ | |
| USERNAME=${1} | |
| GROUP=${2} | |
| if [ $# -ne 2 ]; then | |
| echo "Syntax: $(basename "$0") USERNAME GROUP" | |
| exit 1 | |
| fi | |
| echo + Creating private key: ${USERNAME}.key | |
| openssl genrsa -out ${USERNAME}.key 4096 | |
| echo + Creating signing request: ${USERNAME}.csr | |
| openssl req -new -key ${USERNAME}.key -out ${USERNAME}.csr -subj "/CN=${USERNAME}/O=${GROUP}" | |
| cat > ${USERNAME}-signing-request.yaml <<EOF | |
| apiVersion: certificates.k8s.io/v1 | |
| kind: CertificateSigningRequest | |
| metadata: | |
| name: __USERNAME__-csr | |
| spec: | |
| groups: | |
| - system:authenticated | |
| - example:masters | |
| request: __CSRREQUEST__ | |
| signerName: kubernetes.io/kube-apiserver-client | |
| usages: | |
| - digital signature | |
| - key encipherment | |
| - client auth | |
| expirationSeconds: 7776000 | |
| EOF | |
| sed -i "s@__USERNAME__@${USERNAME}@" ${USERNAME}-signing-request.yaml | |
| B64=`cat ${USERNAME}.csr | base64 | tr -d '\n'` | |
| sed -i "s@__CSRREQUEST__@${B64}@" ${USERNAME}-signing-request.yaml | |
| echo + Creating signing request in kubernetes | |
| kubectl create -f ${USERNAME}-signing-request.yaml | |
| echo + List of signing requests | |
| kubectl get csr | |
| kubectl certificate approve ${USERNAME}-csr | |
| KEY=`cat ${USERNAME}.key | base64 | tr -d '\n'` | |
| CERT=`kubectl get csr ${USERNAME}-csr -o jsonpath='{.status.certificate}'` | |
| echo "======KEY" | |
| echo ${KEY} | |
| echo | |
| echo "======Cert" | |
| echo $CERT | |
| echo | |
| export USERNAME | |
| export CERT | |
| export KEY | |
| kubectl config view --flatten --minify | \ | |
| yq '.contexts[0].context.namespace = "default" ' | \ | |
| yq '.contexts[0].context.user = strenv(USERNAME)' | \ | |
| yq '.contexts[0].name = strenv(USERNAME)+"@"+.contexts[0].context.cluster' | \ | |
| yq '.current-context = strenv(USERNAME)+"@"+.contexts[0].context.cluster' | \ | |
| yq '.users[0].name = strenv(USERNAME)' | \ | |
| yq '.users[0].user.client-certificate-data = strenv(CERT)' | \ | |
| yq '.users[0].user.client-key-data = strenv(KEY)' > ${USERNAME}-kubeconfig.yaml | |
| echo "======Config" | |
| cat ${USERNAME}-kubeconfig.yaml | |
| echo | |
| rm ${USERNAME}.key | |
| rm ${USERNAME}.csr | |
| rm ${USERNAME}-signing-request.yaml |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment