Created
June 30, 2017 00:26
-
-
Save jganoff/2e91787bd73fe86e391a88e72bdb5560 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env bash | |
set -e | |
# How many days should this certificate be valid for? | |
DAYS_VALID_FOR=365 | |
CONFIG_FILE=${CONFIG_FILE:-kubectl-config-$(date +%s)} | |
CLUSTER_NAME=${CLUSTER_NAME:-staging} | |
SERVER_ENDPOINT=${SERVER_ENDPOINT:-https://mycluster.example.com} | |
USERNAME=$1 | |
DIR=$(dirname $0) | |
ASSETS_DIR=${ASSETS:-"$DIR/../assets"} | |
CA_CRT="$ASSETS_DIR/generated/tls/ca.crt" | |
CA_KEY="$ASSETS_DIR/generated/tls/ca.key" | |
if [[ ! -f "$CA_CRT" ]]; then | |
2>&1 echo "Unable to find CA crt at $CA_CRT" | |
exit 1 | |
fi | |
if [[ ! -f "$CA_KEY" ]]; then | |
2>&1 echo "Unable to find CA key at $CA_KEY" | |
exit 1 | |
fi | |
if [[ -z "$USERNAME" ]]; then | |
2>&1 echo "Must provide a username as the first argument." | |
exit 1 | |
fi | |
echo "Creating a client certificate for $USERNAME..." | |
KEY="$USERNAME.pem" | |
CSR="$USERNAME.csr" | |
CRT="$USERNAME.crt" | |
openssl genrsa -out $KEY 4096 | |
openssl req -new -key $KEY -out $CSR -subj "/CN=$USERNAME" | |
openssl x509 -req -in $CSR -CA $CA_CRT -CAkey $CA_KEY -CAcreateserial -out $CRT -days $DAYS_VALID_FOR | |
echo "Client certificate generated at $CRT valid for $DAYS_VALID_FOR days" | |
export KUBECONFIG=$CONFIG_FILE | |
kubectl config set-cluster $CLUSTER_NAME --server $SERVER_ENDPOINT --certificate-authority="$CA_CRT" --embed-certs | |
kubectl config set-credentials $USERNAME --certificate-authority=$CA_CRT --client-key=$KEY --client-certificate=$CRT --embed-certs | |
echo "Wrote new kubectl config file to $CONFIG_FILE with the $USERNAME user configured for cluster $CLUSTER_NAME" | |
# Echo the config file path to stdout so we can capture it easily | |
echo $CONFIG_FILE | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment