Skip to content

Instantly share code, notes, and snippets.

@russau
Last active August 16, 2024 07:32
Show Gist options
  • Save russau/fd371b03f5d5f30a50b19b9a5c71c0e2 to your computer and use it in GitHub Desktop.
Save russau/fd371b03f5d5f30a50b19b9a5c71c0e2 to your computer and use it in GitHub Desktop.

My pod wants to access kubernetes resources - Kubernetes RBAC

Part 1 - try get pods with the default sa

# run a kubectl pod using a default service account
kubectl run super-pod-mon --image=bitnami/kubectl --command sleep infinity

# peak at the volumes mounted into the pod
kubectl get pod super-pod-mon -o yaml

# launch a bash shell
kubectl exec -it super-pod-mon -- bash

# from inside the pod look at the things that have been mounted inside
ls  /var/run/secrets/kubernetes.io/serviceaccount

# try to list the pods in the cluster
kubectl get pods

Part 2 - create a service account and give pods permissions

# create the service account
kubectl create serviceaccount sa-super-pod-mon

# create a role, and role binding
cat <<EOF | kubectl apply -f -
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: pod-scanner
  namespace: default
rules:
- apiGroups: [""]
  resources: ["pods", "pods/status"]
  verbs: ["get", "watch", "list"]
---  
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: super-pod-mon-binding
  namespace: default
roleRef:
  kind: Role
  name: pod-scanner
  apiGroup: rbac.authorization.k8s.io
subjects:
- kind: ServiceAccount
  name: sa-super-pod-mon
EOF

# launch a pod with kubectl, using the new service account
kubectl run -ti --rm super-pod-mon-2 \
  --image=bitnami/kubectl \
  --overrides='{ "spec": { "serviceAccount": "sa-super-pod-mon" }  }' \
  --command bash

# from inside the container - list the pods
kubectl get pods

# try something you are not allowed to do
kubectl get pods --all-namespaces
kubectl get ns


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment