Rego is the declarative policy language used by Open Policy Agent (OPA) for writing and enforcing policies across cloud-native stacks, featuring data-driven rules, comprehensions, and 200+ built-in functions for infrastructure, security, and compliance automation.
Overall
score
97%
Create a Terraform plan validation policy in Rego that enforces security and compliance rules across both raw Terraform and HCP Terraform/Enterprise input structures.
Create terraform.rego with package terraform.validation and import rego.v1.
Critical: normalize the input structure first.
The plan JSON input differs depending on how OPA is invoked:
terraform show -json): resource_changes is at input.resource_changesinput.plan, so resource_changes is at input.plan.resource_changesAlways normalize with object.get so the policy works in both contexts:
tfplan := object.get(input, "plan", input)All subsequent rules must reference tfplan.resource_changes, never input.resource_changes directly.
Define a multi-value deny rule (a set of strings). Each violation must produce a distinct, human-readable message.
Implement the following checks:
1. S3 bucket encryption
All aws_s3_bucket resources being created or updated must have server_side_encryption_configuration set. Check for both "create" and "update" actions. Do not check "delete" actions. Violation message:
S3 bucket <address> does not have server-side encryption enabled2. Required environment tag
All AWS resources (any type beginning with "aws_") being created or updated must have an "Environment" key in change.after.tags. Check for both "create" and "update" actions. Do not check "delete" actions. Violation message:
resource <address> is missing the required Environment tagCreate terraform_test.rego with package terraform.validation_test and import rego.v1.
Do not run terraform plan or any Terraform CLI commands. All test inputs must be mock plan JSON objects injected with the with input as { ... } keyword.
Include tests for:
Environment tag) — deny must be an empty setaws_s3_bucket missing encryption on a create action — deny must contain the encryption messageaws_s3_bucket missing encryption on an update action — deny must contain the encryption messageEnvironment tag — deny must contain the tagging messagedeny must be an empty set (delete actions are not checked)input.plan) — policy must still evaluate correctlyRun opa test . -v and confirm all tests pass.