First: How Kubernetes Identifies Users
Step 1 — Generate the Key and CSR
Bash
mkdir rbac && cd rbac
openssl genrsa -out jane.key 2048
openssl req -new -key jane.key -subj "/CN=jane/O=developers" -out jane.csr
Step 2 — Submit the CSR to Kubernetes
Bash
cat jane.csr | base64 | tr -d '\n'
Yaml
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
name: jane
spec:
request: <base64-encoded-csr>
signerName: kubernetes.io/kube-apiserver-client
expirationSeconds: 86400
usages:
- client auth
Bash
kubectl apply -f csr.yaml
kubectl certificate approve jane
Step 3 — Extract the Signed Certificate
Bash
kubectl get csr jane -o jsonpath='{.status.certificate}' | base64 -d > jane.crt
Step 4 — Build the kubeconfig
Yaml
apiVersion: v1
kind: Config
clusters:
- cluster:
certificate-authority-data: <base64 of /etc/kubernetes/pki/ca.crt>
server: https://<api-server-ip>:<port>
name: my-cluster
contexts:
- context:
cluster: my-cluster
user: jane
name: jane-context
current-context: jane-context
users:
- name: jane
user:
client-certificate-data: <base64 of jane.crt>
client-key-data: <base64 of jane.key>
Bash
cat /etc/kubernetes/pki/ca.crt | base64 | tr -d '\n'
cat jane.crt | base64 | tr -d '\n'
cat jane.key | base64 | tr -d '\n'
Bash
kubectl get pods --kubeconfig jane.kubeconfig
Step 5 — Create a Role
Yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: pod-reader-role
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list", "watch"]
Step 6 — Bind the Role to Jane
Yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: pod-reader-binding
namespace: default
subjects:
- kind: User
name: jane
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader-role
apiGroup: rbac.authorization.k8s.io
Bash
kubectl apply -f role.yaml
kubectl apply -f bind.yaml
Bash
kubectl get role pod-reader-role
kubectl get rolebindings -n default
Step 7 — Verify Access
Bash
kubectl get pods --kubeconfig jane.kubeconfig
# works now
kubectl delete pod <name> --kubeconfig jane.kubeconfig
# Error from server (Forbidden)
Bash
kubectl auth can-i list pods --namespace=default --as=jane
# yes
kubectl auth can-i delete pods --namespace=default --as=jane
# no
A Few Things Worth Knowing
Bash
kubectl get rolebindings,clusterrolebindings -A -o wide
Originally published on Techbeatly.
