Compliance Automation and Tooling Questions
Using technology to make compliance continuous rather than point-in-time. Covers GRC platforms and control libraries (build versus buy, one control set mapped to many regulations, requirement-to-evidence traceability, risk roll-ups), compliance-as-code and policy-as-code checks mapped to framework controls (including testing, versioning and retiring the rules, and turning local legal and privacy obligations such as retention and masking into machine-checkable tests), continuous control monitoring and drift alerts, automated evidence collection and tamper-evident evidence pipelines for auditors, automated compliance and privacy reporting with traceable lineage (including regulatory SLA tracking such as DSAR deadlines), and wiring compliance checks into engineering pipelines without slowing teams. Focuses on what to automate first, how to map controls to machine-checkable tests, where to place checks, and the limits of automation. Does not cover designing or testing the controls themselves, the content of individual frameworks, hands-on security mechanics such as secrets, IAM, scanning or logging pipelines, or conducting the audit.
Your company must show continuous compliance with GDPR, HIPAA, PCI DSS and ISO 27001 across AWS, Azure and GCP, and you do not want four separate sets of checks. How would you design a continuous control monitoring system where one machine-checkable test can satisfy several frameworks, how would you keep false passes and false alarms down at scale, and how would you handle data residency for the evidence itself?
Sample Answer
Direct answer
The four frameworks are GDPR (the EU General Data Protection Regulation), HIPAA (the US health-data law), PCI DSS (the Payment Card Industry Data Security Standard) and ISO 27001 (the international information security management standard). I would not build four sets of checks. I would build one library of machine-checkable tests that measure facts (for example, "which human users lack multi-factor authentication"), plus a versioned mapping file that links each test to the controls it supports in each framework. Continuous control monitoring (CCM) means running those tests repeatedly and alerting on change, not once a year. The mapping, not the test, carries framework differences, so one test can serve several frameworks while each framework's owner still decides what "satisfied" means.
One test, several frameworks (illustrative mapping for "MFA enforced for all human users")
The table has a row for each of the four frameworks in the question, plus a fifth row for SOC 2 (the AICPA report on a company's security controls) to show that a new framework is one more row in the mapping, not one more test.
| Framework | Reference | What the test result supports | Caveat |
|---|---|---|---|
| ISO/IEC 27001:2022 | Annex A 8.5 (secure authentication) | Authentication technology matches the access policy | The control owner defines "adequate" in the Statement of Applicability (the ISO document listing which Annex A controls apply and why) |
| PCI DSS v4.0.1 | Requirement 8.4.2 (MFA for all access into the cardholder data environment) | Only for accounts in scope of the CDE (cardholder data environment: the systems that store, process or transmit card data). Mandatory since 31 March 2025 | The test must be scoped to the CDE, not the whole company |
| HIPAA Security Rule | 45 CFR 164.312(d) (person or entity authentication) | Procedures verify who is accessing electronic protected health information (ePHI) | The rule does not name MFA, so this is supporting evidence |
| SOC 2 | CC6.1 (logical access security: restricting system access to authorized users) | Identification and authentication before access | Auditor judges design |
| GDPR | Article 32 (security of processing) | Appropriate technical measures | Does not prescribe MFA. Counsel and the DPO (data protection officer, the role GDPR requires some organizations to appoint to advise on and monitor compliance) decide sufficiency |
The test outputs a measured value (such as "0 of 412 human users lack MFA") and a scope tag. The mapping says which framework control it supports. I would never state that a passing test equals framework compliance. The citations show how one result attaches to each framework; the pattern to carry is a measured fact, a scope, and a caveat, not recall of every clause number.
A traced example (illustrative numbers). The test mfa-enforced reads the normalized identities from all three clouds: 412 human users, of which 3 have no MFA, 2 of those 3 tagged as CDE accounts. It emits {"test": "mfa-enforced", "evaluated": 412, "failed": 3, "failed_in_cde": 2}. The mapping file lists mfa-enforced under ISO A.8.5, PCI DSS 8.4.2 (counting only failed_in_cde), HIPAA 164.312(d) as supporting evidence, SOC 2 CC6.1 and GDPR Article 32 as supporting evidence. So the one result fails PCI 8.4.2 for 2 accounts and shows 3 exceptions for the ISO and SOC 2 controls, with no second test needed.
Architecture
- Collectors per cloud and per region read from AWS, Azure and GCP, using their native config and policy services as inputs.
- A normalizer (a translation layer) turns each cloud's different resource shapes into one model (an identity, a storage resource, a network rule). For example, an AWS IAM user, an Azure Entra user and a GCP account all become
{kind: identity, cloud, region, human: true, mfa: true or false, scope_tags: [...]}. - The test library evaluates the model. Each result is tri-state (three possible outcomes): pass, fail, or error/unknown.
- The mapping file connects tests to controls many-to-many.
- A results store feeds a GRC (governance, risk and compliance) platform and the auditor view. Control owners see their own failures.
Keeping false passes down
- Never treat error or unknown as a pass.
- Measure coverage: resources evaluated divided by resources found by an independent inventory. A test that passes on 80% of the estate is not a pass.
- Write a negative test for every check: a seeded violation that the check must fail.
- Keep a canary in each cloud that must be flagged daily.
- Reconcile periodically with a human spot check.
Keeping false alarms down
Route to the owning team, deduplicate by resource, allow eventual-consistency grace periods (cloud APIs can take minutes to report a new resource's settings, so a brand-new resource can look noncompliant briefly) before alerting on a just-created resource, give suppressions an expiry, and measure alert precision from triage labels.
Data residency for the evidence
Evidence can contain personal data (user emails in an access list). Collect and store it in the region where it originates, and send only hashes, counts and pass/fail results to the central index. A hash of an email address is pseudonymised, not anonymous, so whether even hashes may leave the region is part of counsel's call; counts and pass/fail results carry no personal data. GDPR Chapter V (Articles 44 to 50) restricts transfers of personal data to third countries (countries outside the EU and EEA), so whether a transfer is lawful is counsel's call, but data minimization (collecting and keeping only what is needed) in the design means most of the evidence never needs to leave. Store configuration values, never PHI or card numbers.
Divergent regional interpretations
The test stays the same. A regional overlay changes the parameters and the scope, such as a longer retention threshold in one jurisdiction or evidence kept in-region, and the divergence is recorded in the mapping. Illustratively, a test log-retention-months >= threshold uses a threshold of 12 in the baseline mapping, and an overlay for one jurisdiction sets 24. The same test then passes a log store set to 12 months under the baseline mapping and fails that same 12-month store under the overlay, with no second test written.
Scoring and integration
Report coverage (illustratively 70 of 120 in-scope controls automated, 58.3%) separately from pass rate (66 of those 70 passing, 94.3%). A single blended score hides which one moved.
Your privacy team misses an occasional data subject access request deadline because nobody notices a backlog building until it is too late. How would you build the tracking and alerting so at-risk requests surface early without paging people for every open ticket, and how would you test that it works before the next backlog spike?
Sample Answer
Direct answer
A data subject access request (DSAR) is a person's request to see the personal data an organization holds about them. The legal clock starts at receipt. Under GDPR Article 12(3) the response is due without undue delay and within one month of receipt, extendable by two further months where necessary given the complexity and number of requests, with the data subject told of the extension and reasons within the first month. California's CCPA (California Consumer Privacy Act, Civil Code 1798.130) gives 45 days, extendable once by 45 days with notice. Which one applies depends on who the requester is and which law covers your organization for them. Counsel owns that mapping, and where two could apply the tracker uses the earlier date. For example, a request received on 3 March 2025 is due 3 April 2025 under GDPR (one month) and 17 April 2025 under CCPA (45 days), and the tracker stores that computed date rather than leaving someone to count. I would track every request with computed due dates, project each one's completion from the queue and team capacity, and flag only requests projected to miss. Counsel decides when an extension is justified and whether any pause applies.
Data model
One record per request: received_at, jurisdiction, due_at computed by rule (kept in one table counsel owns), current stage (identity check, locating data, collection, legal review, delivery), stage timestamps, owner, and extension status. Timestamps per stage give you throughput, which is what makes projection possible.
Alert tiers instead of one page per ticket
- Daily digest: requests whose projected completion date is later than due date minus a safety buffer.
- Page: a flagged request with no owner action for a stated time, or a queue projected to breach on several requests.
- Weekly capacity view: arrivals versus completions and backlog trend, so a spike is seen as a rate problem before individual requests are at risk.
- Heartbeat: an alert if the tracker itself has produced no data, because a silent alerting system looks identical to a calm one.
Testing it before the next spike: a runnable simulation
The core alert rule is simple. A request's position in the queue divided by the team's daily capacity is the number of working days before the team reaches it. Add the safety buffer, and if that total is more than the days left until its due date, flag it now, while there is still time to add people. For example, with 40 requests ahead of it and a capacity of 4 a day, a request needs about 10 days of work before it is handled. With a 3-day buffer that is 13 days. If it has 12 days left it is flagged. If it has 13 or more it is not yet. In the code below that rule is the line if pos / BASE_CAP + BUFFER > days_left, where pos is how many requests are ahead of this one and days_left is its arrival day plus 30 minus today.
This toy model (illustrative parameters, not your data) uses Poisson arrivals (random counts around an average) with a fixed seed. Normal days average 3 requests, and a ten-day spike runs at 20 a day. The team completes 4 a day, so on a normal day it has only 1 spare slot, and it drains a spike backlog by only about 1 request a day. The spike brings about 200 arrivals in ten days against 40 completions, so the queue grows by roughly 160. In the run below, with no early warning, the queue peaks at 154 waiting requests on day 69 and is not fully cleared until about day 199. A 30-day internal target stands in for the legal deadline, the safety buffer is 3 days, and the response to an early flag is to double capacity to 8 a day.
import math, random
DAYS, DUE, BASE_CAP, SURGE_CAP, BUFFER = 200, 30, 4, 8, 3
def poisson(rng, lam):
L, k, p = math.exp(-lam), 0, 1.0
while True:
p *= rng.random()
if p <= L:
return k
k += 1
def run(surge_on):
rng = random.Random(7)
queue, breaches, rid = [], 0, 0 # queue = [(id, arrival_day)], oldest first
naive_pages, flagged, surge_days = 0, set(), 0
for day in range(DAYS):
lam = 20 if 60 <= day < 70 else 3 # a ten-day backlog spike
for _ in range(poisson(rng, lam)):
queue.append((rid, day)); rid += 1
cap = BASE_CAP
newly = 0
for pos, (r, arr) in enumerate(queue):
naive_pages += 1 # what "page on every open ticket" would send today
days_left = arr + DUE - day
if pos / BASE_CAP + BUFFER > days_left and r not in flagged:
flagged.add(r); newly += 1
if surge_on and any(r in flagged for r, _ in queue):
cap, surge_days = SURGE_CAP, surge_days + 1
for _ in range(min(cap, len(queue))):
r, arr = queue.pop(0)
if day - arr > DUE:
breaches += 1
return rid, breaches, naive_pages, len(flagged), surge_days, len(queue)
for label, s in (("no early warning", False), ("early warning + surge", True)):
rid, b, naive, fl, sd, left = run(s)
print(f"{label}: received={rid} breaches={b} flagged={fl} surge_days={sd} still_open={left} naive_pages={naive}")
Real output:
no early warning: received=710 breaches=107 flagged=167 surge_days=0 still_open=0 naive_pages=11377
early warning + surge: received=710 breaches=0 flagged=70 surge_days=23 still_open=0 naive_pages=3715
Without early warning, 107 requests finish after day 30. With the flag and the surge response, 0 do. The variable naive_pages counts one page per open request per day, so a request that stays open for 20 days adds 20 pages. A rule that paged on every open ticket would therefore have sent 3,715 pages across the run in the second case, against 70 distinct requests actually flagged, each flagged once. The two numbers count different things (request-days versus unique requests), which is the point: the projection rule turns thousands of daily reminders into a short list of requests that need action. The model shows the rule would have worked on that spike, not that it works on yours.
Testing on your own data
- Backtest: replay last year's queue history through the rule. List which past misses it would have flagged and how many pages per week it would have sent.
- Synthetic requests: inject back-dated dummy requests in staging and confirm they appear in the digest and escalate on schedule.
- Game day: simulate a spike with the real team and check the escalation path, not just the dashboard.
- Track alert quality: precision (flagged requests that truly needed action) and lead time (days left when first flagged).
Trade-offs
A bigger buffer catches more but pages more. Start with a buffer from your stage-duration history, review precision monthly, and tune. Be careful treating the internal target and the legal deadline as the same number: keep your target earlier than the strictest deadline that applies.
An internal review finds that production configurations across your cloud and on-premises estate have quietly drifted from the approved baseline, and the next audit asks you to prove they stay aligned. How would you set up automated baselining and drift detection, decide what auto-remediates versus what becomes a ticket, and keep the evidence the auditors will want?
Sample Answer
Direct answer
Treat the approved baseline as code in version control, compare reality to it on a schedule and on every change, and split findings by blast radius (how much could break, and for how many users, if the automatic fix is wrong): auto-revert the ones that are reversible and clearly wrong, ticket the ones that could break something or need a decision. Every detection, action and exception is logged, since that log is the audit evidence.
1. Establish the baseline
Define approved settings per system class (hardened server image, database, storage, network rules), based on an accepted benchmark such as a CIS Benchmark (a hardening checklist published by the Center for Internet Security, with recommended settings for operating systems, clouds and databases) where one exists, and keep them in git. Baseline changes go through review, so the baseline itself has a history.
2. Detect drift in three places
- Before it ships (pre-commit and CI): check infrastructure-as-code against the same baseline. Policy checks run on every pull request.
- Against reality:
terraform plan -detailed-exitcodeexits 0 for no changes, 1 for error and 2 when the plan differs from real state, which makes a scheduled drift job simple.terraform plancompares three things: the code, Terraform's state (its record of the resources it created) and what actually exists in the cloud, then lists what it would change to make reality match the code. Run on a schedule against code that has not changed, any difference it reports is drift rather than a pending change. Cloud inventory and configuration services cover resources not under code. On-premises hosts need an agent or configuration-management tool run in check mode (a dry run that reports what it would change without changing anything). - Across many repos and teams: publish the baseline as a shared rule library and make the pipeline template mandatory through organisation-level required checks (a setting on the code-hosting platform that makes chosen checks mandatory before a merge in every repository), so a new team inherits enforcement, not a to-do list.
3. Decide: auto-remediate or ticket
Auto-remediate only if the change is reversible, the correct state is unambiguous, the blast radius is small and the fix has been tested. Ticket if it touches stateful or application-specific settings, could cause an outage, or may be an approved exception. Always fix the code too (the code is the source of truth, the one place the approved state is defined), or the next apply reintroduces the drift.
Worked example (code run, output pasted)
import json
baseline = {
"bucket-logs": {"encryption": "aws:kms", "public_access_block": True, "versioning": True},
"sg-web": {"ingress_ports": [443], "ssh_open_to_world": False},
"db-prod": {"storage_encrypted": True, "backup_retention_days": 7},
}
observed = {
"bucket-logs": {"encryption": "aws:kms", "public_access_block": False, "versioning": True},
"sg-web": {"ingress_ports": [443, 22], "ssh_open_to_world": True},
"db-prod": {"storage_encrypted": True, "backup_retention_days": 3},
}
AUTO_FIX = {("bucket-logs", "public_access_block"), ("sg-web", "ssh_open_to_world")}
def diff(base, obs):
for res, want in base.items():
for key, expected in want.items():
actual = obs[res][key]
if actual != expected:
yield res, key, expected, actual
for res, key, expected, actual in diff(baseline, observed):
action = "AUTO-REMEDIATE" if (res, key) in AUTO_FIX else "TICKET"
print(json.dumps({"resource": res, "setting": key, "expected": expected,
"actual": actual, "action": action}))
Output:
{"resource": "bucket-logs", "setting": "public_access_block", "expected": true, "actual": false, "action": "AUTO-REMEDIATE"}
{"resource": "sg-web", "setting": "ingress_ports", "expected": [443], "actual": [443, 22], "action": "TICKET"}
{"resource": "sg-web", "setting": "ssh_open_to_world", "expected": false, "actual": true, "action": "AUTO-REMEDIATE"}
{"resource": "db-prod", "setting": "backup_retention_days", "expected": 7, "actual": 3, "action": "TICKET"}
Reading the code: baseline is the approved state and observed is what a scan found, each a set of settings per resource. AUTO_FIX is the short allow-list of (resource, setting) pairs that are safe to revert without a person. diff walks every approved setting, compares it with the observed value, and yields a record only where they differ. The loop at the bottom labels each difference AUTO-REMEDIATE if it is on the allow-list and TICKET otherwise, so anything not explicitly judged safe goes to a human by default.
Four drifts, two auto-fixed, two ticketed. Closing SSH to the world is revert-safe, but an extra open port may be something an application needs, so a person decides. Shortened backup retention is a data-protection decision, not a safe revert.
4. Evidence for the auditor
Keep the baseline version, each scan result with timestamp, each remediation (who or what, when, before and after values), exceptions with approver and expiry, and time to remediate by severity. Show the drift rate trending down, not a flat zero.
Pitfalls
- Auto-remediation fighting the deployment tool in a loop. Fix the source of truth first.
- Remediating with no notification: owners should learn their change was reverted.
- A baseline nobody updates trains people to ignore drift reports.
Leadership wants to know, every day rather than once a year, whether encryption, admin MFA and logging are actually in place across your cloud accounts. How would you build a continuous control monitoring pipeline for that, what would you do when a check fails, and how would you keep the results usable as evidence for internal and external auditors?
Sample Answer
Direct answer
Build a daily loop: collect configuration state from every cloud account, evaluate it against a small set of rules, store every result as timestamped evidence, route failures to owners with deadlines, and report pass rate and age of open failures to leadership. This is continuous control monitoring (CCM): automated, frequent testing of whether a control is in place, instead of one annual check.
Pipeline
- Collect. Use the cloud provider's configuration service in every account and aggregate centrally. On AWS, AWS Config is the service that records the settings of resources in an account and checks them against rules, and its managed rules (rules AWS ships ready-made) fit the three asks:
S3_BUCKET_SERVER_SIDE_ENCRYPTION_ENABLED(storage buckets encrypted by default),ROOT_ACCOUNT_MFA_ENABLED(root user requires multi-factor authentication) andCLOUD_TRAIL_ENABLED(an audit-log trail is enabled). Admin MFA for day-to-day administrators needs a check on the identity provider (IdP, the system that signs people in, such as Okta or Microsoft Entra ID) or IAM users too, since the root rule covers only the root user. - Evaluate. Each rule returns compliant, non-compliant or not applicable per resource. Treat not applicable carefully:
ROOT_ACCOUNT_MFA_ENABLEDreturns it when no root credentials exist, which is fine, but a rule that is not applicable because the feed is broken is not. - Store as evidence. Write each result (account, resource, rule and version, result, timestamp) to write-once storage (storage where saved records cannot be edited or deleted for a set period) with a hash, so the history cannot be quietly rewritten.
- Report. Executives see pass rate by control and open-failure age; engineers see the failing resource.
When a check fails
| Step | Action |
|---|---|
| Triage | Ticket auto-created with resource, owner (from tags), severity |
| Fix SLA (service-level agreement, the promised deadline for fixing) | Set by severity, for example days for high and weeks for low (agree it with the business) |
| Exception | Allowed only with a named approver and an expiry date, so it re-appears later |
| Closure | Retest passes and the passing result is stored next to the failing one |
Making results usable for auditors
- Keep the rule definition, its version and the framework control it supports (for example NIST SP 800-53, a US government catalogue of security controls, where IA-2(1) is the entry in the identification and authentication family that requires multi-factor authentication for privileged accounts) next to the results.
- Keep both failures and fixes; auditors trust a record that shows problems being found and closed more than one that shows no failures at all.
- Record gaps: if the collector was down on Tuesday, say so rather than leaving a hole.
- Sample the automation, because auditors still test whether the rule means what you say it means. A typical sample: the auditor picks a few accounts and dates, checks that the live setting matches the stored result for that date, and picks a few failed checks to confirm a ticket was opened and closed within the promised deadline.
Worked example
40 accounts times 3 checks is 120 evaluations per day. Two fail (one unencrypted bucket, one account with logging off): 118 of 120 pass, 98.3%. Over a year that is 43,800 data points, against one sample on one day in a point-in-time audit.
Limits
A passing rule shows the setting, not that it is the right setting. For example, a trail being enabled does not prove it covers every region or that anyone reviews it. Pair CCM with periodic effectiveness testing.
Write an OPA Rego policy that rejects Terraform plan changes which create or update any aws s3 bucket without server side encryption enabled. The policy should examine resource attributes in the Terraform plan input and return a clear deny message indicating which resource lacks server side encryption.
Sample Answer
Approach
Terraform is a tool that creates cloud resources from code files. terraform plan previews what it would create, change or delete without touching anything, and terraform show -json prints that preview as JSON, one entry per resource change. The policy reads that JSON, finds each S3 bucket being created or updated, and denies it unless an encryption configuration for that bucket is also in the plan. Two details decide whether the policy works. Since version 4 of the AWS provider, encryption is a separate resource (aws_s3_bucket_server_side_encryption_configuration), not an argument on the bucket. For a new bucket, that resource's bucket value is unknown at plan time (Terraform cannot know a bucket's ID until the bucket exists, so the plan leaves the value blank), so the link between the two must come from the plan's configuration section, which records which resource each argument was written to refer to. The section "What the plan JSON looks like" shows both pieces.
Reproduce the input
main.tf (the provider block skips credential checks so a plan runs without AWS access):
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.0" }
}
}
provider "aws" {
region = "us-east-1"
access_key = "x"
secret_key = "x"
skip_credentials_validation = true
skip_requesting_account_id = true
skip_metadata_api_check = true
skip_region_validation = true
}
resource "aws_s3_bucket" "logs" { bucket = "acme-logs" }
resource "aws_s3_bucket" "reports" { bucket = "acme-reports" }
resource "aws_s3_bucket" "tmp" { bucket = "acme-tmp" }
resource "aws_s3_bucket_server_side_encryption_configuration" "logs" {
bucket = aws_s3_bucket.logs.id
rule {
apply_server_side_encryption_by_default { sse_algorithm = "aws:kms" }
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "reports" {
bucket = aws_s3_bucket.reports.id
rule {
apply_server_side_encryption_by_default { sse_algorithm = "AES256" }
}
}
module "store" {
source = "./modules/store"
}
modules/store/main.tf:
resource "aws_s3_bucket" "data" { bucket = "acme-data" }
resource "aws_s3_bucket" "scratch" { bucket = "acme-scratch" }
resource "aws_s3_bucket_server_side_encryption_configuration" "data" {
bucket = aws_s3_bucket.data.id
rule {
apply_server_side_encryption_by_default { sse_algorithm = "aws:kms" }
}
}
terraform init
terraform plan -out=tfplan
terraform show -json tfplan > plan.json
What the plan JSON looks like
Every entry in resource_changes carries an address (the resource's full name), a type, and change.actions and change.after (what the resource will look like once applied). Here is the encryption resource for logs, taken from the real plan of the example above and trimmed:
{
"address": "aws_s3_bucket_server_side_encryption_configuration.logs",
"type": "aws_s3_bucket_server_side_encryption_configuration",
"change": {
"actions": ["create"],
"after": {
"rule": [{"apply_server_side_encryption_by_default": [{"sse_algorithm": "aws:kms"}]}]
},
"after_unknown": {"bucket": true}
}
}
Notice what is missing: after has no bucket key at all, and after_unknown says bucket will only be known after apply. That is what "unknown at plan time" looks like, and it means the plan cannot tell you which bucket this encryption belongs to by name. The other half of the answer is in the separate configuration section, which stores the code as written:
{
"address": "aws_s3_bucket_server_side_encryption_configuration.logs",
"expressions": {
"bucket": {"references": ["aws_s3_bucket.logs.id", "aws_s3_bucket.logs"]}
}
}
The bucket argument was written as aws_s3_bucket.logs.id, so the link survives as a reference even though the value is blank. Resources inside a module sit deeper in this section, under module_calls.<module name>.module.resources, and their addresses are relative to the module (aws_s3_bucket.data, not module.store.aws_s3_bucket.data).
Start with the simple version
When bucket names are known in the plan (a bucket that already exists), a short rule is enough. An encryption resource covers a bucket when both name the same bucket:
package terraform.simple
import rego.v1
encrypted(bucket) if {
some cfg in input.resource_changes
cfg.type == "aws_s3_bucket_server_side_encryption_configuration"
cfg.change.after.bucket == bucket.change.after.bucket
}
deny contains msg if {
some bucket in input.resource_changes
bucket.type == "aws_s3_bucket"
not encrypted(bucket)
msg := sprintf("%s has no encryption configuration", [bucket.address])
}
Run against this plan, it denies all five buckets, including logs, reports and store.data, which are encrypted. The reason is the blank bucket value above: cfg.change.after.bucket does not exist for a new bucket, so the comparison never succeeds. A rule with no value to compare behaves as false, and not encrypted(bucket) then denies. The full policy below fixes exactly this with a second way to link the two resources. The extra helper rules in it exist for that second link and for resources inside modules (reusable folders of Terraform code, such as ./modules/store). A repository with no modules needs only the root-level part of them.
The full policy (Rego, the language of Open Policy Agent, OPA 1.x syntax)
package terraform.s3
import rego.v1
allowed_algorithms := {"AES256", "aws:kms"}
# Buckets the plan creates or updates. A replace is ["delete","create"], so it counts.
managed_buckets contains rc if {
some rc in input.resource_changes
rc.type == "aws_s3_bucket"
rc.mode == "managed"
some action in rc.change.actions
action in {"create", "update"}
}
# Encryption configurations that remain in place after the plan and name a real algorithm.
sse_configs contains rc if {
some rc in input.resource_changes
rc.type == "aws_s3_bucket_server_side_encryption_configuration"
rc.change.actions != ["delete"]
some rule in rc.change.after.rule
some default_rule in rule.apply_server_side_encryption_by_default
default_rule.sse_algorithm in allowed_algorithms
}
# "module.store.aws_x.y[0]" -> ["store"]
module_names(addr) := [m[1] | some m in regex.find_all_string_submatch_n(`module\.([^.\[]+)`, addr, -1)]
# "module.store.aws_x.y[0]" -> "aws_x.y"
relative(addr) := regex.replace(regex.replace(addr, `^(module\.[^.]+\.)+`, ""), `\[[^\]]*\]$`, "")
# A configuration path such as ["module_calls","store","module","resources",0] -> ["store"]
module_path(path) := [path[i + 1] | some i, p in path; p == "module_calls"]
# Link 1 (new buckets): the config's `bucket` argument references the bucket resource.
# Both resources must sit in the same module, and the reference is relative to it.
covers(cfg, bucket) if {
module_names(cfg.address) == module_names(bucket.address)
walk(input.configuration.root_module, [path, res])
count(path) >= 2
path[count(path) - 2] == "resources"
module_path(path) == module_names(cfg.address)
res.address == relative(cfg.address)
relative(bucket.address) in res.expressions.bucket.references
}
# Link 2 (existing buckets): the bucket name is already known in the plan.
covers(cfg, bucket) if {
cfg.change.after.bucket == bucket.change.after.bucket
}
encrypted(bucket) if {
some cfg in sse_configs
covers(cfg, bucket)
}
deny contains msg if {
some bucket in managed_buckets
not encrypted(bucket)
msg := sprintf("%s: aws_s3_bucket has no server-side encryption configuration (AES256 or aws:kms) in this plan", [bucket.address])
}
opa eval -f pretty -d s3_encryption.rego -i plan.json 'data.terraform.s3.deny'
Real output (Terraform AWS provider 5.x):
[
"aws_s3_bucket.tmp: aws_s3_bucket has no server-side encryption configuration (AES256 or aws:kms) in this plan",
"module.store.aws_s3_bucket.scratch: aws_s3_bucket has no server-side encryption configuration (AES256 or aws:kms) in this plan"
]
aws_s3_bucket.logs (KMS) and reports (AES256) pass, and so does module.store.aws_s3_bucket.data. The two buckets with no encryption resource are denied, each message naming the resource.
Reading the policy in plain words
managed_bucketsis the list of buckets to inspect: resources of typeaws_s3_bucketthat Terraform manages, whose action list containscreateorupdate.sse_configsis the list of encryption resources that stay in place and name an allowed algorithm. Only a pure delete (["delete"]) removes a resource from the list; a replace (["delete","create"]) leaves the encryption configuration in place, so it still counts. It is built from the plan'saftervalues, so an empty algorithm never gets in.module_names("module.store.aws_s3_bucket.scratch")returns["store"], the module the resource lives in. For a root resource such asaws_s3_bucket.tmpit returns an empty list. The regexmodule\.([^.\[]+)simply captures the word after eachmodule.in the address.relative(...)strips the module prefix and any[0]index, somodule.store.aws_x.y[0]becomesaws_x.y. That is the form theconfigurationsection uses for addresses.module_path(path)reads a location insideconfiguration.walk(input.configuration.root_module, [path, res])visits every nested value in that section and hands back its location (path) and the value (res). A resource inside a module has a path like["module_calls", "store", "module", "resources", 0], andmodule_pathpicks out the module names (["store"]) so the walk only accepts the resource in the same module as the encryption resource. The checks oncount(path)keep the walk to entries that are items of aresourceslist.covershas two bodies, and either one succeeding is enough (Rego treats several definitions of the same function as "or"). Link 1 finds the configuration entry for the encryption resource and checks that itsbucketreference names this bucket. Link 2 is the simple comparison of known names.encryptedis true when at least one encryption resource covers the bucket, anddenyproduces a message for every bucket where it is not.
Trace for aws_s3_bucket.tmp, step by step. It is in managed_buckets (type matches, action is create). encrypted tries each of the three encryption resources. For ...logs, Link 1 finds the configuration entry, but its references are aws_s3_bucket.logs.id and aws_s3_bucket.logs, and aws_s3_bucket.tmp is not among them. For ...reports the same happens. For module.store...data, the module names (["store"] versus an empty list) differ, so it is rejected at the first line. Link 2 fails for all three because after.bucket is missing. Nothing covers tmp, so encrypted is false and deny fires with the message naming aws_s3_bucket.tmp. The same trace for aws_s3_bucket.logs stops early: the logs encryption entry references aws_s3_bucket.logs, Link 1 holds, and no message is produced.
Key points
actionsis a list. A replace (Terraform destroys the resource and creates it again) is["delete","create"], so matching oncreateorupdateanywhere in the list catches it. Deletes are ignored.- Link 1 uses the configuration references for new buckets. Link 2 compares known bucket names for buckets that already exist. Both resources must be in the same module, which the module-name comparison enforces, so a same-named resource in another module cannot make a bucket pass.
- An encryption resource with an empty or missing algorithm does not count.
- In CI (continuous integration, the automated build and test pipeline) use
--fail-defined 'data.terraform.s3.deny[_]', an OPA option that makesopa evalexit with status 1 when the query returns anything, so any denial fails the pipeline step.
Be precise about what this proves
Since January 5, 2023, S3 applies SSE-S3 (server-side encryption with S3-managed keys) to all new object uploads whether or not you configure anything, and you cannot turn that off. So an unconfigured bucket is no longer storing plaintext. What the policy enforces is an explicit, reviewable declaration, and the allowed set (AES256, aws:kms) is where you tighten to KMS (AWS Key Management Service) customer-managed keys if your standard requires it.
Preventive plan check versus detective scan of existing buckets
The plan check is preventive: it only sees buckets Terraform is changing. Buckets created by hand or by old code need a detective control, a scan of the live inventory. With 2,000 buckets, a loop that lists buckets and then reads each bucket's encryption setting makes 2,001 API calls (1 list plus 2,000 reads), with cost and rate limits growing linearly in the number of buckets, so query a continuously recorded inventory such as AWS Config instead of calling each bucket. Feed both into the pipeline: the plan check blocks the merge, and the inventory scan opens tickets for violations in existing buckets.
Edge cases and limits
Buckets defined in modules are handled by the module-path match above. The link is made per resource block, not per instance: with count or for_each, the bucket reference is the block (aws_s3_bucket.f, with each.key listed separately), and relative() strips the [...] index, so one encrypted instance covers every instance of the bucket block. In a test plan with for_each = ["a", "b"] on the bucket and for_each = ["a"] on its encryption resource, aws_s3_bucket.f["b"] passed this rule although it has no encryption resource, so for instanced buckets add a per-instance check or require encryption through a shared module. Resources created outside Terraform, dynamic or computed algorithm values (unknown at plan time, so the policy cannot see an allowed algorithm and the bucket is denied; that is what "fail closed" means: when the policy cannot positively establish that a bucket is encrypted, the answer is deny, whereas failing open would let the change through), and encryption added in a later apply are outside what a single plan can prove. Keep unit tests next to the policy and run them with opa test (OPA's built-in test runner, which feeds sample inputs to the rules and checks the results): one input per case (update with known encryption, update with none, delete, replace of both the bucket and its encryption resource, empty algorithm) so a rule change cannot silently stop denying.
Unlock Full Question Bank
Get access to all 23 Compliance Automation and Tooling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.