rego to check for existance of a field in an array

2.9k views Asked by At

How could the existance of the "spec.rules.host" field in each item under "speck.rules" can be checked, in a way that if any of them do not have such entry, it would trigger a "deny"?

apiVersion: getambassador.io/v3alpha1
kind: FilterPolicy
metadata:
  name: multi-domain-policy
spec:
  rules:
  - host: foo.bar.com
    path: "*"
    filters:
      - name: foo-keycloak
  - host: example.com
    path: "*"
    filters:
      - name: example-auth0

For some reason I can't understand, this is not workin:

        violation[{"msg": msg}] {
          hostExists := input.review.object.spec.rules[_].host
          not hostExists
          msg := sprintf("This is the value: %v", [hostExists])
        }
1

There are 1 answers

0
Devoops On BEST ANSWER

You could use an array comprehension to collect rules where the host attribute is missing, then simply count those rules to see if there are any:

violation[{"msg": msg}] {
    rules_without_host := [rule | rule := input.review.object.spec.rules[_]; not rule.host]
    count(rules_without_host) > 0
    
    msg := sprintf("Rules missing host: %v", [rules_without_host])
}