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.
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.
Your company passes its annual audit every year, yet a misconfiguration sat live for months between audits and nobody noticed. How would you explain to a newer engineer why point-in-time compliance fails, and which checks would you automate first to make compliance continuous?
Sample Answer
Direct answer
An annual audit is a snapshot: it checks a sample of evidence from a window and passes you if what it looked at was in order. It says little about the days it did not look at. Continuous compliance replaces the occasional look with automated checks that run all the time, so a problem is found in hours or days, not at the next audit.
An analogy for a newer engineer
A yearly car inspection can pass a car whose brake warning light came on in March. Continuous compliance is the warning light: it tells you when the problem starts. The inspection still matters, because it checks that the light itself works.
Why point-in-time fails
- Sampling: auditors test a sample, meaning a small subset of records picked from the period, not every day of it.
- Preparation effect: teams tidy up before the audit, so the audited state is not the typical state.
- Gap: if a misconfiguration is live for 90 days, that is 90 of 365, about 24.7% of the year, with nobody watching.
- Cost of lateness: a problem found months later has had months to be exploited and is harder to trace.
What I would automate first
A baseline is the approved list of settings a system should have, so most of these checks are comparisons against it. Pick checks that are objective, frequent and costly when wrong:
- Configuration baselining: encryption on, public exposure off, admin MFA on, logging on. The check compares live state to that baseline daily.
- Change management evidence: every production change links to a reviewed, approved pull request, and the pipeline flags changes with no approval.
- Immutable artifacts: build once, sign, and deploy that exact artifact; servers are replaced, not hand-edited. An artifact is the packaged build output (a container image or a program file). Signing means the build system attaches a cryptographic stamp made from the artifact's contents and a secret key, and the deploy step refuses anything whose stamp does not verify. If someone edits the file by hand, its contents change, the stamp no longer matches, and the edit becomes a detectable difference. The artifact's hash (a short fingerprint of its bytes) recorded at deploy time shows exactly what was deployed.
- Alert health: check that logging and alerting still work, since silent failure here undermines all the others.
For example, a change record might read: change 4812, reviewed and approved by a named second person, merged at 14:02, artifact hash recorded, deployed at 14:09 (illustrative). For alert health, a daily test event must appear in the alerting system within a set time, and the record shows the last pass. These signals double as audit evidence: baseline scan results, change records with approvals and artifact hashes are exactly what an auditor asks for, already timestamped.
Worked example
The annual audit passed in January. A storage bucket became public in March and stayed so until July. A daily baseline check would have failed on day one in March, opened a ticket, and the fix would be visible as evidence. The July discovery would not exist.
Caveats
Automation covers what can be measured; policies, training and judgement calls still need people. Start with a handful of checks that matter, not a hundred that nobody reads.
You have telemetry, vulnerability feeds and control-check results for hundreds of services, and want a live per-service compliance and risk posture score that drives tickets and prioritization. How would you build it, how would you keep scores explainable to auditors and service owners, what would you automate versus route to a human, and how would you stop the score from being gamed or going stale?
Sample Answer
Direct answer
Compute the score as a deterministic, versioned function of check results, vulnerability age and freshness, and store every input so any score can be recomputed. Three rules keep it honest: a stale result counts as unknown, not pass; a failing critical control caps the score; and the data comes from collectors (central jobs or agents, run by a team other than the service owner, that gather check results from the systems) the service owner does not control. Automation opens tickets by threshold. People decide exceptions, scope and disputes.
Inputs and normalization
- Control-check results: pass, fail or unknown per control per service, with the run time.
- Vulnerability feeds: findings mapped to a service through an ownership catalog (a list that says which team owns which service), weighted by severity and age against the remediation deadline.
- Telemetry: for example whether logging is actually flowing. Convert to a pass or fail check first, so the score only consumes one kind of input. In the code below,
logging_enabledis that conversion.
Scoring logic and what it does
from datetime import date
TODAY = date(2026, 10, 4)
MAX_AGE_DAYS = 7 # a check result older than this counts as UNKNOWN, not pass
# (control id, weight, is_critical)
controls = [("mfa_enforced", 30, True), ("encryption_at_rest", 25, True),
("patch_sla_met", 25, False), ("logging_enabled", 20, False)]
# service -> control -> (result, date of last run)
results = {
"checkout": {"mfa_enforced": ("pass", date(2026, 10, 3)), "encryption_at_rest": ("pass", date(2026, 10, 3)),
"patch_sla_met": ("fail", date(2026, 10, 3)), "logging_enabled": ("pass", date(2026, 10, 2))},
"search": {"mfa_enforced": ("pass", date(2026, 10, 3)), "encryption_at_rest": ("fail", date(2026, 10, 3)),
"patch_sla_met": ("pass", date(2026, 10, 3)), "logging_enabled": ("pass", date(2026, 10, 3))},
"reports": {"mfa_enforced": ("pass", date(2026, 9, 10)), "encryption_at_rest": ("pass", date(2026, 10, 3)),
"patch_sla_met": ("pass", date(2026, 10, 3)), "logging_enabled": ("pass", date(2026, 10, 3))},
}
def score(svc):
total, earned, why, cap = sum(w for _, w, _ in controls), 0, [], 100
for cid, w, critical in controls:
res, ran = results[svc][cid]
state = res if (TODAY - ran).days <= MAX_AGE_DAYS else "unknown"
if state == "pass":
earned += w
else:
why.append(f"{cid}={state}(-{w})")
if critical:
cap = 59 # a failing or unknown critical control caps the score
raw = round(100 * earned / total)
return min(raw, cap), raw, why
for svc in results:
final, raw, why = score(svc)
print(f"{svc}: score={final} (raw {raw}) reasons: {', '.join(why) or 'none'}")
checkout: score=75 (raw 75) reasons: patch_sla_met=fail(-25)
search: score=59 (raw 75) reasons: encryption_at_rest=fail(-25)
reports: score=59 (raw 70) reasons: mfa_enforced=unknown(-30)
The weights are illustrative. Checkout scores 75 with one failing non-critical control. Search has the same raw 75 but scores 59 because its failing control is critical (encryption at rest). Reports has a raw 70, and the 59 comes from the MFA check last run on 2026-09-10, 24 days before 2026-10-04, past the 7-day freshness limit, so it counts as unknown and the critical cap applies. Weights and the cap are the policy choices to agree with service owners and the security leadership, and a model change must be backtested (replayed over past data to see which scores the new weights would have produced) before release.
The cap of 59 is deliberately one point below the illustrative ticket line of 60 used in the table below, so a failing or unknown critical control always opens a ticket however well the service scores elsewhere.
Vulnerability age enters the same way, as a converted check. In the code, patch_sla_met is the result of that conversion: it passes only if no open finding is older than its deadline (illustrative deadlines: 15 days for critical, 30 for high, 90 for medium). Checkout has a critical finding opened on 2026-09-10, which is 24 days old on 2026-10-04 against a 15-day deadline, so patch_sla_met fails and costs 25 points, which is the checkout result above.
Explainability for auditors and owners
Store per score: the inputs, each control's contribution, the scoring-model version and the timestamp. The owner sees "you lost 25 points because patch_sla_met failed" instead of an opaque number. An auditor can recompute a score from stored inputs. The score is a prioritization aid: audit evidence is still the control-level results underneath it.
Automate versus human
| Automate | Route to a human |
|---|---|
| Open a ticket when a critical control fails or the score drops below an agreed line (illustrative: 60) | Risk acceptance and exceptions |
| Start SLA timers and escalate on breach | Fixes that could break production |
| Auto-remediate safe, reversible items | Score disputes and scope questions |
| Alert when a collector stops reporting | Changes to weights and thresholds |
Stop it being gamed
- Results come from central collectors, not self-reports.
- The inventory is the source of truth: anything running but not in the catalog is flagged as unowned, so a service cannot escape by omission.
- Exceptions expire and visibly reduce the score.
- A small random sample of passes is independently re-verified each quarter.
- Do not tie the score directly to individual performance reviews. People optimize whatever is measured (Goodhart's law: a measure that becomes a target stops being a good measure).
Stop it going stale
The freshness rule above, a heartbeat alert from each collector (an alert when its regular "I am alive" signal stops), and an "as of" timestamp on every score shown. A dashboard that looks green because collectors died is the worst failure mode, which is why unknown is scored as not-pass.
You are asked to automate evidence collection for SOC 2 controls across change management, access controls, and logging. How would you map each control to automated checks or continuous evidence collection, what tools would you use, and how would you present audit-ready artifacts to an external auditor?
Sample Answer
Direct answer
For each SOC 2 control I would write down the population (every event the control applies to), a machine check that tests each item in it, and an evidence record the check emits. SOC 2 is a report issued by an independent CPA firm, under AICPA attestation standards, in which the auditor tests an organization's controls against the Trust Services Criteria (the AICPA's published criteria, grouped into five categories: security, availability, processing integrity, confidentiality and privacy; the CC-numbered references below are the common criteria that apply to security). A Type I report tests only whether controls are designed properly at a single date; a Type II report tests whether they actually operated over a stated period of time, so the evidence has to be continuous, not a point-in-time screenshot. I would build collectors against the systems of record (source control, the identity provider, the cloud logs), land the results in a restricted evidence store, and give the auditor a read-only, indexed view.
Control to check mapping
| Area | SOC 2 criterion | ISO 27001:2022 Annex A | Automated check | Evidence record |
|---|---|---|---|---|
| Change management | CC8.1 | 8.32 | Every production deploy links to a merged pull request, the approver differs from the author, required status checks passed | Deploy ID, PR ID, author, approver, check results, timestamps |
| Access controls | CC6.1, CC6.2, CC6.3 | 5.15, 5.18, 8.5 | Identity provider export: MFA (multi-factor authentication) enabled for every user; leavers from the HR system disabled in the identity provider within the policy window; access reviews closed | User list with MFA flag, leaver date versus disable date, review ticket IDs |
| Logging and monitoring | CC7.2 | 8.15, 8.16 | Audit logging enabled in every account and region, log integrity validation on, retention setting meets policy, alert rules exist and fire | Config snapshot, retention value, alert test result |
In plain terms, the SOC 2 references ask for: CC6.1, restricting access to systems and data to authorized users; CC6.2, registering and authorizing users before credentials are issued and removing access when it is no longer authorized; CC6.3, granting access by role with least privilege and separation of duties; CC7.2, monitoring systems for anomalies; CC8.1, authorizing, testing, approving and implementing changes. The ISO Annex A numbers are titled 5.15 Access control, 5.18 Access rights, 8.5 Secure authentication, 8.15 Logging, 8.16 Monitoring activities and 8.32 Change management. You are not expected to memorize them; the habit to show is naming the control's purpose and then the check that proves it.
ISO 27001 Annex A is the catalogue of controls an organization selects from, and the Statement of Applicability is the document listing which ones apply and why. Mapping each check to an Annex A reference lets the same evidence serve continuous ISO auditing and reduces manual gathering. For the management-system side of ISO 27001 (the ISMS, the documented set of policies, processes and responsibilities an organization runs to manage information security), the same records support clause 9.1, which requires the organization to decide what to monitor and measure and to evaluate the results, and the internal audit under clause 9.2, a check at planned intervals that the ISMS meets the standard and the company's own rules.
Tools
Pull from the APIs of the systems of record: source control (GitHub or GitLab), an identity provider (Okta or Microsoft Entra ID are examples), the HR system, cloud audit logs (AWS CloudTrail is an example), and the ticketing system. The categories matter more than the product names; use whichever products the company already runs. Either build thin collectors that write to the evidence store, or use a compliance automation platform such as Vanta or Drata for the integrations and spend your effort on the checks those platforms do not cover.
Worked example (illustrative data)
Three production deploys in a month:
| Deploy | Merged PR | Approver is not author | Checks passed | Result |
|---|---|---|---|---|
| D-101 | yes | yes | yes | pass |
| D-102 | yes | yes | yes | pass |
| D-103 | yes | no (self-approved hotfix) | yes | fail, 1 exception |
The failure is recorded, not hidden: it carries an exception ID and a later review by another engineer. Two of three pass, and the auditor sees the one that failed.
Presenting audit-ready artifacts
- An evidence index per control: control ID, test ID, period, population count, sample the auditor picks, links to records.
- The full population as a file, since automation can cover all items where the auditor would otherwise sample.
- A read-only auditor role, time-limited and logged, with access only to the evidence prefix.
- No secrets in evidence: store configuration values and IDs, redact tokens, and scan records for credentials before they are stored.
- Access control on the evidence store itself: writers cannot delete, admins are a separate group, and every read is logged.
- Timestamps from the collector plus the run time, kept in the record.
- Retention: keep records for the audit period plus the time needed for the auditor's follow-up questions and your own retention schedule, with counsel confirming any longer requirement.
- Scope changes without rework: checks iterate over an inventory built from the cloud account list and tags, so a new account is included automatically and each run records the scope it covered.
Limits
Automation proves the check ran and what it saw. The auditor still judges whether the control was well designed and whether the population was complete, and some controls, such as a vendor risk review, stay manual.
Unlock Full Question Bank
Get access to all 14 Compliance Automation and Tooling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.