CodeBlanks Logo Icon CodeBlanks

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.

Practice 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]).

Starter code

terminal
# buraya yaz

Sample solution

terminal
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])
}

Expected output

$ opa eval -d latest.rego -i pod.json "data.k8slatestyasak.violation"
{"result": [{"expressions": [{"value": [{"msg": "etiket yok: nginx"}]}]}]}

Practice 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"].

Starter code

terminal
# buraya yaz

Sample solution

terminal
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sLatestYasak
metadata:
  name: latest-yasak
spec:
  enforcementAction: warn
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
    excludedNamespaces: ["kube-system"]

Expected output

k8slatestyasak.constraints.gatekeeper.sh/latest-yasak created
$ kubectl run deneme --image=nginx
Warning: [latest-yasak] etiket yok: nginx
pod/deneme created

Questions and answers

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

1 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) Correct answer
  • A compile error
  • Only the second runs

Explanation: Lines inside a rule mean AND, rules with the same name mean OR.

2 Check whether the image ends with latest.

Question
  ____(c.image, ":latest")
Answer
  endswith(c.image, ":latest")

Explanation: endswith checks the end of the string.

3 Match.

Term Meaning
endswith Check the end
contains Does it contain
warn Warn first
deny Then reject

All lessons in Expert