k8wiz
Back to Articles

Ready to test your Kyverno knowledge? Try our Kyverno quiz!

Create namespace defaults with a Kyverno GeneratingPolicy

Give every namespace a default-deny NetworkPolicy, quotas and a registry Secret with Kyverno GeneratingPolicy, existing ones included.

9 min read
By k8wiz Team
  • kyverno
  • generatingpolicy
  • cel
  • multi-tenancy
  • networkpolicy

Most platform teams want the same handful of objects in every namespace: a NetworkPolicy that blocks unsolicited traffic, a ResourceQuota and LimitRange so one team can't eat the cluster, and an image pull Secret for the private registry. Asking each team to create them by hand works until the first team forgets. Kyverno can create them for you the moment a namespace appears.

With Kyverno 1.20, the legacy ClusterPolicy generate rule no longer runs, so this job now belongs to GeneratingPolicy in the policies.kyverno.io/v1 API. This guide builds a defaults policy from scratch, applies it to namespaces that already exist, adds a cloned Secret (which needs extra RBAC), and shows where to look when nothing gets created.

Step 1: check that the pieces are in place

A GeneratingPolicy is evaluated when a matching request reaches the admission webhook, but the objects themselves are created by the background controller. If that controller is disabled or crash-looping, admission succeeds and nothing appears. Check both the CRD and the controller before you write any YAML.

kubectl get crd generatingpolicies.policies.kyverno.io
kubectl -n kyverno get deployment kyverno-background-controller

The deployment name assumes a Helm release called kyverno in the kyverno namespace. Adjust both if you installed under another name.

Step 2: decide which namespaces get defaults

Not every namespace should get a default-deny NetworkPolicy. Applying one to kube-system can break cluster DNS and other add-ons that receive traffic from everywhere. Make the exclusions explicit from the start rather than discovering them during an incident.

A GeneratingPolicy matches its trigger with matchConstraints, the same structure Kubernetes uses for ValidatingAdmissionPolicy. You then narrow the match with matchConditions, which are CEL expressions that must all be true. Here the trigger is a Namespace, and two conditions skip system namespaces and any namespace whose owners opted out with a label.

matchConstraints:
  resourceRules:
    - apiGroups: [""]
      apiVersions: ["v1"]
      operations: ["CREATE", "UPDATE"]
      resources: ["namespaces"]
matchConditions:
  - name: skip-system-namespaces
    expression: "!(object.metadata.name in ['kube-system', 'kube-public', 'kube-node-lease', 'kyverno'])"
  - name: honor-opt-out
    expression: "object.metadata.?labels['platform.example.com/defaults'].orValue('') != 'skip'"

The ?labels[...] and orValue('') pair keeps the second condition from failing on a namespace with no labels at all. CEL does not treat a missing field as empty the way legacy Kyverno patterns did, so this habit saves a lot of confusing errors.

Step 3: write the policy with a YAML template

A GeneratingPolicy has two ways to describe what it creates. The older one is a CEL expression that calls generator.Apply(namespace, [resources]), with every resource built as a CEL map wrapped in dyn() calls. It works, but a NetworkPolicy written that way is hard to read and harder to review.

The second way is a template, marked beta since 1.19 and present in the 1.20 CRD. You write plain YAML in template.value, and with interpolate: cel Kyverno evaluates every (( ... )) placeholder as CEL before parsing the YAML. For manifest-shaped objects like these, templates are the better choice. Each generate entry takes exactly one of expression or template, and the API server rejects an entry that sets both.

Save this as namespace-defaults.yaml.

apiVersion: policies.kyverno.io/v1
kind: GeneratingPolicy
metadata:
  name: namespace-defaults
spec:
  evaluation:
    synchronize:
      enabled: true
    generateExisting:
      enabled: true
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["namespaces"]
  matchConditions:
    - name: skip-system-namespaces
      expression: "!(object.metadata.name in ['kube-system', 'kube-public', 'kube-node-lease', 'kyverno'])"
    - name: honor-opt-out
      expression: "object.metadata.?labels['platform.example.com/defaults'].orValue('') != 'skip'"
  generate:
    - template:
        interpolate: cel
        value: |
          apiVersion: networking.k8s.io/v1
          kind: NetworkPolicy
          metadata:
            name: default-deny-ingress
            namespace: (( object.metadata.name ))
          spec:
            podSelector: {}
            policyTypes:
              - Ingress
          ---
          apiVersion: v1
          kind: ResourceQuota
          metadata:
            name: default-quota
            namespace: (( object.metadata.name ))
          spec:
            hard:
              requests.cpu: "8"
              requests.memory: 16Gi
              limits.memory: 32Gi
              pods: "50"
          ---
          apiVersion: v1
          kind: LimitRange
          metadata:
            name: default-limits
            namespace: (( object.metadata.name ))
          spec:
            limits:
              - type: Container
                defaultRequest:
                  cpu: 100m
                  memory: 128Mi
                default:
                  memory: 512Mi

The template holds three YAML documents, and Kyverno generates each one into the namespace named in its own metadata.namespace. In this policy object is the Namespace that triggered the request, so (( object.metadata.name )) puts every object into the new namespace. A placeholder that is the entire value can return any CEL type, including a map or a list. A placeholder inside a longer string must return a scalar.

The NetworkPolicy blocks ingress only. A default-deny on egress also blocks DNS, and every team then needs an extra policy before its pods can resolve a Service name. Start with ingress and add egress rules once you have a tested allow-DNS policy to ship alongside it.

The LimitRange matters more than it looks. Once a ResourceQuota covers requests.cpu or limits.memory, Kubernetes rejects pods that don't declare those values. The LimitRange fills in defaults, so a team's first deployment doesn't fail with a quota error nobody expected.

Step 4: understand the two evaluation settings

By default a GeneratingPolicy only acts on new requests. If you apply it to a cluster with forty namespaces, those forty get nothing until something updates them. Setting evaluation.generateExisting.enabled: true makes Kyverno run the policy once against every existing resource that matches the trigger when the policy is created. The default is false.

evaluation.synchronize.enabled: true ties the generated objects to the policy. With synchronization on and the data defined inline, as here, Kyverno recreates a generated object that someone deletes, reverts manual edits to it, and updates every copy when you change the policy. Without synchronization, a deleted object stays deleted and policy changes only affect namespaces created afterwards.

That revert behavior is the point for a platform team. A developer who deletes the NetworkPolicy to debug a connection problem will find it back almost at once. If a team really needs different limits, give them the opt-out label and let them own their quota, rather than fighting the controller.

Deleting the policy is the case to plan for. With synchronization on, deleting a data-source policy also deletes everything it generated, unless you set evaluation.orphanDownstreamOnPolicyDelete.enabled: true (default false). For defaults like these, a careless kubectl delete that removes every NetworkPolicy in the cluster is a bad outcome, so consider turning orphaning on.

evaluation:
  synchronize:
    enabled: true
  generateExisting:
    enabled: true
  orphanDownstreamOnPolicyDelete:
    enabled: true

Step 5: apply and verify

Apply the policy and check that Kyverno accepted it. The CRD only prints an AGE column, so read the ready field from the status directly.

kubectl apply -f namespace-defaults.yaml
kubectl get generatingpolicy namespace-defaults \
  -o jsonpath='{.status.conditionStatus.ready}{"\n"}'

Then test both paths. Create a fresh namespace for the admission path, and look at a namespace that existed before the policy for the generateExisting path.

kubectl create namespace team-a
kubectl -n team-a get networkpolicy,resourcequota,limitrange
kubectl -n default get networkpolicy,resourcequota,limitrange

Finally, check that the exclusions hold. A namespace with the opt-out label should come up empty.

kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Namespace
metadata:
  name: team-b
  labels:
    platform.example.com/defaults: skip
EOF
kubectl -n team-b get networkpolicy,resourcequota,limitrange

The last command should print No resources found in team-b namespace.

Step 6: clone a registry Secret into every namespace

The second mode of GeneratingPolicy copies an existing object instead of defining one inline. You fetch the source with resource.Get(apiVersion, resource, namespace, name) in a variable and pass it to generator.Apply. Templates can't do this, so this policy uses an expression. Keep it separate from the defaults policy, because its lifecycle is different. With synchronization on, a clone follows its source: edit the source Secret and every copy updates, delete it and every copy goes away.

apiVersion: policies.kyverno.io/v1
kind: GeneratingPolicy
metadata:
  name: clone-registry-secret
spec:
  evaluation:
    synchronize:
      enabled: true
    generateExisting:
      enabled: true
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["namespaces"]
  matchConditions:
    - name: skip-source-and-system
      expression: "!(object.metadata.name in ['platform', 'kube-system', 'kube-public', 'kube-node-lease', 'kyverno'])"
  variables:
    - name: targetNs
      expression: "object.metadata.name"
    - name: source
      expression: 'resource.Get("v1", "secrets", "platform", "regcred")'
  generate:
    - expression: "generator.Apply(variables.targetNs, [variables.source])"

The platform namespace holds the source Secret, so it is excluded from the trigger. Without that, the policy would try to copy the Secret onto itself.

Applying this policy is not enough on a default Helm install. The chart gives the background controller create, update, patch and delete on NetworkPolicies, ResourceQuotas, LimitRanges, ConfigMaps, Roles and RoleBindings, which is why the first policy worked without extra setup. Secrets are not on that list. The controller can only read Secrets in its own namespace.

The controller's ClusterRole uses aggregation. Any ClusterRole labeled rbac.kyverno.io/aggregate-to-background-controller: "true" has its rules merged in, so you grant the extra access without editing the chart.

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: kyverno-background-controller:secrets
  labels:
    rbac.kyverno.io/aggregate-to-background-controller: "true"
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

Be aware of what this grants: read and write access to every Secret in the cluster for one service account. That is the price of cloning Secrets with any cluster-wide controller, so treat the background controller's service account as a sensitive identity and keep its namespace locked down.

The Helm route works too, through backgroundController.rbac.clusterRole.extraResources in your values file, which renders a ClusterRole that gets aggregated in the same way. Pick one route so the permission lives in one place.

Step 7: find out why nothing was generated

When the admission request succeeds but the objects never show up, the work went to the background controller and failed there. Kyverno records each piece of background work as an UpdateRequest, and its status tells you what happened.

kubectl get updaterequests -A

The status column is one of Pending, Completed, Failed or Skip, and the RuleType column reads cel-generate for requests from a GeneratingPolicy. For a failed request, read the status message, using the namespace and name from the listing. It usually names the cause, such as a forbidden error from missing RBAC or an error from a bad CEL expression.

kubectl -n <namespace> get updaterequest <name> -o jsonpath='{.status.message}{"\n"}'
kubectl -n kyverno logs deployment/kyverno-background-controller --since=15m

A few causes account for most failures. Missing RBAC shows up as forbidden and is fixed as in step 6. A wrong source name in resource.Get fails the clone policy for every namespace at once, so check the name and namespace of the source object first. And if nothing happens for existing namespaces, check that generateExisting.enabled is really true. It defaults to false and is easy to drop when you copy a policy from an example.

Once the policies work, put them in Git next to your other policy manifests and test them in CI like any other Kyverno policy. New namespaces then come with their guardrails already in place, and the platform team stops chasing teams for missing quotas.

Test yourself

Ready to test your Kyverno knowledge? Try our Kyverno quiz!