TExcelTAD
Home › Secrets & Policy as Code: Vault, SOPS, OPA & Conftest › In the Cluster: Kyverno & Gatekeeper

In the Cluster: Kyverno & Gatekeeper

CI checks run on what the pipeline renders. Admission control runs on what actually reaches the Kubernetes API, including a kubectl apply from someone's laptop. The mechanism (mutating and validating webhooks, ValidatingAdmissionPolicy with CEL) is covered in Admission Controllers, and image-signature policies in Admission Control: Kyverno & policy-controller. This lesson is about the policy engines themselves and about testing their policies offline, so CI and the cluster enforce the same rules.

Kyverno

Kyverno policies are Kubernetes resources. In current Kyverno (1.19 in this sandbox) the recommended types live in policies.kyverno.io: ValidatingPolicy, MutatingPolicy, GeneratingPolicy and ImageValidatingPolicy, written with CEL expressions, the same language as Kubernetes' own ValidatingAdmissionPolicy. The older kyverno.io/v1 ClusterPolicy with YAML patterns still works but is deprecated, as the CLI tells you:

bash · try it yourself
cat > old.yaml <<'YAML'
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata: {name: require-team-label}
spec:
  validationFailureAction: Enforce
  rules:
    - name: check-team
      match: {any: [{resources: {kinds: [Deployment]}}]}
      validate:
        message: "label 'team' is required"
        pattern: {metadata: {labels: {team: "?*"}}}
YAML
cat > d.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata: {name: linkly, labels: {team: links}}
spec:
  selector: {matchLabels: {app: linkly}}
  template:
    metadata: {labels: {app: linkly}}
    spec: {containers: [{name: app, image: ghcr.io/acme/linkly:1.4.2}]}
YAML
kyverno apply old.yaml --resource d.yaml --remove-color 2>&1 | fold -s -w 110
Warning: old.yaml: 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/

Applying 1 policy rule(s) to 1 resource(s)...

pass: 1, fail: 0, warn: 0, error: 0, skip: 0

A ValidatingPolicy, applied and tested offline

bash · try it yourself
mkdir k && cd k
cat > policy.yaml <<'YAML'
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: linkly-pod-security
spec:
  validationActions: [Deny]          # Audit or Warn while rolling out
  matchConstraints:
    resourceRules:
      - apiGroups: [apps]
        apiVersions: [v1]
        operations: [CREATE, UPDATE]
        resources: [deployments]
  validations:
    - expression: "object.spec.template.spec.?securityContext.?runAsNonRoot.orValue(false) == true"
      message: "pods must set securityContext.runAsNonRoot: true"
    - expression: "object.spec.template.spec.containers.all(c, !c.image.endsWith(':latest'))"
      message: "images must not use :latest"
YAML
cat > resources.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata: {name: linkly, namespace: linkly}
spec:
  selector: {matchLabels: {app: linkly}}
  template:
    metadata: {labels: {app: linkly}}
    spec:
      securityContext: {runAsNonRoot: true}
      containers: [{name: app, image: ghcr.io/acme/linkly:1.4.2}]
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: preview, namespace: linkly}
spec:
  selector: {matchLabels: {app: preview}}
  template:
    metadata: {labels: {app: preview}}
    spec:
      securityContext: {runAsNonRoot: true}
      containers: [{name: app, image: ghcr.io/acme/preview:latest}]
YAML
echo "### kyverno apply: what would admission say?"
kyverno apply policy.yaml --resource resources.yaml --remove-color; echo "exit $?"

cat > kyverno-test.yaml <<'YAML'
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
  name: linkly-pod-security
policies: [policy.yaml]
resources: [resources.yaml]
results:
  - policy: linkly-pod-security
    kind: Deployment
    resources: [linkly]
    result: pass
  - policy: linkly-pod-security
    kind: Deployment
    resources: [preview]
    result: fail
YAML
echo "### kyverno test: does the policy behave as expected?"
kyverno test . --remove-color | grep -vE '^  (Loading|Applying|Checking)'
### kyverno apply: what would admission say?

Applying 1 policy rule(s) to 2 resource(s)...
policy linkly-pod-security -> resource linkly/Deployment/preview failed:
1 -  images must not use :latest

pass: 1, fail: 1, warn: 0, error: 0, skip: 0
exit 1
### kyverno test: does the policy behave as expected?
Loading test  ( kyverno-test.yaml ) ...

│────│─────────────────────│──────│───────────────────────────────────│────────│────────│
│ ID │ POLICY              │ RULE │ RESOURCE                          │ RESULT │ REASON │
│────│─────────────────────│──────│───────────────────────────────────│────────│────────│
│ 1  │ linkly-pod-security │      │ apps/v1/Deployment/linkly/linkly  │ Pass   │ Ok     │
│ 2  │ linkly-pod-security │      │ apps/v1/Deployment/linkly/preview │ Pass   │ Ok     │
│────│─────────────────────│──────│───────────────────────────────────│────────│────────│


Test Summary: 2 tests passed and 0 tests failed
  • kyverno apply answers "would these manifests be admitted?": the CI gate for rendered manifests.
  • kyverno test answers "does the policy do what we think?": expected results per resource, the Kyverno counterpart of opa test. A fail result that is expected counts as a passing test.
  • The ?. and orValue() in the CEL expression handle missing fields; without them a Deployment with no securityContext would produce an evaluation error instead of a clean denial.

In the cluster, start with validationActions: [Audit] (violations show up in PolicyReports), then [Warn], then [Deny], and exclude system namespaces.

OPA Gatekeeper

Gatekeeper brings Rego into admission. A ConstraintTemplate defines a new policy kind with Rego and a parameter schema; Constraints instantiate it with parameters and a scope:

yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8sallowedregistries
spec:
  crd:
    spec:
      names:
        kind: K8sAllowedRegistries
      validation:
        openAPIV3Schema:
          type: object
          properties:
            registries:
              type: array
              items: {type: string}
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8sallowedregistries

        import rego.v1

        violation contains {"msg": msg} if {
          some c in input.review.object.spec.containers
          not allowed(c.image)
          msg := sprintf("image %v is not from an allowed registry", [c.image])
        }

        allowed(image) if {
          some prefix in input.parameters.registries
          startswith(image, prefix)
        }
---
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRegistries
metadata:
  name: linkly-registries
spec:
  enforcementAction: dryrun        # dryrun -> warn -> deny
  match:
    kinds: [{apiGroups: [""], kinds: [Pod]}]
    namespaces: [linkly]
  parameters:
    registries: ["ghcr.io/acme/", "registry.acme.internal/"]
  • Gatekeeper's input is the AdmissionReview: the object is at input.review.object, parameters at input.parameters. The rule must be called violation and produce objects with msg.
  • import rego.v1 lets the v1 syntax used in this course parse in Gatekeeper versions whose default is still v0; check the documentation of the version you install.
  • Audit periodically evaluates existing objects and records violations in each constraint's status.
  • Test offline with Gatekeeper's gator CLI: gator test -f templates/ -f constraints/ -f manifests/ evaluates manifests like the admission webhook would, and gator verify suites/ runs test suites with expected violations. (Not in this course's sandbox; the commands are a sample.)
text
$ gator test -f template.yaml -f constraint.yaml -f pod.yaml
linkly/debug: ["linkly-registries"] Message: "image docker.io/library/busybox:1.37 is not from an allowed registry"

The Gatekeeper project also publishes a policy library of ready-made templates (allowed repos, required labels, privileged containers, and the Pod Security Standards).

Kyverno or Gatekeeper?

Kyverno Gatekeeper
Language CEL (and legacy YAML patterns) Rego
Scope Kubernetes, plus kyverno-json for arbitrary JSON Kubernetes; the same Rego runs in OPA and Conftest
Mutation and generation rich (MutatingPolicy, GeneratingPolicy) mutation via Assign/ModifySet; no generation
Image verification built in (ImageValidatingPolicy) via external data providers (e.g. Ratify)
Offline testing kyverno apply, kyverno test gator test, gator verify

If your CI already runs Rego with Conftest on Terraform plans, Gatekeeper lets one policy language cover both. If your team lives in YAML and wants mutation and generation, Kyverno is usually simpler. Built-in ValidatingAdmissionPolicy (CEL, no webhook) is enough for many simple rules and is the direction Kyverno's new policy types follow.

Test yourself

What does kyverno test check that kyverno apply doesn't?

  1. Image signatures
  2. That each resource gets the result you declared in kyverno-test.yaml, including expected failures
  3. Cluster connectivity
  4. Rego syntax

In a Gatekeeper ConstraintTemplate, where is the object being admitted?

  1. input.object
  2. input.review.object
  3. data.object
  4. input.request

What is a safe rollout order for a new admission policy?

  1. Deny immediately
  2. Audit or dryrun first, then warn, then deny, excluding system namespaces
  3. Warn forever
  4. Only in production