Kubernetes: CI/CD User for Gitlab

We want to deploy our helm charts to k8 cluster and ofc want to do it automatically

I’ve prepared the script which allows to create cicd-user as a service account, build appropriate config file context and allows to work only in defined namespaces.

More secure (useful) to create serviceaccount in isolated namespace

set -e

#define service account name
NAMESPACE="cicd-ns"
SERVICE_ACCOUNT_NAME="gitlab-user"

#create namespace
kubectl create ns $NAMESPACE

#create service account
kubectl create sa ${SERVICE_ACCOUNT_NAME} -n $NAMESPACE

#extracting secret name and public key
SECRET_NAME=$(kubectl get sa ${SERVICE_ACCOUNT_NAME} -n $NAMESPACE -o jsonpath={.secrets..name})
kubectl get secret "${SECRET_NAME}" -n $NAMESPACE -o json | jq -r '.data["ca.crt"]' | base64 --decode > "ca.crt"

#fetch user token
USER_TOKEN=$(kubectl get secret "${SECRET_NAME}" -n $NAMESPACE -o json | jq -r '.data["token"]' | base64 --decode)

#create context
KUBECFG_FILE_NAME="k8s-${SERVICE_ACCOUNT_NAME}_${NAMESPACE}.conf"
CURRENT_CONTEXT=$(kubectl config current-context)
CLUSTER_NAME=$(kubectl config get-contexts "${CURRENT_CONTEXT}" | awk '{print $3}' | tail -n 1)
ENDPOINT=$(kubectl config view -o jsonpath="{.clusters[?(@.name == \"${CLUSTER_NAME}\")].cluster.server}")
CONTEXT_NAME=${SERVICE_ACCOUNT_NAME}-${CLUSTER_NAME}
kubectl config set-cluster ${CLUSTER_NAME} --kubeconfig="${KUBECFG_FILE_NAME}" --server="${ENDPOINT}" --certificate-authority="ca.crt" --embed-certs=true
kubectl config set-credentials $CONTEXT_NAME --kubeconfig="${KUBECFG_FILE_NAME}" --token="${USER_TOKEN}"
kubectl config set-context $CONTEXT_NAME --kubeconfig="${KUBECFG_FILE_NAME}" --cluster="${CLUSTER_NAME}" --user=$CONTEXT_NAME

#verify context
kubectl config use-context $CONTEXT_NAME --kubeconfig="${KUBECFG_FILE_NAME}"
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: cicd-role-binding
  namespace: your-working-ns
subjects:
  - kind: ServiceAccount
    name: gitlab-user
    namespace: cicd-ns
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io

Better to use Custom role instead of ClusterRole: cluster-admin, but in that way we have to define what resources should be available.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Design a site like this with WordPress.com
Get started