Last active
August 8, 2018 22:30
-
-
Save richardsonlima/fbc34f9a762263eb28b2767edf77c4d8 to your computer and use it in GitHub Desktop.
k8s-auth-creator - ./create-user.sh <api_server> <username> <namespace>
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 | |
# set -x | |
KUBE_APISERVER=$1 | |
USER=$2 | |
NS=$3 | |
USAGE="USAGE: create-user.sh <api_server> <username> <namespace>\n | |
Example: https://172.22.1.1:6443" | |
CSR=`pwd`/user-csr.json | |
SSL_PATH="/etc/kubernetes/ssl" | |
SSL_FILES=(ca-key.pem ca.pem ca-config.json) | |
CERT_FILES=(${USER}.csr $USER-key.pem ${USER}.pem) | |
if [[ $KUBE_APISERVER == "" ]]; then | |
echo -e $USAGE | |
exit 1 | |
fi | |
if [[ $USER == "" ]];then | |
echo -e $USAGE | |
exit 1 | |
fi | |
# csr | |
function createCSR(){ | |
cat>$CSR<<EOF | |
{ | |
"CN": "USER", | |
"hosts": [], | |
"key": { | |
"algo": "rsa", | |
"size": 2048 | |
}, | |
"names": [ | |
{ | |
"C": "CN", | |
"ST": "Sao Paulo", | |
"L": "Sao Paulo", | |
"O": "k8s", | |
"OU": "System" | |
} | |
] | |
} | |
EOF | |
# csr | |
sed -i "s/USER/$USER/g" $CSR | |
} | |
function ifExist(){ | |
if [ ! -f "$SSL_PATH/$1" ]; then | |
echo "$SSL_PATH/$1 not found." | |
exit 1 | |
fi | |
} | |
# | |
for f in ${SSL_FILES[@]}; | |
do | |
echo "Check if ssl file $f exist..." | |
ifExist $f | |
echo "OK" | |
done | |
echo "Create CSR file..." | |
createCSR | |
echo "$CSR created" | |
echo "Create user's certificates and keys..." | |
cd $SSL_PATH | |
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes $CSR| cfssljson -bare $USER | |
cd - | |
# | |
kubectl config set-cluster kubernetes \ | |
--certificate-authority=${SSL_PATH}/ca.pem \ | |
--embed-certs=true \ | |
--server=${KUBE_APISERVER} \ | |
--kubeconfig=${USER}.kubeconfig | |
# | |
kubectl config set-credentials $USER \ | |
--client-certificate=$SSL_PATH/${USER}.pem \ | |
--client-key=$SSL_PATH/${USER}-key.pem \ | |
--embed-certs=true \ | |
--kubeconfig=${USER}.kubeconfig | |
# | |
kubectl config set-context kubernetes \ | |
--cluster=kubernetes \ | |
--user=$USER \ | |
--namespace=$USER \ | |
--kubeconfig=${USER}.kubeconfig | |
# | |
kubectl config use-context kubernetes --kubeconfig=${USER}.kubeconfig | |
# if needed create a namespace | |
#kubectl create ns $NS | |
# | |
kubectl create rolebinding ${USER}-admin-binding --clusterrole=admin --user=$USER --namespace=$NS --serviceaccount=$USER:default | |
kubectl config get-contexts | |
echo "Congratulations!" | |
echo "Your kubeconfig file is ${USER}.kubeconfig" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment