From 153a31ae278001f0c92333dafecb81da955d51dd Mon Sep 17 00:00:00 2001 From: Magnus Andersson Date: Wed, 6 Nov 2024 07:55:11 +0100 Subject: [PATCH] Add script to automate creation of k8s users --- tools/createuser.sh | 64 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100755 tools/createuser.sh diff --git a/tools/createuser.sh b/tools/createuser.sh new file mode 100755 index 0000000..e19a181 --- /dev/null +++ b/tools/createuser.sh @@ -0,0 +1,64 @@ +#!/bin/bash + +CLUSTER="matrixtest" + + +function usage() { + echo "Usage: ${0#*/} [group1,group2,...]" + echo "If no group is given the default one is user" +} + + +if [[ ! "${1}" =~ ^[a-z0-9]+$ ]]; then + usage + exit 1 +fi + + +if [[ -z "${2}" ]]; then + groups=( 'user' ) +elif [[ "${2}" =~ ^[-_a-z1-9]+(,[-_a-z1-9]+)*$ ]]; then + groups=( ${2//,/ } ) +else + echo -e "[Error] Fail to validate grouplist\nWe will exit" + exit 2 +fi + +basepath=${HOME}/ssl/kube/${CLUSTER}/${1} + +echo "Generate key and certificate request" +mkdir -p "${basepath}" +openssl genrsa -out ${basepath}/${1}.key 4096 +subj="/CN=${1}" +for group in "${groups[@]}"; do + subj+="/O=${group}" +done +echo "subj: ${subj}" +openssl req -new -key "${basepath}/${1}.key" -out "${basepath}/${1}.csr" -subj "${subj}" + +cat < "${basepath}/req-${1}.yaml" +apiVersion: certificates.k8s.io/v1 +kind: CertificateSigningRequest +metadata: + name: ${1}-req +spec: + request: $(cat ${basepath}/${1}.csr | base64 | tr -d "\n") + signerName: kubernetes.io/kube-apiserver-client + expirationSeconds: $((86400*3650)) # 10 years + usages: + - client auth +EOF +status=0 +kubectl apply -f "${basepath}/req-${1}.yaml" || { status=1; echo "Failed to submit cerificate request to cluster" ;} +kubectl certificate approve ${1}-req || { status=1; echo "Failed to approve cerificate request by cluster ca";} +[[ "${status}" == "1" ]] && exit 1 + +# Retrieving signed cert +kubectl get "csr/${1}-req" -o jsonpath='{.status.certificate}' | base64 -d > "${basepath}/${1}.crt" || { status=1;echo "[Error] Failed to extract certificate from request status";} +[[ "${status}" == "1" ]] && exit 1 +kubectl delete "csr/${1}-req" + +echo -e "\nRun these commands to create or update the user/context in .kube/config" +echo -e "\nkubectl config set-credentials ${1} --client-certificate=${basepath}/${1}.crt --client-key=${basepath}/${1}.key" +echo "kubectl config set-context --cluster= --namespace=default --user=${1}" +