Search code examples
kubernetesnamespacesrbac

Automatically create Kubernetes resources after namespace creation


I have 2 teams:

  • devs: they create a new Kubernetes namespace each time they deploy a branch/tag of their app
  • ops: they manage access control to the cluster with (cluster)roles and (cluster)rolebindings

The problem is that 'devs' cannot kubectl their namespaces until 'ops' have created RBAC resources. And 'devs' cannot create RBAC resources themselves as they don't have the list of subjects to put in the rolebinding resource (sharing the list is not an option).

I have read the official documentation about Admission webhooks but what I understood is that they only act on the resource that triggered the webhook.

Is there a native and/or simple way in Kubernetes to apply resources whenever a new namespace is created?


Solution

  • I've come up with a solution by writing a custom controller.

    With the following custom resource deployed, the controller injects the role and rolebinding in namespaces matching dev-.* and fix-.*:

    kind: NamespaceResourcesInjector
    apiVersion: blakelead.com/v1alpha1
    metadata:
      name: nri-test
    spec:
      namespaces:
      - dev-.*
      - fix-.*
      resources:
      - |
        apiVersion: rbac.authorization.k8s.io/v1
        kind: Role
        metadata:
          name: dev-role
        rules:
          - apiGroups: [""]
            resources: ["pods","pods/portforward", "services", "deployments", "ingresses"]
            verbs: ["list", "get"]
          - apiGroups: [""]
            resources: ["pods/portforward"]
            verbs: ["create"]
          - apiGroups: [""]
            resources: ["namespaces"]
            verbs: ["list", "get"]
      - |
        apiVersion: rbac.authorization.k8s.io/v1
        kind: RoleBinding
        metadata:
          name: dev-rolebinding
        subjects:
        - kind: User
          name: dev
        roleRef:
          kind: Role
          name: dev-role
          apiGroup: rbac.authorization.k8s.io
    

    The controller is still in early stages of development but I'm using it successfully in more and more clusters.

    Here it is for those interested: https://github.com/blakelead/nsinjector