Skip to content
Hands-on IT IT Drills

Day 7: Conditions with includeWhen

Goal: Optional objects: a NetworkPolicy protects Postgres on request, and a PodDisruptionBudget appears on its own as soon as there is more than one replica. · Duration: approx. 40 min · Prerequisite: Day 6

Briefing

  • includeWhen is a list of conditions on an object. kro creates the object only if all of them are true. For OR, you write || within one condition.
  • kro re-evaluates the conditions on every reconcile. If one becomes false, kro removes the object.
  • If an object drops out, all objects that depend on it drop out with it.
  • Conditions on schema.spec are stable. Conditions on the status of other objects can flip back and forth and then keep creating and deleting objects (“flip-flop”). readyWhen is the better tool for that.
Object Condition
dbPolicy (NetworkPolicy) ${schema.spec.networkPolicy}
budget (PodDisruptionBudget) ${schema.spec.replicas > 1}

Drill 1: Switches in the Schema

mkdir -p ~/kro-lab/tag07
cd ~/kro-lab/tag07
cp ../tag06/notesapp-rgd.yaml .

Add a switch below database::

      database:
        storage: string | default="1Gi"
      networkPolicy: boolean | default=false

Save your progress? Sign up for free

Drill 2: Two Optional Objects

Append to the end of the file (after the object service):

    - id: dbPolicy
      includeWhen:
        - ${schema.spec.networkPolicy}
      template:
        apiVersion: networking.k8s.io/v1
        kind: NetworkPolicy
        metadata:
          name: ${database.metadata.name}
        spec:
          podSelector:
            matchLabels: ${database.spec.selector.matchLabels}
          policyTypes:
            - Ingress
          ingress:
            - from:
                - podSelector:
                    matchLabels: ${deployment.spec.selector.matchLabels}
              ports:
                - port: 5432
    - id: budget
      includeWhen:
        - ${schema.spec.replicas > 1}
      template:
        apiVersion: policy/v1
        kind: PodDisruptionBudget
        metadata:
          name: ${schema.metadata.name}
        spec:
          minAvailable: 1
          selector:
            matchLabels: ${deployment.spec.selector.matchLabels}
  • The NetworkPolicy applies to the Postgres pods and only lets notes-api pods through on port 5432. The labels come from the selectors, not as text, so they always match.
  • A PodDisruptionBudget with minAvailable: 1 and only one replica would block every kubectl drain. That’s why it only appears from two replicas on.
kubectl apply -f notesapp-rgd.yaml
kubectl get rgd notesapp
kubectl get rgd notesapp -o jsonpath='{.status.topologicalOrder}{"\n"}'

Expected:

resourcegraphdefinition.kro.run/notesapp configured
NAME       APIVERSION   KIND       STATE    READY   AGE
notesapp   v1alpha1     NotesApp   Active   True    18m
["secret","dbSecret","dbData","database","dbService","deployment","service",
"dbPolicy","budget"]

Both new objects are in the order, but kro hasn’t created either of them yet:

kubectl -n app get networkpolicy,pdb

Expected:

No resources found in app namespace.

Save your progress? Sign up for free

Drill 3: Open

Without a NetworkPolicy, every pod in the cluster can reach the database. A test pod with nc (netcat) shows it:

kubectl -n app run probe --rm -i --restart=Never --image=busybox:1.38 \
  -- nc -zv -w 2 notes-db 5432

Expected (shortened):

notes-db (10.43.143.246:5432) open
pod "probe" deleted from app namespace
  • -z only checks whether the port answers, without sending data. -w 2 waits at most two seconds.
  • --rm -i starts the pod, shows its output and deletes it afterwards.

Save your progress? Sign up for free

Drill 4: Closed

Turn on the NetworkPolicy and give the app two replicas:

kubectl -n app patch notesapp notes --type merge \
  -p '{"spec":{"networkPolicy":true,"replicas":2}}'
kubectl -n app get networkpolicy,pdb

Expected:

notesapp.lab.example.com/notes patched
NAME                                       POD-SELECTOR   AGE
networkpolicy.networking.k8s.io/notes-db   app=notes-db   12s

NAME                               MIN AVAILABLE   MAX UNAVAILABLE   ALLOWED DISRUPTIONS   AGE
poddisruptionbudget.policy/notes   1               N/A               1                     12s
kubectl -n app run probe --rm -i --restart=Never --image=busybox:1.38 \
  -- nc -zv -w 2 notes-db 5432

Expected (shortened):

pod "probe" deleted from app namespace
pod app/probe terminated (Error)

No more open: after two seconds, nc gives up. k3s enforces NetworkPolicies with its built-in policy controller. notes-api is still allowed through:

curl -s localhost:30080/notes

Expected:

[{"id":"5953a797-216a-45be-a2f9-fe1e5782a1f4","text":"bleibt erhalten"}]

Save your progress? Sign up for free

Drill 5: Removing

kubectl -n app patch notesapp notes --type merge \
  -p '{"spec":{"networkPolicy":false,"replicas":1}}'
kubectl -n app get networkpolicy,pdb

Expected:

notesapp.lab.example.com/notes patched
No resources found in app namespace.

Both conditions are false, and kro has deleted both objects. The ApplySet from Day 1 tells kro which objects it has created. Whatever no longer belongs in the graph gets thrown out.

Save your progress? Sign up for free

Checkpoint

kubectl get rgd notesapp

Expected: STATE Active.

kubectl -n app patch notesapp notes --type merge -p '{"spec":{"networkPolicy":true}}'
kubectl -n app get networkpolicy

Expected:

notesapp.lab.example.com/notes patched
NAME       POD-SELECTOR   AGE
notes-db   app=notes-db   3s

The NetworkPolicy stays turned on from now on.

diff notesapp-rgd.yaml ~/kro-lab/code/loesung/tag07/notesapp-rgd.yaml

Expected: no output.

Challenge

In namespaces whose name starts with prod, the NetworkPolicy should always apply, no matter what the team sets. What is the condition?

Note: schema.metadata.namespace and the string function startsWith.

Solution

      includeWhen:
        - ${schema.spec.networkPolicy || schema.metadata.namespace.startsWith("prod")}

One condition with || instead of two entries, because multiple entries are combined with AND. You don’t need to apply this; the fleet on Day 10 uses the switch.

Save your progress? Sign up for free

Enterprise Note

  • Secure by default: In a real platform, networkPolicy would default to true, or there would be no switch at all. Anyone who needs an exception asks for it.
  • Policies don’t belong only in the RGD: Kyverno or ValidatingAdmissionPolicies enforce rules for all objects, including those not created via kro. See “Kyverno & NetworkPolicies hands-on”.
  • Careful when removing: If an object drops out via includeWhen, kro really deletes it. For volumes or databases, the deletion policy from Day 6 therefore belongs with it.