Sub topic 4
Kyverno validate rules
This chapter assumes you know Pods, labels and namespaces, can read YAML, and understand that the API server calls admission webhooks before it stores an object. Kyverno is the policy engine that registers those webhooks. A validate rule is the part of a policy that accepts or rejects a request.
What a validate rule does
When a request matches the rule, Kyverno checks the resource against the rule's condition. If the check fails, the API server rejects the request and returns your message to the user. Validation never changes the resource. Changing resources is the job of mutate rules, which come later.
A worked example
This ClusterPolicy rejects Pods that have no non-empty team label.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-team-label
spec:
validationFailureAction: Enforce
background: true
rules:
- name: check-team-label
match:
any:
- resources:
kinds:
- Pod
validate:
message: "The label 'team' is required."
pattern:
metadata:
labels:
team: "?*"The parts work like this:
validationFailureAction: Enforceblocks violating requests. The other value,Audit, allows them and records the violation in a report.background: truealso scans resources that already exist, so you can find violations that predate the policy.matchselects which resources the rule applies to. Here it selects Pods.messageis the text the user sees when the request is denied.patternis an overlay. Kyverno compares it to the resource field by field.
The value "?*" is a wildcard. ? matches one character and * matches any number of characters, so together they mean "at least one character". A missing label fails, and so does an empty one.
Request flow
Test it
Check the policy against a local manifest first. This does not touch a cluster.
kyverno apply require-team-label.yaml --resource pod.yamlThe command prints a pass or fail result for each rule.
Common errors
- Policy matches Pods only. A Deployment is accepted if it has no
teamlabel on the Deployment itself, because the rule matches only Pods. Kyverno auto-generates rules for Pod controllers such as Deployments, but it applies them to the Pod template. Confirm that behavior in your Kyverno version. - Enforcing too early. Existing workloads are not blocked, but their next update can be. Start with
Audit, read the reports, then switch toEnforce. - Vague messages. A message such as "denied" gives users nothing to act on. Say which field is wrong and what value is expected.
Exercise
A Pod is created with the label team: "". Does require-team-label accept it? Explain why.
Show answer
No. The pattern "?*" needs at least one character, so an empty string fails. The request is rejected and the user sees "The label 'team' is required." because validationFailureAction is Enforce.