OPA Rego rule to check annotation in k8s namespace with other rules

9/18/2020

I want to check if an annotation exist in a namespace, if not deny. I have this code but not working. How can I get the right object path ( namespace.annotation ) to compare to ?

  violation[{"msg": msg, "details": {}}] {
        input.request.kind.kind == "Namespace"
        not input.review.object.metadata.annotations.hostPath
        msg := sprintf("no hostpath defined in namespace for this pod %v, [input.review.object.metadata.name])
    }

I have both pod and namespace specified in my constrains since I need rules that check both in my template

spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
      - apiGroups: [""]
        kinds: ["Namespace"]

thanks !

-- mohbar
kubernetes
open-policy-agent
rego

1 Answer

9/19/2020

Check it out this nearly identical example from the gatekeeper library repository.
I think the specific issue is with the way you are extracting the annotation itself (notice the example is using square brackets while you are using a dot notation).

-- Yaron Idan
Source: StackOverflow