Create User in Kubernetes

05 Jan 2020

Tested On

OS: Ubuntu 18.04
Kubernetes Version: v1.17.0

This guide will show you how to create user in kubernetes and use it inside a bash script to run some automate tasks.

Here I will show how to create a backup job in Jenkins for chef server that runs inside kubernetes.

Create Kubernetes User

kubectl -n chef create serviceaccount jenkins-robot
kubectl -n chef create rolebinding jenkins-robot-binding --clusterrole=cluster-admin --serviceaccount=chef:jenkins-robot
TOKEN_NAME=$(kubectl -n chef get serviceaccount jenkins-robot -o go-template --template='\n')
kubectl -n chef get secrets ${TOKEN_NAME} -o go-template --template '' | base64 -d  

Create a Jenkins job

Configure kubectl
if [ ! -x ~/bin/kubectl ]
  curl -LO
  chmod +x ./kubectl
  mkdir ~/bin/
  mv ./kubectl ~/bin/kubectl
kubectl config set-cluster prod --server= --certificate-authority=${CA}
kubectl config set-credentials jenkins-robot --token=${TOKEN}
kubectl config set-context prod --cluster=prod --namespace=default --user=jenkins-robot
kubectl config use-context prod
kubectl -n chef exec -i ${POD_NAME} -- chef-server-ctl backup --yes
TAR_FILE=$(kubectl -n chef exec -i ${POD_NAME} -- ls -lrt /var/opt/chef-backup/ | tail -1 | awk '{print $NF}')
rm -f chef-backup*.tgz
kubectl -n chef cp ${POD_NAME}:/var/opt/chef-backup/${TAR_FILE} ${TAR_FILE}