Create Service Account
Create Service Account and Access Restriction
Save Follwoing File As kubeconfig.sh
wget -q https://itmconsult.ir/kubernetes/service-account/kubeconfig.tpl
while [ -z "${ServiceAccount}" ]
do
read -p 'Please Enter Kubernetes ServiceAccount: ' ServiceAccount
export ServiceAccount
done
while [ -z "${NameSpace}" ]
do
read -p 'Please Enter Kubernetes NameSpace: ' NameSpace
export NameSpace
done
# Check ServiceAccount is Exist
kubectl get ns $NameSpace > /dev/null || ( echo -e "${NameSpache} Does'nt Exist\nCreation Started ..." && kubectl create ns $NameSpace > /dev/null && echo "Creation Successful." && kubectl create sa -n ${NameSpace} $ServiceAccount)
export ServiceAccountSecret=$(kubectl get sa $ServiceAccount -n $NameSpace -o jsonpath="{.secrets..name}")
export ServiceAccountToken=$(kubectl get secrets $ServiceAccountSecret -n $NameSpace -o jsonpath="{.data.token}" | base64 -d)
export ClusterCA=$(kubectl config view --raw -o json | jq -r '.clusters[] | select(.name == "'$(kubectl config view --minify -o jsonpath={.contexts..context.cluster})'") | .cluster."certificate-authority-data"')
export ClusterServer=$(kubectl config view --raw -o json | jq -r '.clusters[].cluster.server')
export ClusterName=$(kubectl config view --raw -o json | jq -r '.clusters[].name')
export ServiceAccountContext=${ServiceAccount}-Access
curl -sS https://itmconsult.ir/kubernetes/service-account/kubeconfig.tpl | envsubst > kubeconfig-${ServiceAccount}
Using Follwing Template For ~/.kube/config Save it As kubeconfig.tpl
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: ${ClusterCA}
server: ${ClusterServer}
name: ${ClusterName}
contexts:
- context:
cluster: ${ClusterName}
user: ${ServiceAccount}
name: ${ServiceAccountContext}
current-context: ${ServiceAccountContext}
kind: Config
preferences: {}
users:
- name: ${ServiceAccount}
user:
token: ${ServiceAccountToken}
Runing Following Command
wget https://itmconsult.ir/kubernetes/service-account/kubeconfig.sh
bash kubeconfig.sh
Automatic Way
bash <(curl -s https://itmconsult.ir/kubernetes/service-account/kubeconfig.sh)
After Create Service Account We Need to Create Role And Assign it with RoleBinding. See Following Link to Create Role and RoleBinding.