0

I have 'JSON' file something like below, now i want to validate is label cat is set or not?

"labels": {
"apple": "one",
"banana": "two",
"cat": "three"
    }
      
check_against_targets(value, targets) {
    mode == "allowlist"
    match_mode == "regex"
    not my_regexp.match_name(value, targets)
}
check_labels(labels) {
    print(count(labels))
    count(labels) > 0
    some i
    check_against_targets(labels[i])
}

with above OPA test its only taking first label and not going through all labels to validate it.

any idea where i'm going wrong (I am quite new to OPA).

expected behaviour is should go through all labels and find CAT is their or not!

1 Answer 1

0

The example isn't complete, but I'll do my best to answer :) As soon as a function body evaluates, it'll return true unless a different return value has been defined. In your case you're using negation (i.e. not my_regexp.match_name(value, targets)) which naturally will be true as the first label does not match...

Adding to that, you're only passing one argument to check_against_targets which should take two, so I'm not sure what the expected outcome here would be? If you're only looking to answer whether the cat key is in the object or not, you could just do something like:

package p

import future.keywords.in

labels := {
    "apple": "one",
    "banana": "two",
    "cat": "three",
}

has_cat_key {
    "cat" in object.keys(labels)
}

If you have some custom function for validating keys, you'd use that without the negation:

package p

import future.keywords.in

labels := {
    "apple": "one",
    "banana": "two",
    "cat": "three",
}

# Check if *any* key matches
has_key_match {
    some key in object.keys(labels)
    my_matcher(key)
}

my_key_matcher(key) {
    # ... matching implementation here
}

If you want to validate that all keys match some criteria, you could use the every keyword.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.