CodeBlanks Logo Icon CodeBlanks

Summary - OPA

Combine Rego and ConstraintTemplate to write a policy.

Summary: OPA

In this group:

  • OPA separates policies from code; in Kubernetes it checks object content in the admission stage (RBAC checks who, OPA checks content).
  • Rego: violation rules, input.review.object, [_], not; tested locally with opa eval and opa test.
  • Gatekeeper: stops new requests with admission and reports existing violations with the audit.
  • A ConstraintTemplate defines the logic and parameter definition, a Constraint the targets (match) and parameters.
  • enforcementAction: gradual rollout with dryrun → warn → deny; system namespaces are excluded.
kubectl get constrainttemplates
kubectl get constraints

Practice Move from warn to deny

Write three commands: list all Constraints; apply the patch {"spec":{"enforcementAction":"deny"}} to the deployment-etiketleri (k8szorunluetiket) Constraint with --type=merge; try creating a deneme deployment with the nginx:1.27 image in magaza with --dry-run=server.

Starter code

terminal
# buraya yaz

Sample solution

terminal
kubectl get constraints
kubectl patch k8szorunluetiket deployment-etiketleri --type=merge -p '{"spec":{"enforcementAction":"deny"}}'
kubectl create deployment deneme --image=nginx:1.27 -n magaza --dry-run=server

Expected output

NAME                    ENFORCEMENT-ACTION   TOTAL-VIOLATIONS
deployment-etiketleri   warn                 0
k8szorunluetiket.constraints.gatekeeper.sh/deployment-etiketleri patched
error: admission webhook "validation.gatekeeper.sh" denied the request: [deployment-etiketleri] eksik etiket: takim

Questions and answers

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

1 Which lists all Constraints regardless of their types?

  • kubectl get constraints Correct answer
  • kubectl get policies
  • kubectl get rego
  • kubectl get admission

Explanation: Gatekeeper gathers all Constraint types in the constraints category.

2 Specify the target object type.

Question
  match:
    ____:
      - apiGroups: ["apps"]
        kinds: ["Deployment"]
Answer
  match:
    kinds:
      - apiGroups: ["apps"]
        kinds: ["Deployment"]

Explanation: match.kinds is a list of API groups and kinds.

3 Match.

Term Meaning
Rego Policy language
ConstraintTemplate Logic
Constraint Application
audit Existing violations

All lessons in Expert