Geavanceerd
Zoeken inInstallatiegidsen
Zo zoek je
  • Plak een foutmelding tussen aanhalingstekens, bijv. "permission denied", om de oplossingstabel te vinden.
  • Kies een gebied en een deel van de gids (installeren, eerste instellingen, dagelijks gebruik, beveiliging, oplossingen) om direct naar de juiste stap te gaan.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Gids 61Kyverno / OPA Gatekeeper · Security

Install and set up Kyverno (and know OPA Gatekeeper)

Policy engines check every object before it enters a Kubernetes cluster: "every Pod must have limits", "no latest tag", "only signed images from our registry", "no privileged containers". Kyverno writes these rules as Kubernetes YAML; OPA Gatekeeper writes them in the Rego language. Both run as admission webhooks. This guide installs Kyverno with Helm, writes validate, mutate and image-verify policies, starts in Audit mode and moves to Enforce, reads policy reports, and compares Gatekeeper and the built-in ValidatingAdmissionPolicy.

  • 10 Lessen
  • 4 Commando's

Dit deel is nog niet vertaald. Je ziet de Engelse tekst.

$ als gewone gebruiker# als root (of met sudo)

61.1

Know it before you install

When someone creates or changes an object, the API server asks the policy engine (an admission webhook). A policy can validate (allow or deny), mutate (add or change fields), generate (create other objects) or verify images (check signatures). Audit mode only reports; Enforce blocks. Background scans write PolicyReports for objects that already exist.

ItemKyvernoOPA Gatekeeper
Rules written inYAML (with patterns, CEL and JMESPath)Rego (ConstraintTemplate) + YAML (Constraint)
InstallHelm chart kyverno/kyvernoHelm chart gatekeeper/gatekeeper
Namespacekyvernogatekeeper-system
ObjectsClusterPolicy, Policy, PolicyException, PolicyReportConstraintTemplate, constraints
Image signaturesbuilt in (verifyImages, Cosign/Notary)with extra tools

Also built into Kubernetes (GA since 1.30): ValidatingAdmissionPolicy with CEL — good for simple rules without an extra engine.

61.2

Install Kyverno with Helm

Use at least 3 replicas of the admission controller in production (the webhook must always answer):

helm repo add kyverno https://kyverno.github.io/kyverno/
helm repo update
helm upgrade --install kyverno kyverno/kyverno -n kyverno --create-namespace --set admissionController.replicas=3 --set backgroundController.replicas=2 --set cleanupController.replicas=2 --set reportsController.replicas=2 --wait
kubectl -n kyverno get pods
kubectl get validatingwebhookconfigurations | grep kyverno

Optional: the ready Pod Security policy set (baseline/restricted) in Audit mode:

helm upgrade --install kyverno-policies kyverno/kyverno-policies -n kyverno --set podSecurityStandard=restricted --set validationFailureAction=Audit

The Kyverno CLI tests policies without a cluster: download kyverno from the GitHub releases (or kubectl krew install kyverno).

61.3

First configuration: your first policies (Audit)

Three rules every cluster needs — no latest tag, resource limits, and a team label:

policies/basics.yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: basics
  annotations:
    policies.kyverno.io/description: "No latest tag, limits required, team label required."
spec:
  background: true
  rules:
    - name: no-latest-tag
      match:
        any:
          - resources: { kinds: [Pod] }
      validate:
        failureAction: Audit
        message: "Use a fixed image tag, not ':latest' or no tag."
        pattern:
          spec:
            containers:
              - image: "!*:latest & *:*"
    - name: require-limits
      match:
        any:
          - resources: { kinds: [Pod] }
      validate:
        failureAction: Audit
        message: "CPU and memory limits are required."
        pattern:
          spec:
            containers:
              - resources:
                  limits:
                    memory: "?*"
                    cpu: "?*"
    - name: require-team-label
      match:
        any:
          - resources: { kinds: [Deployment, StatefulSet] }
      exclude:
        any:
          - resources: { namespaces: [kube-system, kyverno] }
      validate:
        failureAction: Audit
        message: "The label 'team' is required."
        pattern:
          metadata:
            labels:
              team: "?*"

A mutate policy (add a safe default) and an image signature check (only Cosign-signed images from your registry):

policies/defaults-and-signing.yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: default-no-privilege-escalation
spec:
  rules:
    - name: add-allowPrivilegeEscalation-false
      match:
        any:
          - resources: { kinds: [Pod] }
      mutate:
        patchStrategicMerge:
          spec:
            containers:
              - (name): "*"
                securityContext:
                  +(allowPrivilegeEscalation): false
---
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: verify-signed-images
spec:
  webhookTimeoutSeconds: 30
  rules:
    - name: cosign-keyless
      match:
        any:
          - resources: { kinds: [Pod] }
      verifyImages:
        - imageReferences: ["harbor.example.com/shop/*"]
          failureAction: Audit
          attestors:
            - entries:
                - keyless:
                    subject: "https://github.com/ORG/shop/.github/workflows/release.yml@refs/heads/main"
                    issuer: "https://token.actions.githubusercontent.com"
kubectl apply -f policies/
kubectl get clusterpolicy
NAME                             ADMISSION   BACKGROUND   READY
basics                           true        true         True

Test a policy locally first (also in CI for your YAML):

kyverno apply policies/basics.yaml --resource k8s/deployment.yaml
kyverno test ./policy-tests/

61.4

Read reports, then enforce

kubectl get policyreport -A
kubectl get clusterpolicyreport
kubectl -n shop get policyreport -o yaml | grep -B2 -A6 'result: fail'

When the reports show (almost) no failures, switch the rules to failureAction: Enforce and apply again. For a real, approved exception, use a PolicyException for that workload instead of weakening the policy.

kubectl -n shop run test --image=nginx:latest
Error from server: admission webhook "validate.kyverno.svc-fail" denied the request: … no-latest-tag: Use a fixed image tag …

61.5

OPA Gatekeeper in short

Gatekeeper splits a rule into a ConstraintTemplate (Rego logic) and a Constraint (where and with which parameters). Install with helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts and helm install gatekeeper gatekeeper/gatekeeper -n gatekeeper-system --create-namespace. A constraint that uses a template from the Gatekeeper library:

required-labels-constraint.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: deployments-need-team
spec:
  enforcementAction: dryrun
  match:
    kinds:
      - apiGroups: ["apps"]
        kinds: ["Deployment"]
  parameters:
    labels: ["team"]

enforcementAction: dryrun = audit only; deny = block. Results: kubectl get k8srequiredlabels deployments-need-team -o yaml (status.violations). Choose Gatekeeper when your company already uses OPA/Rego elsewhere; Kyverno when you want pure YAML and image verification built in.

61.6

Daily use: the commands and the real uses

kubectl get clusterpolicy,policy -A
kubectl get policyreport -A -o wide
kubectl get policyexception -A
kubectl -n kyverno logs deploy/kyverno-admission-controller --tail 50
kyverno apply policies/ --resource rendered.yaml
helm template ./chart | kyverno apply policies/ --resource -

Real uses at work:

  • Guardrails for all teams: Pod Security, limits, labels, allowed registries.
  • Supply-chain gate: only signed images (Cosign) and images with an SBOM attestation.
  • Defaults by mutation (security context, labels); generate a default NetworkPolicy for each new namespace.

61.7

Make it safe

Security checklist:

  • Start in Audit, read reports, then Enforce — never surprise teams with blocks.
  • Run 3 admission replicas with a PodDisruptionBudget; the webhook must stay up.
  • Exclude system namespaces carefully; keep exceptions small, named and reviewed (PolicyException).
  • Policies in Git (GitOps) with tests (kyverno test) in CI.
  • Limit who may change policies and exceptions (RBAC).
  • Keep Kyverno/Gatekeeper updated and check the webhook failurePolicy (Fail = safe, Ignore = available).

61.8

Update and remove

helm repo update
helm upgrade kyverno kyverno/kyverno -n kyverno --reuse-values --wait
helm uninstall kyverno -n kyverno

Remove policies before you uninstall, and check that no webhook configuration is left (kubectl get validatingwebhookconfigurations) — a dead webhook can block the whole cluster.

61.9

Fix common problems

ProblemCauseFix
All creates fail: failed calling webhook "validate.kyverno.svc…": context deadline exceededKyverno Pods down or not reachable.Check kubectl -n kyverno get pods; network policies to the webhook; more replicas.
Policy is READY FalseError in the policy.kubectl describe clusterpolicy NAME; test with kyverno apply.
A valid Pod is blockedPattern too strict (for example init containers, sidecars).Fix the pattern; add a PolicyException; check with kyverno apply.
No PolicyReportsBackground scans off or reports controller down.background: true; check the reports controller Pod.
verifyImages denies a signed imageWrong subject/issuer or the image is referenced by a different name.Compare with cosign verify output; use digests.
Gatekeeper constraint shows no violationsWrong match or still syncing.Check match.kinds; wait for audit interval; kubectl get constrainttemplates.

61.10

Next steps

1Why start Kyverno policies with failureAction: Audit?

To see in PolicyReports what would be blocked before blocking anything.

2What is the difference between Kyverno and Gatekeeper rules?

Kyverno rules are YAML patterns; Gatekeeper rules are written in Rego (ConstraintTemplates) with YAML constraints.

Alle commando's in dit hoofdstuk