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
Last active
May 23, 2020 06:06
-
-
Save angelbarrera92/b65bf5cea4707b627b7d76e88acc3522 to your computer and use it in GitHub Desktop.
Kubernetes: Create users in groups
This file contains 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 | |
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