Kubernetes RBAC Example
Jump to navigation
Jump to search
Use Service Account for Namespaced Admin Runner
This will create and destroy namespace test
create.sh
#!/usr/bin/env bash set -e # namespace=test kubectl create namespace test kubectl config set-context --current --namespace=test kubectl create sa test-sa cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: test namespace: test spec: serviceAccountName: test-sa containers: - name: test image: alpine args: - sleep - "1000000" EOF sleep 5 cat <<EOF | kubectl apply -f - apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: annotations: rbac.authorization.kubernetes.io/autoupdate: "true" labels: name: test-read-only namespace: test rules: - apiGroups: - "" resources: ["*"] verbs: - get - list - watch - apiGroups: - extensions resources: ["*"] verbs: - get - list - watch - apiGroups: - apps resources: ["*"] verbs: - get - list - watch EOF cat <<EOF | kubectl apply -f - kind: ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-binding subjects: - kind: ServiceAccount name: test-sa namespace: test roleRef: kind: ClusterRole name: test-read-only apiGroup: rbac.authorization.k8s.io EOF kubectl get pod test -o yaml | grep serviceAccount kubectl exec test -- apk add curl kubectl exec test -- curl -L "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" -o /bin/kubectl kubectl exec test -- chmod +x /bin/kubectl kubectl exec test -- kubectl get pods kubectl exec test -- mount | grep secrets kubectl exec test -- ls /run/secrets/kubernetes.io/serviceaccount/ kubectl exec test -- cat /run/secrets/kubernetes.io/serviceaccount/namespace kubectl exec test -- cat /run/secrets/kubernetes.io/serviceaccount/token kubectl exec test -- cat /run/secrets/kubernetes.io/serviceaccount/ca.crt
delete.sh
#!/usr/bin/env bash set -e # namespace=test # kubectl create namespace test kubectl config set-context --current --namespace=test kubectl exec test -- kubectl get pods kubectl delete ClusterRoleBinding test-binding sleep 15 kubectl get pods --field-selector=status.phase=Running kubectl exec test -- kubectl get pods || true kubectl exec test -- mount | grep secrets kubectl exec test -- ls /run/secrets/kubernetes.io/serviceaccount/ kubectl delete clusterrole test-read-only kubectl delete sa test-sa kubectl delete pod test kubectl delete namespace test
Extract creds via command if wanted
s=$(kubectl describe sa test-sa | grep Tokens | awk '{print $2}'); kubectl get secret $s -o "jsonpath={.data['ca\.crt']}" s=$(kubectl describe sa test-sa | grep Tokens | awk '{print $2}'); kubectl get secret $s -o "jsonpath={.data['ca\.crt']}" kubectl exec test -- ls /run/secrets/kubernetes.io/serviceaccount/ kubectl exec test -- cat /run/secrets/kubernetes.io/serviceaccount/namespace kubectl exec test -- cat /run/secrets/kubernetes.io/serviceaccount/token kubectl exec test -- cat /run/secrets/kubernetes.io/serviceaccount/ca.crt