Add script to automate creation of k8s users

This commit is contained in:
Magnus Andersson 2024-11-06 07:55:11 +01:00
parent d5c31c0d32
commit 153a31ae27
Signed by: mandersson
GPG key ID: 1F7C896B34B28164

64
tools/createuser.sh Executable file
View file

@ -0,0 +1,64 @@
#!/bin/bash
CLUSTER="matrixtest"
function usage() {
echo "Usage: ${0#*/} <username> [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 <<EOF > "${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 <contextname> --cluster=<clustername> --namespace=default --user=${1}"