Skip to content

Instantly share code, notes, and snippets.

@w3irdrobot
Created February 28, 2022 19:35
Show Gist options
  • Save w3irdrobot/c957a48de21111e71df5da4e782ab7dc to your computer and use it in GitHub Desktop.
Save w3irdrobot/c957a48de21111e71df5da4e782ab7dc to your computer and use it in GitHub Desktop.
Create User in Kubernetes and output usable kubeconfig
#!/usr/bin/env bash
set -euo pipefail
# make sure username is passed as argument
if [[ "$#" -ne 1 ]]; then
echo "not enough arguments"
echo "Usage: create_kubernetes_user.sh USERNAME"
exit 1
fi
# make sure there is a kubernetes context
if ! context=$(kubectl config current-context) 1>/dev/null 2>&1; then
echo "no kubernetes context set"
exit 1
fi
username=$1
# create private key for user
if [[ ! -f "$username.key" ]]; then
openssl genrsa -out "$username.key" 2048
fi
# create signing request for user
if [[ ! -f "$username.csr" ]]; then
openssl req -new -key "$username.key" -out "$username.csr" -subj "/CN=$username/O=Foundation Devices/C=US"
fi
# create CertificateSigningRequest
if ! kubectl get csr "$username" 1>/dev/null 2>&1; then
cat <<EOF | kubectl apply -f -
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
name: $username
spec:
request: $(base64 --wrap 0 < "$username.csr")
signerName: kubernetes.io/kube-apiserver-client
usages:
- client auth
EOF
fi
# approve the CSR
status=$(kubectl get csr "$username" -o jsonpath='{.status}')
if [[ "$status" = "{}" ]]; then
kubectl certificate approve "$username"
fi
cluster_name=$(kubectl config get-contexts "$context" | awk '{print $3}' | tail -n 1)
endpoint=$(kubectl config view -o jsonpath="{.clusters[?(@.name == \"$cluster_name\")].cluster.server}")
kubectl get csr "$username" -o jsonpath='{.status.certificate}' | base64 --decode > "$username.crt"
kubectl config view --raw -o json | \
jq -r ".clusters[] | select(.name == \"$cluster_name\") | .cluster.\"certificate-authority-data\"" | \
base64 --decode > ca.crt
# create kubeconfig
(
export KUBECONFIG="k8s-$username-conf.yaml"
kubectl config set-credentials "$username" \
--embed-certs=true \
--client-key="$username.key" \
--client-certificate="$username.crt"
kubectl config set-cluster "$cluster_name" \
--embed-certs=true \
--server="$endpoint" \
--certificate-authority=ca.crt
kubectl config set-context "$context" --cluster="$cluster_name" --user="$username"
kubectl config use-context "$context"
)
echo "kubeconfig created in k8s-$username-conf.yaml"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment