Grant a pod access to create new Namespaces

5/14/2021

I'm trying to provision emepheral environments via automation leveraging Kubernetes namespaces. My automation workers deployed in Kubernetes must be able to create Namespaces. So far my experimentation with this led me nowhere. Which binding do I need to attach to the Service Account to allow it to control Namespaces? Or is my approach wrong?

My code so far:

deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: k8s-deployer
  namespace: tooling
  labels:
    app: k8s-deployer
spec:
  replicas: 1
  selector:
    matchLabels:
      app: k8s-deployer 
  template:
    metadata:
      name: k8s-deployer
      labels:
        app: k8s-deployer
    spec:
      serviceAccountName: k8s-deployer
      containers: ...

rbac.yaml:

apiVersion: v1
kind: ServiceAccount
metadata:
  name: k8s-deployer
  namespace: tooling

---

# this lets me view namespaces, but not write
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: administer-cluster
subjects:
- kind: ServiceAccount
  name: k8s-deployer
  namespace: tooling
roleRef:
  kind: ClusterRole
  name: admin
  apiGroup: rbac.authorization.k8s.io
-- Aleksander Nowak
automation
continuous-integration
kubernetes

1 Answer

5/14/2021

To give a pod control over something in Kubernetes you need at least four things:

  1. Create or select existing Role/ClusterRole (you picked administer-cluster, which rules are unknown to me).
  2. Create or select existing ServiceAccount (you created k8s-deployer in namespace tooling).
  3. Put the two together with RoleBinding/ClusterRoleBinding.
  4. Assign the ServiceAccount to a pod.

Here's an example that can manage namespaces:

# Create a service account
apiVersion: v1
kind: ServiceAccount
metadata:
  name: k8s-deployer
  namespace: tooling
---
# Create a cluster role that allowed to perform 
# ["get", "list", "create", "delete", "patch"] over ["namespaces"]
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: k8s-deployer
rules:
  - apiGroups: [""]
    resources: ["namespaces"]
    verbs: ["get", "list", "create", "delete", "patch"]
---
# Associate the cluster role with the service account
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: k8s-deployer
  # make sure NOT to mention 'namespace' here or
  # the permissions will only have effect in the
  # given namespace
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: k8s-deployer
subjects:
- kind: ServiceAccount
  name: k8s-deployer
  namespace: tooling

After that you need to mention the service account name in pod spec as you already did. More info about RBAC in the documentation.

-- anemyte
Source: StackOverflow