I am new with rego and I am finding it difficult to get my head around on how to write a policy. Based on information on the internet, I tried to write a policy to ensure that required tag keys and its values are present in the 'input' tfplan (terraform plan) . Using the code below, I can check if the required tag key are present in the input JSON, however I am not sure how to match values for this key.
Below is the input data for example (not putting the complete tfplan here):
"tags_all": {
"application": "app_name",
"billingcode": "12345",
"contact": "email_id",
"dept": "101",
"div": "22",
"domain": "data",
**"env": "dev"**,
"initiator": "some_name",
**"project": "abc"**
}
Below is the code
package tfplan
# The format to store required tags can be CHANGED, if needed
required_tags := {"tags": [
{"tagkey": "project", "tagvalue": ["abc","def"]},
{"tagkey": "env", "tagvalue": ["stage","prod"]},
]}
array_contains(arr, elem) {
arr[_] == elem
}
deny[reason] {
# reading tags from terraform plan
resource := input.resource_changes[_]
tags := resource.change.after.tags_all
existing_tags_keys := [ key | tags[key] ]
required_tag := required_tags.tags[_]
required_tag_key := required_tag.tagkey
required_tag_value := required_tag.tagvalue
not array_contains(existing_tags_keys, required_tag_key)
reason := sprintf(
"%s: missing required key %q and value %q",
[resource.address, required_tag_key, required_tag_value]
)
}
My expectation is that "env" and "project" from tags_all (input) should match the required_tags's key and the value for the matching key should exist in the list of values in required tags.
Can some one guide me on how to write this?
Question 2] In the above current code, if the Key matches, i see empty values in the result something like this:
{ "result": [
{
"expressions": [
{
"value": [],
"text": "data.tfplan.deny",
"location": {
"row": 1,
"col": 1
}
}
]
} ] }
How can I update the deny function to just return True or False in case of matching policy.