CodeBlanks Logo Icon CodeBlanks

The Rego language

Learn the Rego policy language.

The Rego language

OPA policies are written in the Rego language. Rego is declarative: a rule fires if all the expressions inside it are true. In Gatekeeper, violations are produced with the violation rule; the object under review is in input.review.object:

package image_kaynagi

violation[{"msg": msg}] {
  c := input.review.object.spec.template.spec.containers[_]
  not startswith(c.image, "ghcr.io/sirket/")
  msg := sprintf("izinsiz image: %v", [c.image])
}

[_] tries the rule for each element of the array; not negates; := assigns a variable.

Testing Rego locally

opa eval runs a policy locally with a sample input; opa test runs unit tests written in Rego. Policies are tested this way before going to the cluster:

$ opa eval -d politika.rego -i girdi.json "data.image_kaynagi.violation"
{"result": [{"expressions": [{"value": [{"msg": "izinsiz image: nginx:1.27"}]}]}]}
$ opa test . -v
data.image_kaynagi.test_izinli_image: PASS (1.2ms)
data.image_kaynagi.test_izinsiz_image: PASS (0.9ms)

Practice Test the policy locally

Write two commands: run the query "data.image_kaynagi.violation" with opa eval using politika.rego and girdi.json (-d, -i); run the tests in the current folder verbosely (-v).

Starter code

terminal
# buraya yaz

Sample solution

terminal
opa eval -d politika.rego -i girdi.json "data.image_kaynagi.violation"
opa test . -v

Expected output

{"result": [{"expressions": [{"value": [{"msg": "izinsiz image: nginx:1.27"}]}]}]}
data.image_kaynagi.test_izinli_image: PASS (1.2ms)
data.image_kaynagi.test_izinsiz_image: PASS (0.9ms)
PASS: 2/2

Questions and answers

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

1 How many violations does the rule above produce if one of two containers uses an unauthorized image?

  • 1 Correct answer
  • 2
  • 0
  • It errors

Explanation: The rule is tried separately for each container; a violation appears only for the one meeting the condition.

2 Try every container in the array.

Question
  c := input.review.object.spec.template.spec.containers[____]
Answer
  c := input.review.object.spec.template.spec.containers[_]

Explanation: _ is an anonymous variable; the rule is tried for every index.

3 Match.

Term Meaning
violation Violation rule
input.review.object Object under review
not Negation
opa test Unit tests

All lessons in Expert