Created
September 11, 2019 14:46
-
-
Save danquack/e860a5f00615bb92561d041c3f4e2ed0 to your computer and use it in GitHub Desktop.
A script to create a kubeconfig, signed from a root CA
This file contains hidden or 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 | |
# Minimum Required Args: username (u) and cluster (c) | |
# | |
# Sample usage: | |
# Create a dev-user service account for the kubernetes cluster, in the dev namespace | |
# ./create-config.sh -c kubernetes -u dev-user -n dev -l $HOME/ca-directory | |
while getopts "u:c:n:l:" option; do | |
case $option in | |
u) USERNAME=$OPTARG;; | |
c) CLUSTER=$OPTARG;; | |
n) NAMESPACE=$OPTARG;; | |
l) CA_LOCATION=$OPTARG;; | |
esac | |
done | |
if [[ -z $USERNAME ]]; then | |
echo "Username not provided" | |
exit 1 | |
fi | |
if [[ -z $CLUSTER ]]; then | |
echo "Cluster not provided" | |
exit 1 | |
fi | |
if [[ -z $NAMESPACE ]]; then | |
echo "Namespace not provided. Using default" | |
NAMESPACE=default | |
fi | |
if [[ -z $CA_LOCATION ]]; then | |
echo "CA Directory not provided. Assuming /etc/kubernetes/pki" | |
CA_LOCATION="/etc/kubernetes/pki" | |
fi | |
# Create an SSL Key | |
CURRENT_DIRECTORY=$PWD | |
echo "Current Directory is: $CURRENT_DIRECTORY" | |
cd /tmp | |
openssl genrsa -out $USERNAME.key 2048 | |
openssl req -new -key $USERNAME.key -out $USERNAME.csr -subj "/CN=$USERNAME/O=$CLUSTER" | |
# Create user cert | |
openssl x509 -req -in $USERNAME.csr -CA $CA_LOCATION/ca.crt -CAkey $CA_LOCATION/ca.key -CAcreateserial -out $USERNAME.crt -days 900 | |
# Make Certs directory | |
mkdir -p "${CURRENT_DIRECTORY}/.certs" || exit 1 | |
mv /tmp/$USERNAME.crt /tmp/$USERNAME.key "${CURRENT_DIRECTORY}/.certs" | exit 1 | |
cd $CURRENT_DIRECTORY | |
# Create the Config File | |
kubectl config --kubeconfig="${CURRENT_DIRECTORY}/config" set-credentials $USERNAME --client-certificate="${CURRENT_DIRECTORY}/.certs/$USERNAME.crt" --client-key="${CURRENT_DIRECTORY}/.certs/$USERNAME.key" --embed-certs=true | |
kubectl config --kubeconfig="${CURRENT_DIRECTORY}/config" set-context $USERNAME-context --cluster=$CLUSTER --namespace=$NAMESPACE --user=$USERNAME | |
# Switch the context just created | |
kubectl config --kubeconfig="${CURRENT_DIRECTORY}/config" use-context $USERNAME-context | |
# Remove created directory, as certs are embedded within | |
rm -rf "${CURRENT_DIRECTORY}/.certs" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment