Docker & Kubernetes
ConstraintTemplate
Learn to define policies with a ConstraintTemplate.
ConstraintTemplate
A ConstraintTemplate defines a new Constraint type (CRD) and contains the Rego logic. crd.spec.names.kind is the name of the Constraint type to be created, validation the parameter definition, and targets[].rego the policy code:
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8szorunluetiket
spec:
crd:
spec:
names:
kind: K8sZorunluEtiket
validation:
openAPIV3Schema:
type: object
properties:
etiketler:
type: array
items: {type: string}
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8szorunluetiket
violation[{"msg": msg}] {
gerekli := input.parameters.etiketler[_]
not input.review.object.metadata.labels[gerekli]
msg := sprintf("eksik etiket: %v", [gerekli])
}
Parameters
Keeping the template generic and leaving the details to the Constraint lets the same logic be used in different places with different settings. In Rego, the parameters are under input.parameters:
gerekli := input.parameters.etiketler[_] # ["takim", "ortam"]
not input.review.object.metadata.labels[gerekli]
For example, the same template can require the [takim, ortam] labels on deployments and [sahip] on namespaces.
Exercise An image-source template
Write a ConstraintTemplate's targets section (starting with targets:): target: admission.k8s.gatekeeper.sh; under rego: |, package k8sizinliregistry and a rule producing violation[{"msg": msg}] if the container image doesn't start with input.parameters.onek (c := input.review.object.spec.containers[_], not startswith(c.image, input.parameters.onek), msg := sprintf("izinsiz image: %v", [c.image])).
Show example solution
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sizinliregistry
violation[{"msg": msg}] {
c := input.review.object.spec.containers[_]
not startswith(c.image, input.parameters.onek)
msg := sprintf("izinsiz image: %v", [c.image])
}
Test yourself
-
After this template is applied, which new type appears in the cluster?
- Policy
- Rego
- K8sZorunluEtiket
- ConstraintTemplate
Show answer
K8sZorunluEtiket — Gatekeeper produces a CRD from the template; Constraints are written in this type.
-
Read the Constraint's parameters in Rego.
gerekli := input.____.etiketler[_]
Show answer
gerekli := input.parameters.etiketler[_]
-
Match.
- crd.spec.names.kind
- New Constraint type
- validation
- Parameter definition
- targets[].rego
- Policy code
- input.parameters
- Constraint settings
Next lesson: Constraint