Kubernetes User, Role, and RoleBinding Setup

This guide demonstrates how to create a Kubernetes user (ZAKOPS) using certificate-based authentication, and bind it to a specific namespace using RBAC (Role-Based Access Control).

Generate the Private Key and CSR

openssl genrsa -out ZAKOPS.key 2048
openssl req -new -key ZAKOPS.key -out ZAKOPS.csr -subj "/CN=ZAKOPS"
  • CN=ZAKOPS becomes the Kubernetes username

Create a Kubernetes CertificateSigningRequest (CSR)

cat <<EOF | kubectl apply -f -
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
  name: ZAKOPS-csr
spec:
  request: $(cat ZAKOPS.csr | base64 | tr -d '\n')
  signerName: kubernetes.io/kube-apiserver-client
  usages:
  - client auth
EOF
  • This CSR is used to request a client certificate for authenticating with the Kubernetes API

Approve the CSR and Extract the Certificate

kubectl certificate approve ZAKOPS-csr
kubectl get csr ZAKOPS-csr -o jsonpath='{.status.certificate}' | base64 -d > ZAKOPS.crt

Configure the User in kubeconfig

kubectl config set-credentials ZAKOPS \
  --client-certificate=ZAKOPS.crt \
  --client-key=ZAKOPS.key

kubectl config set-context ZAKOPS \
  --cluster=default \
  --user=ZAKOPS

Define a Role

Create the file access-role.yaml with the following content

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: access-role
  namespace: namespace-prod
rules:
- apiGroups: ["", "apps"]
  resources:
    - pods
    - pods/log
    - services
    - deployments
    - replicasets
    - daemonsets
  verbs:
    - get
    - list
    - watch
    - create
    - update
    - patch
- apiGroups: ["", "apps"]
  resources:
    - configmaps
    - secrets
  verbs:
    - get
    - list
    - watch
    - patch

Apply it

kubectl apply -f access-role.yaml

Bind the Role to the User

kubectl create rolebinding access-binding \
  --role=access-role \
  --user=ZAKOPS \
  --namespace=namespace-prod

(Optional) Export Certificate and Key as Base64

cat ZAKOPS.crt | base64 | tr -d '\n'
cat ZAKOPS.key | base64 | tr -d '\n'

This step encodes the certificate and key in base64 format for use in a kubeconfig fileor automated tools (e.g., CI/CD), allowing the user to securely access the Kubernetes API

Add a User to an Existing RoleBinding

Use this step if you only need to add a user to an existing RoleBinding, without creating a new role. You can list and edit bindings using kubectl

kubectl get rolebindings -n namespace-prod
kubectl edit rolebinding access-binding -n namespace-prod

Add the following block at the end of the RoleBinding file to include the user

- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: ZAKOPS-1
Updated on