I am trying to write a policy where I want to enforce tags to exist on AWS resources using Open Policy Agent (OPA). I am attempting to parse the JSON output of a run of terraform plan
in order to enforce policies on new resources in the root module.
So far, I have a simple filter set up that works just fine:
filter_taggable_resources = filtered {
...
}
The list of tags I want to validate is pretty simple:
required_tags := {"foo", "bar", "baz"}
In my validataion
area, I want to:
- make sure the resource has tags actually defined
- make sure that the required tags are present
- allow for any additional tags to be set on top of the required ones
I was hoping to set up something like this (pardon the pseudo-code, I am very new at OPA Rego):
get_missing_tags(resource) = missing_tags {
missing_tags := required_tags
resource_tags := resource.values.tags
# if resource_tags is null - fail and return all tags
resource_tags != null
# if we got this far, run a diff and return the tags
missing_tags = required_tags - resource_tags
}
violation[msg] {
filtered := filter_taggable_resources
resource := filtered[_]
missing_tags := get_missing_tags(resource)
count(missing_tags) != 0
msg = sprintf("My error message: %v", [concat(", ", missing_tags)])
}
I believe I am completely missing some concepts figuring this out and cannot get it to return properly. I do NOT want it to fail fast and I want it to loop over all resources and give me errors for each and every one. I want to expand this later to check for valid values for the tags, but I want to solve the more simple problem first.
My core problem is that I am only getting an error if tags exist. If I have the following resources:
resource "aws_instance" "bla1" {
ami = local.some_ami
instance_type = "t2.micro"
}
resource "aws_instance" "bla2" {
ami = local.some_ami
instance_type = "t2.micro"
tags = { Name = "IHaveATagButNotAll" }
}
I only get errors for aws_instance.bla2
in my output and nothing for aws_instance.bla1
, even though it doesn’t have any tags. How can I set this up?
My execution is:
conftest test /path/to/tfplan.json
--policy /path/to/policies
--all-namespaces
--fail-on-warn
--show-builtin-errors
--strict
With:
- Conftest: v0.52.0
- OPA: 0.64.1