Skip to content
CNPE · Chapter 11 of 22 Day 9: Self-service and the golden path

Day 9: Self-service and the golden path

Goal: Every new tenant namespace gets its fences automatically – quota, LimitRange, NetworkPolicies, rights for the team group – and keeps them. New services start from a template in Gitea instead of an empty repo · Duration: approx. 60 min · Prerequisite: Day 8

Briefing

  • On Day 1 you set up the fences by hand; on Day 4, team-green-staging was created without them. A platform must not rely on someone remembering. Self-service means: the team creates a namespace with the label tier=tenant (or Argo CD does), and the platform does the rest – immediately and permanently.
  • The tool is Kyverno, a policy engine in the cluster. Today you use its generate function; Day 13 follows with validation and mutation.
  • Important in practice: Kyverno 1.20 no longer executes the classic ClusterPolicy. You write new policies as GeneratingPolicy, ValidatingPolicy, MutatingPolicy with CEL expressions – the same language as in CRDs (Day 7). Many examples on the web are still old.
  • The golden path is the most convenient way that is also the right one: a template with a Dockerfile and structure from which any team creates a new repo in seconds.

Drill 1: Installing Kyverno

# on cp1
mkdir -p ~/cnpe/tag09 && cd ~/cnpe/tag09
helm repo add kyverno https://kyverno.github.io/kyverno/
helm repo update
# admission and background controllers are platform services (Day 2)
helm install kyverno kyverno/kyverno --version 3.10.0 -n kyverno --create-namespace \
  --set admissionController.priorityClassName=plattform-kritisch \
  --set backgroundController.priorityClassName=plattform-kritisch
k -n kyverno rollout status deploy/kyverno-admission-controller --timeout=300s
k -n kyverno get pods

Expected (abridged):

STATUS: deployed
deployment "kyverno-admission-controller" successfully rolled out
NAME                                             READY   STATUS    RESTARTS   AGE
kyverno-admission-controller-7c9b586499-26r2x    1/1     Running   0          45s
kyverno-background-controller-6dcc6556b6-vlqcp   1/1     Running   0          45s
kyverno-cleanup-controller-c9cc448b4-57lpx       1/1     Running   0          45s
kyverno-reports-controller-758c89b484-tnbd7      1/1     Running   0          45s

Four controllers: admission validates and mutates at creation time, background generates objects and processes existing ones, reports writes result reports, cleanup deletes according to rules.

What happens to a classic policy?

# on cp1
printf 'apiVersion: kyverno.io/v1\nkind: ClusterPolicy\nmetadata:\n  name: alt\nspec:\n  rules: []\n' | k apply -f -

Expected:

Warning: kyverno.io/v1 ClusterPolicy is deprecated and will be removed in a future release; migrate to ValidatingPolicy, MutatingPolicy, GeneratingPolicy or ImageValidatingPolicy (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/
Error from server: error when creating "STDIN": admission webhook "validate-policy.kyverno.svc" denied the request: kyverno.io/v1 ClusterPolicy: Kyverno v1.20 removed execution of legacy kyverno.io policy types and no longer accepts create or update requests for them; ...

Save your progress? Sign up for free

Drill 2: The fences as a GeneratingPolicy

A policy that creates five objects for every namespace with tier=tenant. A CEL list describes the objects; dyn(...) tells CEL that the values may have different types.

# on cp1
cat > mandanten-zaeune.yaml <<'EOF'
apiVersion: policies.kyverno.io/v1
kind: GeneratingPolicy
metadata:
  name: mandanten-zaeune
spec:
  evaluation:
    generateExisting:
      enabled: true                    # when the policy is created, also provision existing namespaces
    synchronize:
      enabled: true                    # reset generated objects if someone changes or deletes them
  matchConstraints:                    # when the policy applies
    resourceRules:
    - apiGroups: [""]
      apiVersions: [v1]
      operations: [CREATE, UPDATE]
      resources: [namespaces]
    objectSelector:                    # tenants only
      matchLabels:
        tier: tenant
  variables:
  - name: ns
    expression: object.metadata.name
  - name: team
    expression: object.metadata.labels["team"]
  - name: zaeune
    expression: |-
      [
        {
          "apiVersion": dyn("v1"),
          "kind": dyn("ResourceQuota"),
          "metadata": dyn({"name": "team-quota"}),
          "spec": dyn({"hard": dyn({
            "requests.cpu": "2", "requests.memory": "4Gi",
            "limits.cpu": "4", "limits.memory": "8Gi",
            "pods": "20", "persistentvolumeclaims": "5", "services.nodeports": "0"
          })})
        },
        {
          "apiVersion": dyn("v1"),
          "kind": dyn("LimitRange"),
          "metadata": dyn({"name": "team-defaults"}),
          "spec": dyn({"limits": dyn([{
            "type": dyn("Container"),
            "defaultRequest": dyn({"cpu": "100m", "memory": "128Mi"}),
            "default": dyn({"cpu": "500m", "memory": "256Mi"}),
            "max": dyn({"cpu": "1", "memory": "1Gi"})
          }])})
        },
        {
          "apiVersion": dyn("networking.k8s.io/v1"),
          "kind": dyn("NetworkPolicy"),
          "metadata": dyn({"name": "default-deny-ingress"}),
          "spec": dyn({"podSelector": dyn({}), "policyTypes": dyn(["Ingress"])})
        },
        {
          "apiVersion": dyn("networking.k8s.io/v1"),
          "kind": dyn("NetworkPolicy"),
          "metadata": dyn({"name": "allow-same-namespace"}),
          "spec": dyn({"podSelector": dyn({}), "policyTypes": dyn(["Ingress"]),
                       "ingress": dyn([{"from": dyn([{"podSelector": dyn({})}])}])})
        },
        {
          "apiVersion": dyn("rbac.authorization.k8s.io/v1"),
          "kind": dyn("RoleBinding"),
          "metadata": dyn({"name": "team-devs-edit"}),
          "roleRef": dyn({"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "edit"}),
          "subjects": dyn([{"apiGroup": "rbac.authorization.k8s.io", "kind": "Group",
                            "name": "team-" + variables.team + "-devs"}])
        }
      ]
  generate:
  - expression: generator.Apply(variables.ns, variables.zaeune)   # create the list in the namespace
EOF
k apply -f mandanten-zaeune.yaml
sleep 20
k -n team-green-staging get quota,limitrange,netpol,rolebinding -o name

Expected:

generatingpolicy.policies.kyverno.io/mandanten-zaeune created
resourcequota/team-quota
limitrange/team-defaults
networkpolicy.networking.k8s.io/allow-same-namespace
networkpolicy.networking.k8s.io/default-deny-ingress

Four out of five – the RoleBinding is missing. The policy reports itself healthy; the error is in the log of the background controller:

# on cp1
# strip colour codes, wrap the last message about team-green-staging
k -n kyverno logs deploy/kyverno-background-controller --tail=40 | grep team-green-staging | tail -1 \
  | sed 's/\x1b\[[0-9;]*m//g' | fold -w 120

Expected (abridged):

... failed to generate resources: permission denied: rolebindings.rbac.authorization.k8s.io "team-devs-edit" is
forbidden: User "system:serviceaccount:kyverno:kyverno-background-controller" cannot get resource "rolebindings" ...

Kyverno may only create what its ServiceAccount is allowed to. For RoleBindings it needs two rights: manage RoleBindings and be allowed to grant the edit role (bind) – without bind, it would have to hold all the rights of edit itself (protection against privilege escalation). Again via aggregation:

# on cp1
cat > kyverno-rechte.yaml <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: kyverno-darf-rolebindings
  labels:
    rbac.kyverno.io/aggregate-to-background-controller: "true"   # into the background controller's role
rules:
- apiGroups: [rbac.authorization.k8s.io]
  resources: [rolebindings]
  verbs: [get, list, watch, create, update, patch, delete]
- apiGroups: [rbac.authorization.k8s.io]
  resources: [clusterroles]
  verbs: [bind]
  resourceNames: [edit]                # grant only edit, not cluster-admin
EOF
k apply -f kyverno-rechte.yaml
# trigger the policy again: an UPDATE on the namespaces (set the label and remove it again)
k label ns team-blue team-green team-green-staging zaeune=neu --overwrite
k label ns team-blue team-green team-green-staging zaeune-
sleep 15
k get rolebinding -A | grep team-devs-edit

Expected (abridged):

clusterrole.rbac.authorization.k8s.io/kyverno-darf-rolebindings created
team-blue            team-devs-edit   ClusterRole/edit   10s
team-green-staging   team-devs-edit   ClusterRole/edit   25s
team-green           team-devs-edit   ClusterRole/edit   10s

The fences from Day 1 in team-blue and team-green have the same names – but Kyverno did not take them over. An object that already exists stays unmanaged: whoever changes or deletes it does not get it back. You can tell by the missing label generate.kyverno.io/policy-name:

# on cp1
k get quota,limitrange,netpol,rolebinding -A -l generate.kyverno.io/policy-name=mandanten-zaeune --no-headers \
  | awk '{print $1}' | sort | uniq -c

Expected:

      1 team-blue
      1 team-green
      5 team-green-staging

In team-blue and team-green, only the new RoleBinding belongs to Kyverno. Handover: delete the hand-made objects and trigger the policy again. The NetworkPolicy allow-monitoring from Day 1 stays – it is not part of the policy.

# on cp1
for ns in team-blue team-green; do
  k -n $ns delete quota team-quota
  k -n $ns delete limitrange team-defaults
  k -n $ns delete netpol default-deny-ingress allow-same-namespace
done
k label ns team-blue team-green zaeune=neu --overwrite
k label ns team-blue team-green zaeune-
sleep 15
k get quota,limitrange,netpol,rolebinding -A -l generate.kyverno.io/policy-name=mandanten-zaeune --no-headers \
  | awk '{print $1}' | sort | uniq -c

Expected (abridged):

      5 team-blue
      5 team-green
      5 team-green-staging

Between deletion and re-creation, the namespaces are without fences for a few seconds – in production, schedule the handover in a maintenance window.

Save your progress? Sign up for free

Drill 3: A new team in seconds

# on cp1
k create namespace team-gelb --dry-run=client -o yaml \
  | k label --local -f - team=gelb tier=tenant -o yaml | k apply -f -
sleep 8
k -n team-gelb get quota,limitrange,netpol,rolebinding -o name
k -n team-gelb get rolebinding team-devs-edit -o jsonpath='{.subjects[0].name}{"\n"}'

Expected:

namespace/team-gelb created
resourcequota/team-quota
limitrange/team-defaults
networkpolicy.networking.k8s.io/allow-same-namespace
networkpolicy.networking.k8s.io/default-deny-ingress
rolebinding.rbac.authorization.k8s.io/team-devs-edit
team-gelb-devs

Now synchronisation: someone deletes the quota, someone else enlarges it.

# on cp1
k -n team-gelb delete quota team-quota
sleep 10
k -n team-gelb get quota
k -n team-gelb patch quota team-quota --type=merge -p '{"spec":{"hard":{"requests.cpu":"50"}}}'
sleep 10
k -n team-gelb get quota team-quota -o jsonpath='{.spec.hard.requests\.cpu}{"\n"}'

Expected (abridged):

resourcequota "team-quota" deleted from team-gelb namespace
NAME         REQUEST                                              LIMIT                                   AGE
team-quota   persistentvolumeclaims: 0/5, pods: 0/20, ...         limits.cpu: 0/4, limits.memory: 0/8Gi   11s
resourcequota/team-quota patched
2

Deleted → re-created, changed → reset. The policy is the source of truth, like Git for Argo CD.

Save your progress? Sign up for free

Drill 4: The golden path

Gitea can mark repos as a template. When a new repo is generated from it, Gitea replaces variables such as ${REPO_NAME} in the files listed in .gitea/template.

# on cp1
G=http://172.16.0.126:30300/api/v1
# create the template repo, marked as template
curl -s -u platform:platform-lab-123 -H 'Content-Type: application/json' \
  -d '{"name":"vorlage-webdienst","default_branch":"main","template":true,"description":"Golden Path: statischer Webdienst mit Dockerfile"}' \
  $G/user/repos | jq -r '"\(.full_name) template=\(.template)"'
cd ~/cnpe/tag09
git init -q -b main vorlage && cd vorlage
printf 'FROM nginx:1.29-alpine\nCOPY index.html /usr/share/nginx/html/index.html\n' > Dockerfile
echo '<h1>${REPO_NAME}</h1>' > index.html
printf '# ${REPO_NAME}\n\nAngelegt aus der Vorlage vorlage-webdienst.\n' > README.md
# files in which Gitea should replace variables
mkdir -p .gitea && printf 'index.html\nREADME.md\n' > .gitea/template
git add -A && git commit -qm 'Vorlage'
git remote add origin http://172.16.0.126:30300/platform/vorlage-webdienst.git
git push -q -u origin main
# a team generates a new repo from it
#   git_content: true   copy the content (otherwise only the settings)
curl -s -u platform:platform-lab-123 -H 'Content-Type: application/json' \
  -d '{"owner":"platform","name":"katalog-app","git_content":true,"description":"Katalog von Team Green"}' \
  $G/repos/platform/vorlage-webdienst/generate | jq -r .full_name
sleep 3
curl -s -u platform:platform-lab-123 $G/repos/platform/katalog-app/raw/index.html
curl -s -u platform:platform-lab-123 $G/repos/platform/katalog-app/raw/README.md

Expected:

platform/vorlage-webdienst template=true
platform/katalog-app
<h1>katalog-app</h1>
# katalog-app

Angelegt aus der Vorlage vorlage-webdienst.

With the pipeline from Day 6 (adjust the parameters url and image) and an overlay directory in the platform repo (Day 4), this becomes a running service in minutes – without a ticket.

Save your progress? Sign up for free

Exercise: What did Kyverno generate?

Time limit: 5 minutes. Find all objects that the policy mandanten-zaeune generated, across all namespaces.

Solution

# on cp1
# Kyverno marks generated objects with labels; the policy name is in the label generate.kyverno.io/policy-name
k get quota,limitrange,netpol,rolebinding -A -l generate.kyverno.io/policy-name=mandanten-zaeune --no-headers | wc -l
k get quota -A -l generate.kyverno.io/policy-name=mandanten-zaeune

Expected (abridged):

20
NAMESPACE            NAME         ...
team-blue            team-quota   ...
team-gelb            team-quota   ...
team-green           team-quota   ...
team-green-staging   team-quota   ...

Four tenant namespaces × five objects = 20. The other labels (generate.kyverno.io/trigger-name etc.) reveal which namespace triggered the generation.

Save your progress? Sign up for free

Challenge

Time limit: 10 minutes. Team Gelb gets more budget: 4 CPU requests. How do you allow that without changing the policy for everyone and without Kyverno resetting it?

Solution

Read the values from a label or an annotation of the namespace, with a default. In the policy, replace "requests.cpu": "2" with:

"requests.cpu": object.metadata.?annotations["plattform.lab/cpu"].orValue("2"),

? and orValue are CEL for “if present, otherwise”. The platform sets the annotation (k annotate ns team-gelb plattform.lab/cpu=4) – teams may not change namespaces, and therefore not their budget either. The UPDATE on the namespace triggers the policy, and Kyverno adjusts the quota.

# on cp1
cd ~/cnpe/tag09
sed -i 's|"requests.cpu": "2", |"requests.cpu": object.metadata.?annotations["plattform.lab/cpu"].orValue("2"), |' mandanten-zaeune.yaml
k apply -f mandanten-zaeune.yaml
k annotate ns team-gelb plattform.lab/cpu=4
sleep 12
for ns in team-gelb team-blue; do echo "$ns: $(k -n $ns get quota team-quota -o jsonpath='{.spec.hard.requests\.cpu}')"; done

Expected:

generatingpolicy.policies.kyverno.io/mandanten-zaeune configured
namespace/team-gelb annotated
team-gelb: 4
team-blue: 2

Save your progress? Sign up for free

Checkpoint

# on cp1
# policy ready
k get generatingpolicy mandanten-zaeune -o jsonpath='{.status.conditionStatus.ready}{"\n"}'
# every tenant has a quota (no output = good)
for ns in $(k get ns -l tier=tenant -o name | cut -d/ -f2); do
  [ -z "$(k -n $ns get quota -o name)" ] && echo "$ns: keine Quota"
done
# Team Gelb's group may work in team-gelb
k auth can-i create deployments -n team-gelb --as=carla --as-group=team-gelb-devs
# the template is marked as template
curl -s -u platform:platform-lab-123 http://172.16.0.126:30300/api/v1/repos/platform/vorlage-webdienst | jq .template

Expected:

true
yes
true

Interview Note

  • How do you make sure every namespace has a quota and NetworkPolicies? Generation by a policy engine at creation time, with synchronisation – not through documentation or tickets.
  • Why does the Kyverno controller need bind on edit? Kubernetes prevents privilege escalation: whoever grants a role must hold it themselves or explicitly have bind on it.
  • What is a golden path? A pre-built, supported path (template, pipeline, deployment) that is the easiest one – teams may deviate, but rarely do.

Enterprise Note

  • Version policies and roll them out via GitOps; test them with kyverno test in CI against sample objects before they reach the cluster.
  • Maintain budgets per team centrally (annotations from a directory or a Crossplane API for teams), not in the policy.
  • A developer portal (Backstage) as the interface for templates and platform APIs – the APIs underneath stay the same.
  • Legacy: migrate existing ClusterPolicy objects before upgrading to Kyverno 1.20 (guide “migration-to-cel”), otherwise they no longer take effect after the upgrade.

Contents

More