Policy as Code at Hyper-Scale: Preventing Destructive Database Operations in CI/CD
Relying on human code reviews to parse complex Infrastructure as Code execution plans guarantees that a production database will eventually be destroyed by an accidental resource replacement.
TL;DR
- Problem: Human PR reviewers inspect HCL diffs rather than multi-thousand-line
terraform planoutputs, missingForceNewreplacements (-/+), unmapped module renames, and0.0.0.0/0listener exposures, whilelifecycle { prevent_destroy = true }disappears whenever a resource block is deleted.- Answer: Serialize speculative plans with
tofu show -json(orterraform show -json) and gate every PR through Open Policy Agent (OPA) Rego rules that block unauthorized deletes, public listener CIDRs, and missing customer-managed KMS keys before human review.- Watch out: Monolithic state files bloat plan JSON evaluation times, self-approved decommission tags bypass safety checks unless paired with
CODEOWNERS, and OpenTofu 1.7 state encryption must be paired with external OPA evaluation rather than assuming an embedded policy engine.
Situation
Platform engineering teams manage cloud database fleets—across Oracle Cloud Infrastructure (OCI), Amazon Web Services (AWS), and Microsoft Azure—using declarative Infrastructure as Code (IaC) engines such as Terraform and OpenTofu. Daily pull requests (PRs) resize compute shapes, expand block volumes, adjust subnet routes, update parameter groups, and refactor shared modules.
A standard database IaC pipeline follows four steps: a developer edits HCL and opens a PR, the CI runner executes a speculative plan, a peer reviewer inspects the diff, and merge triggers apply against cloud provider APIs. When a state file grows to hundreds or thousands of managed resources, a single refactoring PR generates thousands of lines of plan output. Human reviewers naturally focus on the readable HCL diff—variable names, tags, and module structure—rather than auditing every attribute change inside the compiled execution plan.
The Problem
Human code review breaks down against four structural constraints in declarative IaC engines:
- Constraint 1 — Plan-Parsing Fatigue vs.
ForceNewReplacement: Cloud database resources (oci_database_db_system,oci_database_cloud_vm_cluster,aws_db_instance,azurerm_oracle_cloud_vm_cluster) treat core attributes—such as availability domain, subnet or VCN placement, or certain KMS key bindings—as immutable (ForceNew). Modifying one of those attributes in HCL does not trigger an in-place update; Terraform plans a destroy-and-recreate (-/+), represented in the compiled plan JSON aschange.actionscontaining["delete", "create"](or["create", "delete"]whencreate_before_destroyis set). At a careful human reading pace of roughly 50 lines per minute, auditing a 3,000-line plan output takes 60 minutes of uninterrupted attention per PR—an unsustainable tax when teams merge dozens of infrastructure PRs per week. - Constraint 2 — State Identity Breaks on Module Refactors: Renaming a module or resource address (for example,
module.core_db.oci_database_db_system.primarytomodule.core_db.oci_database_db_system.production) without a Terraform 1.1+movedblock severs the state-address mapping. In the state graph, the old address disappears and the new address has no prior state, so the engine schedules an immediatedeleteof the live production database and acreateof an empty replacement. - Constraint 3 —
lifecycle { prevent_destroy = true }Is Self-Defeating: Teams often rely onprevent_destroy = trueinside resource blocks. However, if a developer deletes or replaces the surrounding module block during a refactor, thelifecycleblock is deleted along with it. Worse,prevent_destroyonly triggers atapplytime—often after preceding dependencies have already been mutated—and inspects nothing about network ingress CIDRs (0.0.0.0/0) or customer-managed encryption keys. - Constraint 4 — Unresolved Variables in HCL Source: Raw HCL files hide computed values behind
locals,for_eachmaps,dynamicblocks, and module outputs. Static source-code grep checks (and even AST-only HCL linters) cannot reliably determine whether a dynamically constructed NSG rule opens TCP port 1521 to the public internet, nor can they see whether a provider marks an attribute change asForceNewin the current provider schema.
How do platform teams build deterministic CI/CD gates that inspect resolved infrastructure mutations before merge, blocking accidental deletions, public database exposure, and unencrypted storage?
Options Considered
Platform teams typically evaluate four governance mechanisms before adopting plan-JSON Policy as Code.
| Governance Option | Catches ForceNew / Refactors | Evaluates Computed CIDRs & KMS | Survives Block Deletion | Why Rejected / Chosen |
|---|---|---|---|---|
| Human PR Review | Poor — fatigue on large plans | Poor — variables hide values | Yes (if noticed) | Fails under volume; misses buried -/+ actions. |
| HCL Regex / Grep Linters | Fails — blind to state graph | Fails — cannot resolve locals | No | High false-positive rate; ignores provider ForceNew logic. |
lifecycle { prevent_destroy } | Partial — fails at apply time | Fails — no network/KMS checks | No — deleted with block | Easily bypassed by deleting the module or resource block. |
| Plan-JSON + OPA Gate (Chosen) | 100% deterministic on plan | Full resolved attribute check | Yes — external to HCL | Evaluates exact provider actions at PR time before review. |
Human review alone was rejected because plan volume scales faster than reviewer attention. HCL regex linters and static AST scanners (such as tflint or tfsec running without a plan) were rejected as the primary gate because they cannot resolve for_each expressions, cross-module outputs, state-graph diffs, or provider-level ForceNew semantics. Native prevent_destroy blocks were rejected as a sole control because they vanish when a resource block is removed, fail only during apply rather than PR review, and offer zero protection against opening port 1521 to 0.0.0.0/0. Evaluating the compiled tfplan.json with Open Policy Agent (OPA) inspects the exact state transitions the provider will execute, including prior_state, planned_values, and resource_changes.
The Policy-as-Code Pipeline Architecture
The target architecture decouples policy enforcement from application Terraform repositories by evaluating serialized plan JSON (tofu show -json tfplan.binary) against a pinned, versioned Rego policy bundle in CI before peer review begins.
Architectural Policy Pillars
- Deterministic Plan-JSON Inspection: OPA evaluates
input.resource_changesin the compiled plan JSON rather than raw HCL. Because Terraform and OpenTofu resolve all variable interpolations,movedblocks, and provider replacement flags duringplan, Rego sees the exactactionsarray (["delete"],["delete", "create"], or["create", "delete"]) andchange.afterattributes. Checking"delete" in resource.change.actionscatches both pure deletions and both replacement orderings (create_before_destroyon or off). - Hierarchical Blast-Radius Guardrails: Policies separate benign in-place updates (such as freeform tag edits or storage scaling, where
actions == ["update"]) from destructivedeleteandreplaceactions on stateful database primitives (oci_database_db_system,oci_database_cloud_vm_cluster,oci_database_autonomous_database,aws_db_instance,aws_rds_cluster,azurerm_oracle_cloud_vm_cluster). - Network Zero-Exposure Enforcement: Policies inspect all security rules (
oci_core_network_security_group_security_rule,aws_security_group_rule,aws_vpc_security_group_ingress_rule) and deny anyINGRESSrule withsource == "0.0.0.0/0"or"::/0"overlapping Oracle listener ports1521(Oracle Net),2484(TCPS), or5500(EM Express), as well as wildcard protocol rules (protocol == "all"or"6"with port range1–65535). - Mandatory Customer-Managed Encryption (CMEK) and
after_unknownHandling: Policies verify thatkms_key_idis non-empty on protected database and storage resources, rejecting null or provider-default encryption keys. Crucially, when a KMS key is provisioned in the sameplanas the database,change.after.kms_key_idisnullintfplan.jsonwhilechange.after_unknown.kms_key_idistrue. Rego rules must explicitly checkafter_unknownor traceconfiguration.root_modulereferences so new-environment bootstraps do not trigger false denials while still blocking unencrypted builds. - Micro-State Decomposition: To keep
tfplan.jsonsmall and OPA evaluation sub-second, database state files are partitioned by environment and tier (network, IAM, database cluster) rather than stored in a single monolithic state. Smaller state files also limit the blast radius of state-lock contention and isolateplanIAM permissions per tier.
Production Rego Policies and GitHub Actions Workflow
The anti-destruction policy (database_safety.rego) inspects resource_changes for any "delete" action on protected database types and requires explicit decommissioning tags gated by CODEOWNERS:
package terraform.database.safety
import future.keywords.in
protected_database_types := {
"oci_database_db_system",
"oci_database_cloud_vm_cluster",
"oci_database_autonomous_database",
"aws_db_instance",
"aws_rds_cluster",
"azurerm_oracle_cloud_vm_cluster"
}
deny[msg] {
some resource in input.resource_changes
resource.type in protected_database_types
"delete" in resource.change.actions
not is_authorized_decommission(resource)
msg := sprintf(
"CRITICAL GOVERNANCE VIOLATION: '%v' (%v) plans destruction (%v) without decommission approval.",
[resource.address, resource.type, resource.change.actions]
)
}
is_authorized_decommission(resource) {
after := object.get(resource.change, "after", {})
tags := object.get(after, "freeform_tags", {})
tags["decommission_approved"] == "true"
object.get(tags, "decommission_ticket_id", "") != ""
}
The network isolation policy (network_security.rego) checks OCI NSG rules for 0.0.0.0/0 ingress overlapping database listener ports:
package terraform.database.security
import future.keywords.in
database_listener_ports := {1521, 2484, 5500}
deny[msg] {
some resource in input.resource_changes
resource.type == "oci_core_network_security_group_security_rule"
after := object.get(resource.change, "after", {})
after.direction == "INGRESS"
after.source_type == "CIDR_BLOCK"
after.source == "0.0.0.0/0"
tcp_options := after.tcp_options[_]
port_range := tcp_options.destination_port_range[_]
some port in database_listener_ports
port >= port_range.min
port <= port_range.max
msg := sprintf(
"SECURITY VIOLATION: NSG rule '%v' exposes database port %v to 0.0.0.0/0.",
[resource.address, port]
)
}
The GitHub Actions workflow generates tfplan.json, evaluates both packages, and posts violations back to the PR:
name: "Database IaC Policy Verification"
on:
pull_request:
paths: ["terraform/databases/**"]
jobs:
policy-evaluation:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v4
- uses: opentofu/setup-opentofu@v1
with:
tofu_version: 1.7.2
- uses: open-policy-agent/setup-opa@v2
with:
version: 0.62.0
- working-directory: terraform/databases
run: |
tofu init -backend=false
tofu plan -out=tfplan.binary
tofu show -json tfplan.binary > tfplan.json
opa eval --data ../../policies/ --input tfplan.json --format pretty \
"data.terraform.database.safety.deny" > violations.txt
if grep -q "CRITICAL GOVERNANCE VIOLATION" violations.txt; then
cat violations.txt
exit 1
fi
How It Rolls Out
Turning on hard-blocking OPA gates across an active repository without prior fixture testing creates immediate developer friction and console-bypass pressure. Roll out enforcement in four gated phases.
- Phase 1 — Rego Fixture Unit Testing (
opa test): Collect sanitizedtfplan.jsonsnapshots from real past PRs (in-place tag edits, storage resizes,ForceNewreplacements,after_unknownbootstraps, and module refactors) and build anopa testsuite. Validation gate: 100% pass rate on expected allows and denies before touching CI pipelines. Rollback: Fix Rego edge cases in the policy repo without affecting app teams. - Phase 2 — Audit-Only PR Comments with Credential Isolation: Deploy the GitHub Actions workflow in non-blocking mode (commenting violations on PRs without
exit 1). Run speculativeplansteps using a dedicated read-only OIDC role so PR runners can read state and cloud metadata without holding write orapplypermissions, and deletetfplan.binaryandtfplan.jsonin analways()cleanup step because plan files contain resolved resource attributes and sensitive outputs. Validation gate: Audit two weeks of PRs to identify existing non-compliant NSGs, missing KMS keys, or provider schema quirks. Rollback: Disable the workflow trigger if runner latency spikes. - Phase 3 — Hard Blocking + Branch Protection: Flip the CI gate to
exit 1on violations and markpolicy-evaluationas a required status check in GitHub branch protection. Validation gate: Confirm a test PR attempting an unapprovedaws_db_instancereplacement or0.0.0.0/0port 1521 rule is blocked automatically. Rollback: Revert the branch-protection requirement to audit-only if a provider upgrade triggers false-positive replacements. - Phase 4 — Governed Break-Glass Decommissioning: Enforce
CODEOWNERSrequiring Lead DBA sign-off on any PR that setsdecommission_approved = "true"or modifies policy references, paired with a pre-deletion snapshot check and a separateapplypipeline that re-validates the signed plan digest.
In Practice
The behavior of this pipeline rests on documented Terraform, OpenTofu, and OPA semantics:
- OpenTofu 1.7 Native State and Plan Encryption: OpenTofu 1.7 introduced client-side State and Plan Encryption using an
encryptionblock (key_provider "aws_kms"withencryption_context, paired withmethod "aes_gcm"andenforced = true). While encrypting state and plan artifacts at rest protects sensitive credentials from backend storage leaks, OpenTofu 1.7 does not include an embedded Rego policy engine—meaning teams still serializetofu show -jsonin memory or ephemeral CI runners for OPA evaluation and clean uptfplan.jsonimmediately after the job step completes. - OCI and AzureRM Resource Semantics: In the OCI and AzureRM Terraform providers,
oci_database_db_systemsupports updatablefreeform_tagsandkms_key_idattributes while marking placement and shape-family changes asForceNew, andazurerm_oracle_cloud_vm_cluster(for Oracle Database@Azure) marksname,location, and core cluster identity fields as replacement triggers. Evaluatingtfplan.jsoncatches these provider-specific replacement flags automatically without hardcoding everyForceNewfield in Rego. - Terraform
movedBlock State-Graph Behavior: Introduced in Terraform 1.1 and supported in OpenTofu, amoved { from = ... to = ... }block rewrites the resource address inside state duringplanandapplywithout invoking cloud provider destroy or create APIs. Intfplan.json, a validmovedrefactor producesprevious_addressalongsideactions: ["no-op"](or["update"]if attributes also changed), allowing the OPA anti-destruction rule to pass cleanly while still blocking any unmapped rename that falls back to["delete", "create"]. - CARL Acknowledgment: I have not operated a multi-thousand-resource OCI/AzureRM Terraform monorepo personally; the policy mechanics above derive from documented Terraform/OpenTofu plan JSON schemas, Open Policy Agent Rego evaluation rules, and provider
ForceNewspecifications.
Where It Breaks
Automated policy gates introduce failure modes around state size, schema drift, and emergency operational paths.
| Failure Condition | Breaks How | How to Detect | Mitigation |
|---|---|---|---|
| Monolithic state file | Thousands of resources in one state generate huge tfplan.json files that slow CI and OPA. | Track CI job duration and tfplan.json file size per repo. | Decompose monolithic states into micro-states per database or tier. |
| Self-approved decommission tag | Author adds decommission_approved = "true" in the same PR to bypass the delete rule. | Audit PR diffs modifying decommission_approved without DBA review. | Require CODEOWNERS approval from Lead DBAs for retirement PRs. |
| Provider schema drift | Provider upgrade renames a JSON key; Rego lookup returns undefined and fails open. | Run opa test against new provider plan fixtures during upgrades. | Use object.get() with safe defaults and pin provider versions. |
Module rename without moved | Refactoring renames a resource address; Terraform plans delete+create and OPA blocks it. | CI detects paired delete + create of identical resource types. | Require Terraform 1.1+ moved blocks for all address refactors. |
| Unpinned policy bundles | Runners pull mutable main branch Rego rules, causing inconsistent staging vs. prod blocks. | Compare OPA bundle digest logged in CI run metadata. | Distribute policies as SHA-pinned Git submodules or signed OCI artifacts. |
| Emergency storage block | Quota or budget Rego rule blocks an urgent disk expansion during an ORA-00257 outage. | Monitor emergency-label PRs blocked by policy checks. | Maintain a pre-approved fast-path runbook/exemption for storage expansion. |
When onboarding new provider releases, keep a golden suite of sanitized tfplan.json fixtures covering both permitted changes and intentional policy violations. Running opa test against those fixtures on every policy or provider version bump catches silent schema renames before a broken rule reaches production pull requests.
Key Takeaways
- Evaluate compiled
tfplan.json, never raw HCL: Only the serialized plan resolves variables,for_eachloops, and providerForceNewreplacement flags. - Treat
prevent_destroyas defense-in-depth, not a gate: Deleting a resource or module block deletes itslifecyclerule with it, andprevent_destroycannot inspect NSG CIDRs or KMS keys. - Pair tag exemptions with
CODEOWNERS: A Rego check fordecommission_approved == "true"is only safe if branch protection prevents the PR author from self-approving that tag. - Keep states small and policies pinned: Micro-states keep
tfplan.jsonevaluation fast, and SHA-pinned Rego bundles prevent runner policy drift. - Encrypt state at rest with OpenTofu 1.7+: Use
aes_gcmwithaws_kmsandenforced = trueto protect state files while running OPA on ephemeral CI runners.
What to Do Next
- Problem: Human PR reviews miss buried
-/+database replacements and0.0.0.0/0exposures inside large Terraform execution plans, whileprevent_destroydisappears when blocks are removed. - Solution: Gate every database IaC PR with OPA Rego policies evaluating
tofu show -json(orterraform show -json) for deletions, public listener CIDRs, and mandatory CMEK keys, backed byCODEOWNERSand micro-states. - Proof: Export a real
tfplan.jsonfrom your repository and verify withopa evalthat an unapproveddeleteor0.0.0.0/0port 1521 rule returns exit code 1 while benign tag updates pass. - Action: Add the OPA step in audit-only mode to your database Terraform CI workflow this week, remediate any existing violations it surfaces, and then enable branch-protection enforcement.