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.
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.
Your organisation has hundreds of policy-as-code rules written by different teams across clouds, and some rules are noisy, stale or contradictory. How would you test, version, roll out and retire policies safely (including warn-before-enforce), who owns them, and how do you handle exceptions and drift?
Sample Answer
Direct answer
Treat policy rules like production software with a named owner: every rule has tests, a version, a mode (warn or enforce), an expiry-dated exception path, and a retirement route. Roll out in the order test, warn, enforce on new resources, enforce everywhere. Retire a rule only after confirming the control it tested is still covered by another rule.
Ownership
- Rule content: the team that owns the risk (security for baseline guardrails, data platform for retention rules, each product team for its own service rules). Each rule file carries an owner field and is protected by CODEOWNERS (a repository file that forces the named team to approve changes).
- The platform: a small central team owns the engine, the shared test harness, the registry (the central catalog where released rule versions are stored) and the promotion pipeline (the automated steps that move a rule from test to warn to enforce). It does not own the content, otherwise it becomes the bottleneck and the rules go stale.
- Intent first: write each requirement once as a control objective (the outcome the rule protects, such as "storage is encrypted at rest"), then map it to per-cloud rules. Contradictions are then visible as two rules mapped to one objective.
Test
Every rule ships with unit tests against fixture resources (small JSON documents describing a compliant and a non-compliant resource). In CI, run the whole rule set against one shared fixture corpus (the shared collection of those fixture documents): two rules that give opposite answers on the same fixture fail the build, which is how contradictory rules from different teams get caught. The Open Policy Agent (OPA, an open-source policy engine) policy below, written in Rego (OPA's rule language), is a runnable example with a mode switch and expiring exceptions. Save the first block as s3_encryption.rego and the second as s3_encryption_test.rego.
package policy.s3_encryption
import rego.v1
# Rule metadata lives in data.rules; this file is the rule logic.
# data.rules["s3-encryption"] = {"mode": "warn" | "enforce", "owner": "...", "version": "1.2.0"}
# data.exceptions = [{"rule": ..., "resource": ..., "expires": "YYYY-MM-DD", "ticket": ...}]
default decision := {"action": "allow", "violations": []}
violated contains res.id if {
some res in input.resources
res.type == "bucket"
not res.encrypted
not excepted(res.id)
}
excepted(id) if {
some e in data.exceptions
e.rule == "s3-encryption"
e.resource == id
e.expires >= input.today
}
mode := data.rules["s3-encryption"].mode
decision := {"action": "deny", "violations": sort(violated)} if {
count(violated) > 0
mode == "enforce"
}
decision := {"action": "warn", "violations": sort(violated)} if {
count(violated) > 0
mode == "warn"
}
package policy.s3_encryption_test
import rego.v1
import data.policy.s3_encryption
base := {"today": "2026-10-04", "resources": [
{"id": "logs", "type": "bucket", "encrypted": true},
{"id": "scratch", "type": "bucket", "encrypted": false},
{"id": "legacy", "type": "bucket", "encrypted": false},
]}
exc := [
{"rule": "s3-encryption", "resource": "legacy", "expires": "2026-12-31", "ticket": "RISK-101"},
]
test_warn_mode_never_blocks if {
d := s3_encryption.decision with input as base
with data.rules as {"s3-encryption": {"mode": "warn"}}
with data.exceptions as exc
d == {"action": "warn", "violations": ["scratch"]}
}
test_enforce_mode_denies_unexcepted_only if {
d := s3_encryption.decision with input as base
with data.rules as {"s3-encryption": {"mode": "enforce"}}
with data.exceptions as exc
d == {"action": "deny", "violations": ["scratch"]}
}
test_expired_exception_stops_applying if {
late := object.union(base, {"today": "2027-01-01"})
d := s3_encryption.decision with input as late
with data.rules as {"s3-encryption": {"mode": "enforce"}}
with data.exceptions as exc
d == {"action": "deny", "violations": ["legacy", "scratch"]}
}
test_clean_input_allows if {
clean := {"today": "2026-10-04", "resources": [{"id": "logs", "type": "bucket", "encrypted": true}]}
d := s3_encryption.decision with input as clean
with data.rules as {"s3-encryption": {"mode": "enforce"}}
with data.exceptions as []
d.action == "allow"
}
$ opa test s3_encryption.rego s3_encryption_test.rego
PASS: 4/4
Reading the Rego in plain language. default decision := ... is the fallback answer, "allow" with no violations, used when no other decision rule applies. violated contains res.id if { ... } builds a set of resource ids: some res in input.resources loops over every resource, and the id is added only when all the lines in the body hold (it is a bucket, it is not encrypted, and no exception covers it). excepted(id) is a small helper that is true when some exception row names this rule and this resource and has not yet expired (ISO dates compare correctly as text). mode := ... reads the warn or enforce setting from configuration data. The last two decision rules each apply only when there is at least one violation and the mode matches, so exactly one fires and sort keeps the violation list in a stable order. In the test file, with input as base swaps in the test's own input for that one evaluation, and with data.rules as ... and with data.exceptions as ... swap in test configuration, which is how one rule file is exercised in both modes. Tracing the first test: logs is encrypted, legacy is covered by an exception that expires 2026-12-31 (not before 2026-10-04), so only scratch is violated, and warn mode returns warn. After 2027-01-01 the exception no longer applies, so both legacy and scratch are denied.
The tests pin three behaviors: warn mode never blocks, enforce mode blocks only unexcepted violations, and an exception stops applying after its expires date.
Version and roll out (warn before enforce)
| Stage | Behavior | Gate to move on |
|---|---|---|
| 1. Test | Runs in CI on fixtures only | Unit tests plus the conflict check pass |
| 2. Warn | Evaluates real resources, reports, blocks nothing | Warning triage shows a low false-positive rate |
| 3. Enforce new | Blocks only resources created or changed after the date | Owners have a remediation path |
| 4. Enforce all | Blocks or auto-remediates existing resources too | Remaining exceptions are approved and dated |
Use semantic versions (numbers in MAJOR.MINOR.PATCH form, where a major bump such as 1.2.0 to 2.0.0 signals a change that can break existing users, here a rule that gets stricter) and pin each pipeline to a version so a rule change never lands unannounced. The promotion gate is a number, not a feeling. Illustrative: if a rule raised 200 warnings in 30 days and owners triaged 38 as false positives, that is 38 / 200 = 19%. I would not promote it, because roughly one block in five that enforcement produced would be a false block (the 19% is a share of the warnings, not a share of all deploys, so how many deploys it hits depends on how many deploys trigger the rule at all). Fix the logic, restart the clock. Pick your own threshold with the owners; the point is that one exists before warn mode starts.
Exceptions
Exceptions are data, not rule edits: rule, resource, approver, ticket, mandatory expiry date. Expired ones stop applying automatically (tested above), and the count of active exceptions per rule is a key risk indicator (KRI, a metric that signals rising risk). A rule with many exceptions is usually a bad rule, which feeds retirement. Accepting a lasting exception is a risk acceptance (a formal, recorded decision to live with a known risk) and belongs to the risk owner (the named person with authority over the affected system or business area), not to the engineer who wants the deploy.
Drift and remediation playbooks
Drift means live state no longer matches the desired state in infrastructure-as-code (infrastructure described in version-controlled files, such as Terraform). Detect it by evaluating the same rules against live cloud state on a schedule. Route by blast radius (how much could break if you fix it): auto-revert for safe, reversible fixes such as turning encryption on; open a ticket with a deadline for owner-fixed items; page someone only when exposure is active, such as a public bucket holding sensitive data. Every automatic fix writes an evidence record and notifies the owner.
Retire
Flag noisy rules (high false-positive rate from triage labels) and stale ones (no hits for a long period, or targeting a service or API that changed). Move a retiring rule to warn or audit-only first (a mode that evaluates and records results but never blocks), check the control-to-rule mapping so no control loses its only test, then delete it. Git history keeps the record for the auditor.
What would change my call
If rules are few and one team owns them all, skip the central platform. If a rule guards regulated data, skip the long warn stage and enforce on new resources immediately with a fast exception path.
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.
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.
What is policy as code, and how would you use it to make sure a publicly readable storage bucket can never reach production, without turning the check into a bottleneck for developers?
Sample Answer
Direct answer
Policy as code means writing a rule such as "no storage bucket may be publicly readable" as a small program kept in version control, instead of a wiki page. A machine evaluates every proposed infrastructure change against the rule and returns allow or deny with a reason. For "can never reach production", one check is not enough: you stack a plan-time check in CI (continuous integration, the automated build and test pipeline), an account-level guardrail that cannot be bypassed, and a runtime scan that catches drift (a live setting changing away from what the code says, for example someone editing a bucket by hand in the console).
Why it helps compliance
- Rules are versioned, so the history shows who changed which rule and when.
- Changes go through pull-request review, like application code.
- Rules are unit-testable, so you can prove the rule denies what it should.
- The same rule produces the same answer every run, which makes it usable as audit evidence.
Three layers, and which one gives the "never"
| Layer | Example | What it catches | Bypass risk |
|---|---|---|---|
| CI, on the Terraform plan (Terraform is a tool that creates cloud resources from code files, and its plan is a JSON description of what a change will create) | Deny a public ACL (access control list) or a disabled public-access block | Mistakes in code, before merge | Someone clicks in the console |
| Account or organization guardrail | S3 Block Public Access turned on for the account, plus an organization-level service control policy (SCP, a permission ceiling) denying anyone turning it off | Everything, including the console | None short of changing the guardrail |
| Runtime scan | Scheduled scan or AWS Config rule comparing live buckets to the same rule | Drift and anything created outside Terraform | Detects after the fact, so alert or auto-remediate |
The account-level guardrail is what actually makes "never" true. The CI rule is the fast, friendly feedback loop on top of it.
A plan-time rule (Rego, the language used by Open Policy Agent)
package terraform.s3public
import rego.v1
public_acls := {"public-read", "public-read-write", "authenticated-read"}
block_flags := ["block_public_acls", "block_public_policy", "ignore_public_acls", "restrict_public_buckets"]
changed(rc) if {
some action in rc.change.actions
action in {"create", "update"}
}
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_s3_bucket_acl"
changed(rc)
rc.change.after.acl in public_acls
msg := sprintf("%s: ACL '%s' makes the bucket publicly readable", [rc.address, rc.change.after.acl])
}
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_s3_bucket_public_access_block"
changed(rc)
some flag in block_flags
rc.change.after[flag] != true
msg := sprintf("%s: %s must be true", [rc.address, flag])
}
Given a plan excerpt with one public ACL and one half-open public-access block:
opa eval -f pretty -d s3_public.rego -i input.json 'data.terraform.s3public.deny'
with this input.json:
{"resource_changes":[{"address":"aws_s3_bucket_acl.site","type":"aws_s3_bucket_acl","change":{"actions":["create"],"after":{"acl":"public-read"}}},{"address":"aws_s3_bucket_public_access_block.reports","type":"aws_s3_bucket_public_access_block","change":{"actions":["create"],"after":{"block_public_acls":true,"block_public_policy":false,"ignore_public_acls":true,"restrict_public_buckets":true}}}]}
the real output is:
[
"aws_s3_bucket_acl.site: ACL 'public-read' makes the bucket publicly readable",
"aws_s3_bucket_public_access_block.reports: block_public_policy must be true"
]
Each message names the resource and the setting to fix, which is what keeps developers from filing a ticket.
Reading the rule in plain words
The package line names the rule set, and the two collections at the top are data: the ACL values that count as public (including authenticated-read, which grants read access to any AWS account holder and which S3 Block Public Access also treats as public), and the four switches of S3 Block Public Access (an AWS setting that stops a bucket from being made public) that must all be on. changed(rc) is a small test that is true when a resource change creates or updates something. Each deny contains msg if { ... } block reads as "add a message to the deny list if every line inside the braces is true". Inside, some rc in input.resource_changes means "look at each change in the plan in turn", and the lines after it filter that change down. The first block keeps only ACL resources being created or updated whose acl value is in the public set. The second keeps only public-access-block resources and, for each of the four switches, checks whether it is anything other than true (rc.change.after.flag is the value the setting will have once the plan is applied). msg := sprintf(...) builds the text. In the example input, site trips the first block because its ACL is public-read, and reports trips the second because block_public_policy is false, while its other three switches are on and produce nothing. An empty deny list means the plan passes.
Not a bottleneck
- The rule runs on the plan JSON inside the existing CI job, as a local function over a file, with no network service in the path.
- Start in warn mode, fix false positives, then enforce, and announce the enforce date.
- Offer a compliant-by-default Terraform module so most teams never trigger the rule.
- Exceptions are a reviewed file in the repo with an owner and an expiry date.
What it does not cover
Policy as code on the plan only sees what Terraform manages. A bucket created by hand never appears in a plan, which is why the account guardrail and the runtime scan exist.
In CI versus at runtime
CI classes: public exposure, missing encryption, mandatory tags, banned regions. Runtime or admission classes (Kubernetes admission is the moment the cluster accepts or rejects a new object): privileged containers, images from unapproved registries, and console-made changes. Tools to know: Open Policy Agent with Rego (used above and usable across Terraform, Kubernetes and APIs), Checkov (a scanner that ships with a large library of ready-made rules for Terraform and other infrastructure files), HashiCorp Sentinel (policy as code built into HashiCorp's commercial products), and, for Kubernetes clusters only, Kyverno and OPA Gatekeeper.
Unlock Full Question Bank
Get access to all 12 Compliance Automation and Tooling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.