CodeBlanks Logo Icon CodeBlanks

Constraint

Learn to enforce policies with a Constraint.

Constraint

A Constraint is an object of the type the template produces: it says to which objects (match) and with which parameters the policy applies. enforcementAction sets the behaviour: deny (reject), warn (warn but accept), dryrun (audit only):

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sZorunluEtiket
metadata:
  name: deployment-etiketleri
spec:
  enforcementAction: deny
  match:
    kinds:
      - apiGroups: ["apps"]
        kinds: ["Deployment"]
    excludedNamespaces: ["kube-system", "gatekeeper-system"]
  parameters:
    etiketler: ["takim", "ortam"]

Excluding system namespaces

Applying policies to system namespaces like kube-system can block updates of critical components; that's why they are excluded with excludedNamespaces. Gatekeeper's own config can also leave some namespaces out entirely:

$ kubectl create deployment deneme --image=nginx:1.27 -n magaza
error: admission webhook "validation.gatekeeper.sh" denied the request: [deployment-etiketleri] eksik etiket: takim
$ kubectl create deployment deneme --image=nginx:1.27 -n magaza --dry-run=server -o name
Warning: [deployment-etiketleri] eksik etiket: ortam     # if enforcementAction were warn

Practice Write a Constraint

Write a K8sZorunluEtiket Constraint YAML: constraints.gatekeeper.sh/v1beta1; name deployment-etiketleri; enforcementAction: deny; under match.kinds, apiGroups: ["apps"], kinds: ["Deployment"]; excludedNamespaces: ["kube-system"]; parameters.etiketler: ["takim", "ortam"].

Starter code

terminal
# buraya yaz

Sample solution

terminal
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sZorunluEtiket
metadata:
  name: deployment-etiketleri
spec:
  enforcementAction: deny
  match:
    kinds:
      - apiGroups: ["apps"]
        kinds: ["Deployment"]
    excludedNamespaces: ["kube-system"]
  parameters:
    etiketler: ["takim", "ortam"]

Expected output

k8szorunluetiket.constraints.gatekeeper.sh/deployment-etiketleri created

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the way to roll out a new policy safely in production?

  • Turn off the audit
  • Start with dryrun or warn and switch to deny after clearing the violations Correct answer
  • Start directly with deny
  • Apply it to kube-system too

Explanation: Going straight to deny can suddenly stop updates of existing deployments.

2 Set the policy to only warn.

Question
spec:
  enforcementAction: ____
Answer
spec:
  enforcementAction: warn

Explanation: warn accepts but returns a warning.

3 Match.

Term Meaning
deny Reject
warn Warn, accept
dryrun Audit only
excludedNamespaces Excluded ones

All lessons in Expert