Skip to main content
In this lesson we use Kyverno preconditions to make a ClusterPolicy that only runs against Services of type NodePort. When the precondition is met, the policy validates that spec.externalTrafficPolicy is set to Local.
The image features the words "Preconditions" and "Demo" on a white and blue-green background, with a copyright notice for KodeKloud.
Goal
  • Validate Services only when spec.type is NodePort.
  • Enforce spec.externalTrafficPolicy: Local for those NodePort Services.
Preconditions are evaluated against the incoming admission request. If preconditions pass, the rule’s validate/mutate/generate actions run; otherwise the rule is skipped. Use preconditions to make policies highly selective and avoid unnecessary validation on unrelated resources.
Policy manifest (ClusterPolicy)
What this policy does
  • match narrows targets to Kubernetes Service resources.
  • preconditions further limit execution to Services whose spec.type equals NodePort.
  • When the precondition passes, the validate block enforces that spec.externalTrafficPolicy is Local.
  • If the precondition does not pass (for example, a ClusterIP Service), the rule is skipped.
Apply the policy
Verify the ClusterPolicy is ready
Example output:
Test cases We create three Service examples to demonstrate the policy behavior:
  1. Bad NodePort Service (should be rejected)
Expected admission webhook error:
The admission webhook will block creation when the policy’s validationFailureAction is enforce. Inspect Kyverno logs and events if an expected create is denied.
  1. Good NodePort Service (should be accepted)
Expected response:
  1. ClusterIP Service (precondition not met; policy skipped — should be accepted)
Expected response:
Summary and references

Watch Video

Practice Lab