Docker & Kubernetes
Challenge - OPA
Write a policy with Rego.
Challenge: banning latest
In this challenge you'll write a Gatekeeper policy that bans images tagged latest or with no tag. The rule will apply to pods; it will only warn first, and reject once violations are cleared:
nginx -> violation (no tag, counts as latest)
nginx:latest -> violation
nginx:1.27 -> fine
ghcr.io/sirket/api@sha256:… -> fine
In Rego you'll use the built-in functions endswith and contains.
Exercise Rego rules
Write the Rego code: package k8slatestyasak; two violation[{"msg": msg}] rules. The first: c := input.review.object.spec.containers[_], endswith(c.image, ":latest"), msg := sprintf("latest yasak: %v", [c.image]). The second, with the same c: not contains(c.image, ":"), msg := sprintf("etiket yok: %v", [c.image]).
Show example solution
package k8slatestyasak
violation[{"msg": msg}] {
c := input.review.object.spec.containers[_]
endswith(c.image, ":latest")
msg := sprintf("latest yasak: %v", [c.image])
}
violation[{"msg": msg}] {
c := input.review.object.spec.containers[_]
not contains(c.image, ":")
msg := sprintf("etiket yok: %v", [c.image])
}
Exercise Warn first
Write a K8sLatestYasak Constraint YAML: constraints.gatekeeper.sh/v1beta1; name latest-yasak; enforcementAction: warn; under match.kinds, apiGroups: [""], kinds: ["Pod"]; excludedNamespaces: ["kube-system"].
Show example solution
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sLatestYasak
metadata:
name: latest-yasak
spec:
enforcementAction: warn
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
excludedNamespaces: ["kube-system"]
Test yourself
-
What happens if two violation rules with the same name are written in Rego?
- Both must fire (AND)
- Violations merge; a violation appears if either fires (OR)
- A compile error
- Only the second runs
Show answer
Violations merge; a violation appears if either fires (OR) — Lines inside a rule mean AND, rules with the same name mean OR.
-
Check whether the image ends with latest.
____(c.image, ":latest")
Show answer
endswith(c.image, ":latest")
-
Match.
- endswith
- Check the end
- contains
- Does it contain
- warn
- Warn first
- deny
- Then reject
Next lesson: Challenge - Expert project