Docker & Kubernetes
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
Exercise 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"].
Show example solution
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"]
Test yourself
-
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
- Start directly with deny
- Apply it to kube-system too
Show answer
Start with dryrun or warn and switch to deny after clearing the violations — Going straight to deny can suddenly stop updates of existing deployments.
-
Set the policy to only warn.
spec:
enforcementAction: ____
Show answer
spec:
enforcementAction: warn
-
Match.
- deny
- Reject
- warn
- Warn, accept
- dryrun
- Audit only
- excludedNamespaces
- Excluded ones
Next lesson: Summary - OPA