Skip to content

Instantly share code, notes, and snippets.

@grawert
Created September 19, 2019 16:10
Show Gist options
  • Save grawert/da0b1b3ed37357d9c92037a851c444b6 to your computer and use it in GitHub Desktop.
Save grawert/da0b1b3ed37357d9c92037a851c444b6 to your computer and use it in GitHub Desktop.
Create new user certificate and kubeconfig for Kubernetes
#!/bin/bash
# Create new user certificate and kubeconfig
# Run me as user 'root' on K8s master node
CA_LOCATION="/etc/kubernetes/pki"
KUBECONFIG="./kubeconfig"
KEY_LEN="2048"
DAYS_VALID="500"
NEWUSER=$1
GROUPNAME=$2
SUBJ="/CN=$NEWUSER/O=$GROUPNAME"
set -e
function exit_error {
[[ -z "$1" ]] || echo $1
echo "Usage: $0 NEW_USER_NAME GROUP_NAME"
exit 1
}
function merge_kubeconfig {
# merge new kubeconfig with admin.conf and remove admin credentials
ADMIN_KUBECONFIG=/etc/kubernetes/admin.conf
KUBECONFIG_TEMP=${KUBECONFIG}.temp
KUBECONFIG=${KUBECONFIG}:${ADMIN_KUBECONFIG} \
kubectl config view --flatten > $KUBECONFIG_TEMP
mv $KUBECONFIG_TEMP $KUBECONFIG
export KUBECONFIG=${KUBECONFIG}
CLUSTERNAME=$(kubectl config get-clusters | grep -v NAME)
kubectl config unset users.kubernetes-admin
kubectl config set contexts.cluster.${CLUSTERNAME}.user $NEWUSER
kubectl config unset contexts
kubectl config set-context kubernetes --user=$NEWUSER --cluster=$CLUSTERNAME
kubectl config use-context kubernetes
unset $KUBECONFIG
}
[[ -z "$NEWUSER" ]] && exit_error
[[ -z "$GROUPNAME" ]] && exit_error
[[ -f "${CA_LOCATION}/ca.key" ]] || exit_error "missing ${CA_LOCATION}/ca.key"
[[ -f "${CA_LOCATION}/ca.crt" ]] || exit_error "missing ${CA_LOCATION}/ca.crt"
openssl req -newkey rsa:$KEY_LEN -nodes -subj "$SUBJ" \
-out ${CA_LOCATION}/$NEWUSER.csr \
-keyout ${CA_LOCATION}/$NEWUSER.key
openssl x509 -req -CA ${CA_LOCATION}/ca.crt -CAkey ${CA_LOCATION}/ca.key \
-CAcreateserial \
-in ${CA_LOCATION}/$NEWUSER.csr \
-out ${CA_LOCATION}/$NEWUSER.crt \
-days $DAYS_VALID
kubectl --kubeconfig=$KUBECONFIG config set-credentials $NEWUSER \
--client-certificate=${CA_LOCATION}/$NEWUSER.crt \
--client-key=${CA_LOCATION}/$NEWUSER.key \
--embed-certs=true
merge_kubeconfig
echo "Key/certificate has been written to ${CA_LOCATION}/$NEWUSER.{key,crt}"
echo "kubeconfig has been written to $KUBECONFIG"
@grawert
Copy link
Author

grawert commented Sep 27, 2019

NEWUSER="booboo"; kubeadm alpha kubeconfig user --client-name="$NEWUSER" --cert-dir /etc/kubernetes/pki > kubeconf_${NEWUSER}.conf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment