Policy as Code for IaC, and Drift
The previous lesson ended with two serious problems the scanner's built-in rules didn't see: an IAM policy allowing every action, and a literal database password. Every organisation has rules like that, specific to its own risks: "no IAM wildcards", "databases only in the data subnets", "every bucket tagged with a data owner", "no resources outside eu-west-1". Policy as code writes those rules as versioned, tested code that runs in the same pipeline as the scanner. The second half of the lesson deals with the gap that no pre-deployment check can close: drift, the difference between what the code says and what the account contains after someone changes it by hand. Policy as Code and Rego Basics teach the Rego language with OPA and Conftest; here it runs inside Trivy as custom checks.
Custom checks in Rego
Trivy accepts custom checks written in Rego, the policy language of OPA. A check has a metadata header (ID, title, severity, which input type it reads) and deny rules that return results. With --raw-config-scanners terraform, Terraform checks receive the parsed HCL: modules, blocks with their type and name, and attributes with resolved values (including the JSON string produced by jsonencode). The two checks below close the gaps from the last lesson. The session runs in your sandbox on local files.
mkdir -p iac checks
cat > iac/main.tf <<'TF'
resource "aws_db_instance" "shop" {
identifier = "shop-db"
engine = "postgres"
instance_class = "db.t4g.micro"
username = "shop"
password = "Wq7!vR2#kd9Lp0sZ"
storage_encrypted = true
}
resource "aws_iam_policy" "ci" {
name = "ci-deploy"
policy = jsonencode({
Version = "2012-10-17"
Statement = [{ Effect = "Allow", Action = "*", Resource = "*" }]
})
}
resource "aws_iam_policy" "reports" {
name = "reports-read"
policy = jsonencode({
Version = "2012-10-17"
Statement = [{ Effect = "Allow", Action = ["s3:GetObject"], Resource = "arn:aws:s3:::lab-reports/*" }]
})
}
TF
cat > checks/no_literal_password.rego <<'R'
# METADATA
# title: Database passwords must not be literals in Terraform
# custom:
# id: LAB-0001
# avd_id: LAB-0001
# severity: HIGH
# recommended_action: Use manage_master_user_password or a secret manager reference.
# input:
# selector:
# - type: terraform-raw
package user.lab.no_literal_password
import rego.v1
deny contains res if {
some block in input.modules[_].blocks
block.kind == "resource"
block.type == "aws_db_instance"
pw := block.attributes.password
is_string(pw.value)
res := result.new(sprintf("aws_db_instance %q sets a literal password", [block.name]), pw)
}
R
cat > checks/iam_wildcard.rego <<'R'
# METADATA
# title: IAM policies must not allow every action
# custom:
# id: LAB-0002
# avd_id: LAB-0002
# severity: CRITICAL
# input:
# selector:
# - type: terraform-raw
package user.lab.iam_wildcard
import rego.v1
deny contains res if {
some block in input.modules[_].blocks
block.type == "aws_iam_policy"
doc := json.unmarshal(block.attributes.policy.value)
some st in doc.Statement
st.Effect == "Allow"
"*" in as_list(st.Action)
res := result.new(sprintf("aws_iam_policy %q allows Action \"*\"", [block.name]), block.attributes.policy)
}
as_list(x) := x if is_array(x)
as_list(x) := [x] if not is_array(x)
R
trivy config -q -f json --raw-config-scanners terraform --config-check checks --check-namespaces user iac \
| jq -r '[.Results[].Misconfigurations[]? | select(.ID | startswith("LAB"))] | sort_by(.ID)[] | "\(.Severity) \(.ID) \(.Message) (main.tf line \(.CauseMetadata.StartLine))"'HIGH LAB-0001 aws_db_instance "shop" sets a literal password (main.tf line 6)
CRITICAL LAB-0002 aws_iam_policy "ci" allows Action "*" (main.tf line 11)
Both gaps are now findings, with the line to fix, and the narrow reports-read policy passes. The checks live in the repository next to the code they guard, get reviewed like code, and run on every pull request. A good custom check also has tests: a known-bad and a known-good input that must produce exactly the expected results (opa test does this for plain Rego; OPA Tests shows the pattern).
Policy-as-code engines worth knowing: OPA/Conftest (Rego, any JSON/YAML/HCL input, including Terraform plans), Checkov custom policies (Python or YAML), Sentinel (HashiCorp's, in Terraform Cloud/Enterprise), cfn-guard (CloudFormation), and cloud-native guardrails that run at deployment (SCPs, Azure Policy, GCP Organization Policy).
Drift: when the account and the code disagree
Pre-deployment checks only see the code. If someone opens a security group from the console during an incident, disables Block Public Access "for a minute", or creates an IAM user by hand, the code still looks perfect. Drift comes in three forms:
| Drift | Example | Found by |
|---|---|---|
| Changed managed resource | a console edit adds 0.0.0.0/0 to sg-db |
terraform plan -refresh-only (exit code 2 with -detailed-exitcode), AWS Config change history |
| Unmanaged resource | an IAM user temp-admin created by hand |
inventory vs state comparison, CSPM |
| Deleted managed resource | someone deletes the trail | plan shows it would be recreated; config history shows who |
The program compares a Terraform-state-like description of the lab account with a live inventory (as a CSPM tool or the providers' APIs would return it) and classifies the differences.
state = { # what the code and its state say
"aws_security_group.db": {"ingress": [{"port": 5432, "source": "sg-app"}]},
"aws_s3_bucket_public_access_block.uploads": {"block_public_policy": True, "restrict_public_buckets": True},
"aws_cloudtrail.org": {"is_logging": True, "is_multi_region_trail": True},
"aws_iam_user.alice": {"mfa": True},
}
live = { # what the account contains now
"aws_security_group.db": {"ingress": [{"port": 5432, "source": "sg-app"}, {"port": 5432, "source": "0.0.0.0/0"}]},
"aws_s3_bucket_public_access_block.uploads": {"block_public_policy": True, "restrict_public_buckets": False},
"aws_cloudtrail.org": {"is_logging": True, "is_multi_region_trail": True},
"aws_iam_user.alice": {"mfa": True},
"aws_iam_user.temp-admin": {"mfa": False, "policies": ["AdministratorAccess"]},
}
SECURITY_SENSITIVE = {"ingress", "restrict_public_buckets", "block_public_policy", "is_logging", "mfa", "policies"}
for addr in sorted(set(state) | set(live)):
if addr not in live:
print(f"DELETED {addr}")
continue
if addr not in state:
print(f"UNMANAGED {addr} {live[addr]}")
continue
for key in sorted(set(state[addr]) | set(live[addr])):
want, have = state[addr].get(key), live[addr].get(key)
if want != have:
tag = "SECURITY" if key in SECURITY_SENSITIVE else "drift"
if isinstance(want, list):
extra = [x for x in have if x not in want]
print(f"CHANGED {addr}.{key}: added {extra} [{tag}]")
else:
print(f"CHANGED {addr}.{key}: {want} -> {have} [{tag}]")UNMANAGED aws_iam_user.temp-admin {'mfa': False, 'policies': ['AdministratorAccess']}
CHANGED aws_s3_bucket_public_access_block.uploads.restrict_public_buckets: True -> False [SECURITY]
CHANGED aws_security_group.db.ingress: added [{'port': 5432, 'source': '0.0.0.0/0'}] [SECURITY]
All three differences are security-relevant: the database group is open to the Internet, one bucket's public-access protection is half off, and an administrator nobody declared exists without MFA. A terraform apply would revert the first two (if anyone runs it), but it would never notice the unmanaged user, because Terraform only manages what is in its state. That is why drift detection needs both a refresh-only plan and an inventory of everything in the account.
How drift is detected and prevented
- Scheduled refresh-only plans per workspace, alerting on exit code 2; AWS Config / Azure Resource Graph change tracking / GCP Cloud Asset Inventory feeds for who changed what.
- CSPM over the live account for unmanaged resources and misconfigurations wherever they came from (the next lesson).
- CloudTrail detections on console changes to sensitive resources by humans (
userAgentof the console,sessionContextwithout the pipeline role). - Prevention: production write access only for the pipeline role; humans get read-only plus an audited break-glass role; SCPs that deny the riskiest changes outside the pipeline. Then drift becomes rare, and every instance of it is an event worth explaining.
Drift & Refresh shows the Terraform mechanics.
Pitfalls
- Custom checks without tests: a typo in a Rego condition silently passes everything.
- Writing policies that only work on one style of code (
jsonencodebut not heredoc oraws_iam_policy_document): test each style you allow, or standardise on one. - Treating
terraform applyas drift remediation: it reverts silently, so nobody learns who opened the port and why.
Practice
1. Rewrite the ci policy with a heredoc JSON string instead of jsonencode. Does LAB-0002 still fire?
Yes: the attribute value is the JSON string either way, and json.unmarshal parses it. With an aws_iam_policy_document data source, the policy attribute would be a reference, not a string value, and the check would need a second rule over data blocks.
2. Extend LAB-0002 to also catch "Action": "iam:*". What changes?
Replace "*" in as_list(st.Action) with some a in as_list(st.Action); a in {"*", "iam:*"} (or endswith(a, ":*") for every service-wide wildcard), and add test cases for each form.
3. In the drift output, which item would you investigate first, and where would you look?
The unmanaged temp-admin user with AdministratorAccess and no MFA: in CloudTrail for CreateUser/AttachUserPolicy with userName temp-admin (who, when, from where), then everything that user's keys did since.
Test yourself
What did the custom checks find that the built-in rules missed?
- Unencrypted RDS
- A literal database password and an IAM policy allowing Action *
- Public buckets
- Missing tags
Which kind of drift can terraform plan -refresh-only never show?
- Changed attributes of managed resources
- Unmanaged resources created outside Terraform
- Deleted managed resources
- Tag changes
What is the strongest prevention of drift in production?
- Running apply hourly
- Only the pipeline role may write; humans are read-only with an audited break-glass role
- More scanners
- Disabling the console