Skip to content

Instantly share code, notes, and snippets.

@angelbarrera92
Last active May 23, 2020 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angelbarrera92/b65bf5cea4707b627b7d76e88acc3522 to your computer and use it in GitHub Desktop.
Save angelbarrera92/b65bf5cea4707b627b7d76e88acc3522 to your computer and use it in GitHub Desktop.
Kubernetes: Create users in groups

Usage

chmod +x create-user.sh
# ./create-user.sh <username> <group>
./create-user.sh angel k8spin
./create-user.sh pau k8spin
./create-user.sh bill microsoft
#!/bin/bash
current_context=$(kubectl config view -o json | jq -r '.["current-context"]')
CLUSTER_NAME=$(kubectl config view -o json | jq -r '.contexts[] | select( .name == "'"${current_context}"'") | .context.cluster')
CONTROL_PLANE_ADDRESS=$(kubectl config view -o json | jq -r '.clusters[] | select( .name == "'"${CLUSTER_NAME}"'") | .cluster.server')
CONTROL_PLANE_CA=$(kubectl config view --raw -o json | jq -r '.clusters[] | select( .name == "'"${CLUSTER_NAME}"'") | .cluster["certificate-authority-data"]')
USERNAME=$1
GROUPNAME=$2
CSR_FILE=users/$USERNAME.csr
KEY_FILE=users/$USERNAME.key
CRT_FILE=users/$USERNAME.crt
KUBECONFIG_FILE=users/$USERNAME.kubeconfig
mkdir -p ./users
openssl genrsa -out $KEY_FILE 2048
openssl req -new -key $KEY_FILE -out $CSR_FILE -subj "/CN=$USERNAME/O=$GROUPNAME"
CERTIFICATE_NAME=$USERNAME
cat <<EOF | kubectl apply -f -
apiVersion: certificates.k8s.io/v1beta1
kind: CertificateSigningRequest
metadata:
name: $CERTIFICATE_NAME
spec:
groups:
- system:authenticated
request: $(cat $CSR_FILE | base64 | tr -d '\n')
usages:
- digital signature
- key encipherment
- server auth
- client auth
EOF
kubectl certificate approve $CERTIFICATE_NAME
kubectl get csr $CERTIFICATE_NAME -o jsonpath='{.status.certificate}' | base64 -d > $CRT_FILE
cat << EOF > ${KUBECONFIG_FILE}
apiVersion: v1
kind: Config
clusters:
- cluster:
certificate-authority-data: ${CONTROL_PLANE_CA}
server: ${CONTROL_PLANE_ADDRESS}
name: ${CLUSTER_NAME}
users:
- name: ${USERNAME}
user:
client-certificate-data: $(cat $CRT_FILE | base64 | tr -d '\n')
client-key-data: $(cat $KEY_FILE | base64 | tr -d '\n')
contexts:
- context:
cluster: ${CLUSTER_NAME}
user: ${USERNAME}
name: ${USERNAME}-${CLUSTER_NAME}
current-context: ${USERNAME}-${CLUSTER_NAME}
EOF
echo "Use your new kubeconfig. kubectl cluster-info --kubeconfig ${KUBECONFIG_FILE}"
echo "Dont forget to create the required role bindings"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment