RBAC

Author: Fabrice JAMMES (LinkedIn).

1. Create Namespaces

Create two namespaces:

  • foo-<ID>
  • bar-<ID>
Answer
kubectl create namespace foo-<ID>
kubectl create namespace bar-<ID>

2. Deploy curl-custom-sa Pod

Create a curl-custom-sa pod inside the foo-<ID> namespace, using the service account foo-<ID>:default (the default service account of foo-<ID>).

Use the following example YAML file: Proxy Pod YAML Example

Answer
# Download the kubectl-proxy pod definition
curl -s -o kubectl-proxy.yaml https://raw.githubusercontent.com/k8s-school/k8s-advanced/master/labs/2_authorization/kubectl-proxy.yaml

# Replace the service account name in the pod definition (foo -> default)
sed -i "s/serviceAccountName: foo/serviceAccountName: default/" kubectl-proxy.yaml

kubectl apply -f kubectl-proxy.yaml -n foo-<ID>

3. Create Services in Both Namespaces

Create a service inside both namespaces (foo-<ID> and bar-<ID>).

Answer
kubectl create service clusterip foo-service --tcp=80:80 -n foo-<ID>
kubectl create service clusterip bar-service --tcp=80:80 -n bar-<ID>

4. Test Access via curl-custom-sa

Run curl inside the curl-custom-sa container to query the API server for services in foo-<ID> and bar-<ID>.

Answer
kubectl exec -it curl-custom-sa -c main bash
curl http://localhost:8001/api/v1/namespaces/foo-<ID>/services
curl http://localhost:8001/api/v1/namespaces/bar-<ID>/services

5. Create Role and RoleBinding

Inside foo-<ID>, create:

  • A Role named service-reader that grants read access to services.
  • A RoleBinding to bind foo-<ID>:default service account to the service-reader role.
Answer

Role Definition (service-reader.yaml):

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: service-reader
  namespace: foo-<ID>
rules:
- apiGroups: [""]
  resources: ["services"]
  verbs: ["get", "list"]

RoleBinding Definition (rolebinding.yaml):

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: service-reader-binding
  namespace: foo-<ID>
subjects:
- kind: ServiceAccount
  name: default
  namespace: foo-<ID>
roleRef:
  kind: Role
  name: service-reader
  apiGroup: rbac.authorization.k8s.io

Apply the Role and RoleBinding:

kubectl apply -f service-reader.yaml
kubectl apply -f rolebinding.yaml

6. Test Role Access via curl-custom-sa pod

Answer

Run curl inside the curl-custom-sa pod to check access:

kubectl exec -it curl-custom-sa -c main bash
curl http://localhost:8001/api/v1/namespaces/foo-<ID>/services  # Should work
curl http://localhost:8001/api/v1/namespaces/bar-<ID>/services  # Should be forbidden

Expected Outcome:

  • curl to foo-<ID> should succeed.
  • curl to bar-<ID> should be forbidden, since the role only grants access to services in foo-<ID>.

Access to full solution

https://github.com/k8s-school/k8s-advanced/blob/master/labs/2_authorization/2_0_RBAC_simple.sh