Sub topic 15
Testing policies before enforcing them
This chapter assumes you can read Kyverno and Gatekeeper policies, know the difference between enforcing and auditing, and can use kubectl. A policy that rejects the wrong Pods can block deployments across a whole cluster. You test a policy in three stages: offline, in audit mode, and then enforced.
Stage 1: test offline
Offline tests run against local files and never touch a cluster. They are fast and fit well in CI.
The Kyverno CLI applies a policy to a resource manifest:
kyverno apply require-team-label.yaml --resource pod.yamlThe output lists each resource with a pass or fail result for each rule. Run it against one manifest that should pass and one that should fail. A policy you have only seen pass is not tested.
Kyverno also has kyverno test, which reads a kyverno-test.yaml file. That file lists the policy, the resources, and the result you expect for each rule. It lets you keep expected outcomes in version control.
Gatekeeper policies are Rego, so you can test the Rego with the gator CLI. gator verify runs test suites that pair a template and constraint with sample objects and the expected violations. You can also use opa test on the Rego alone.
Stage 2: test in audit mode
Offline tests use the samples you thought of. Real clusters contain objects you did not think of. Deploy the policy in a non-blocking mode first:
- Kyverno: set
validationFailureAction: Audit. Violations appear in policy reports. - Gatekeeper: set
enforcementAction: dryrun(orwarn) on the Constraint. Violations appear in the Constraint'sstatus.violations.
kubectl get policyreport -A
kubectl get k8srequiredlabels pods-must-have-team -o yamlRead the results. Each violation is either a real problem to fix or a sign that the policy is too broad. Narrow the match block or add exclusions until the remaining violations are ones you want.
Stage 3: enforce
Switch to Enforce (Kyverno) or deny (Gatekeeper) only when audit shows no unexpected violations. Roll out to one namespace first if you can.
Common mistakes
- Testing only the passing case.
- Skipping audit and finding existing workloads that violate the policy only after they fail to restart.
- Forgetting that a policy applies to Pods created by controllers. A Deployment can look fine while its Pods are rejected.
- Not re-running tests when the policy changes.
Exercise
You wrote a Gatekeeper Constraint that requires a team label. Which setting lets you see what it would block without blocking anything, and where do you read the results?
Show answer
Set enforcementAction: dryrun on the Constraint. Read the violations in the Constraint's status.violations, for example with kubectl get k8srequiredlabels pods-must-have-team -o yaml.