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 plan outputs, missing ForceNew replacements (-/+), unmapped module renames, and 0.0.0.0/0 listener exposures, while lifecycle { prevent_destroy = true } disappears whenever a resource block is deleted.
  • Answer: Serialize speculative plans with tofu show -json (or terraform 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.

Evaluating compiled Terraform plan JSON with OPA before human review

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. ForceNew Replacement: 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 as change.actions containing ["delete", "create"] (or ["create", "delete"] when create_before_destroy is 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.primary to module.core_db.oci_database_db_system.production) without a Terraform 1.1+ moved block 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 immediate delete of the live production database and a create of an empty replacement.
  • Constraint 3 — lifecycle { prevent_destroy = true } Is Self-Defeating: Teams often rely on prevent_destroy = true inside resource blocks. However, if a developer deletes or replaces the surrounding module block during a refactor, the lifecycle block is deleted along with it. Worse, prevent_destroy only triggers at apply time—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_each maps, dynamic blocks, 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 as ForceNew in the current provider schema.

Declarative state constraints showing ForceNew replacement, missing moved blocks, and prevent_destroy deletion

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 OptionCatches ForceNew / RefactorsEvaluates Computed CIDRs & KMSSurvives Block DeletionWhy Rejected / Chosen
Human PR ReviewPoor — fatigue on large plansPoor — variables hide valuesYes (if noticed)Fails under volume; misses buried -/+ actions.
HCL Regex / Grep LintersFails — blind to state graphFails — cannot resolve localsNoHigh false-positive rate; ignores provider ForceNew logic.
lifecycle { prevent_destroy }Partial — fails at apply timeFails — no network/KMS checksNo — deleted with blockEasily bypassed by deleting the module or resource block.
Plan-JSON + OPA Gate (Chosen)100% deterministic on planFull resolved attribute checkYes — external to HCLEvaluates exact provider actions at PR time before review.

Comparison of human review, HCL regex linters, prevent_destroy, and Plan-JSON OPA gates

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.

Policy-as-Code CI architecture decoupling signed Rego bundles from database Terraform repositories

Architectural Policy Pillars

  1. Deterministic Plan-JSON Inspection: OPA evaluates input.resource_changes in the compiled plan JSON rather than raw HCL. Because Terraform and OpenTofu resolve all variable interpolations, moved blocks, and provider replacement flags during plan, Rego sees the exact actions array (["delete"], ["delete", "create"], or ["create", "delete"]) and change.after attributes. Checking "delete" in resource.change.actions catches both pure deletions and both replacement orderings (create_before_destroy on or off).
  2. Hierarchical Blast-Radius Guardrails: Policies separate benign in-place updates (such as freeform tag edits or storage scaling, where actions == ["update"]) from destructive delete and replace actions 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).
  3. 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 any INGRESS rule with source == "0.0.0.0/0" or "::/0" overlapping Oracle listener ports 1521 (Oracle Net), 2484 (TCPS), or 5500 (EM Express), as well as wildcard protocol rules (protocol == "all" or "6" with port range 1–65535).
  4. Mandatory Customer-Managed Encryption (CMEK) and after_unknown Handling: Policies verify that kms_key_id is non-empty on protected database and storage resources, rejecting null or provider-default encryption keys. Crucially, when a KMS key is provisioned in the same plan as the database, change.after.kms_key_id is null in tfplan.json while change.after_unknown.kms_key_id is true. Rego rules must explicitly check after_unknown or trace configuration.root_module references so new-environment bootstraps do not trigger false denials while still blocking unencrypted builds.
  5. Micro-State Decomposition: To keep tfplan.json small 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 isolate plan IAM 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.

Four-phase rollout from Rego fixture unit tests and audit-only mode to hard enforcement and break-glass

  1. Phase 1 — Rego Fixture Unit Testing (opa test): Collect sanitized tfplan.json snapshots from real past PRs (in-place tag edits, storage resizes, ForceNew replacements, after_unknown bootstraps, and module refactors) and build an opa test suite. 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.
  2. 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 speculative plan steps using a dedicated read-only OIDC role so PR runners can read state and cloud metadata without holding write or apply permissions, and delete tfplan.binary and tfplan.json in an always() 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.
  3. Phase 3 — Hard Blocking + Branch Protection: Flip the CI gate to exit 1 on violations and mark policy-evaluation as a required status check in GitHub branch protection. Validation gate: Confirm a test PR attempting an unapproved aws_db_instance replacement or 0.0.0.0/0 port 1521 rule is blocked automatically. Rollback: Revert the branch-protection requirement to audit-only if a provider upgrade triggers false-positive replacements.
  4. Phase 4 — Governed Break-Glass Decommissioning: Enforce CODEOWNERS requiring Lead DBA sign-off on any PR that sets decommission_approved = "true" or modifies policy references, paired with a pre-deletion snapshot check and a separate apply pipeline 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 encryption block (key_provider "aws_kms" with encryption_context, paired with method "aes_gcm" and enforced = 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 serialize tofu show -json in memory or ephemeral CI runners for OPA evaluation and clean up tfplan.json immediately after the job step completes.
  • OCI and AzureRM Resource Semantics: In the OCI and AzureRM Terraform providers, oci_database_db_system supports updatable freeform_tags and kms_key_id attributes while marking placement and shape-family changes as ForceNew, and azurerm_oracle_cloud_vm_cluster (for Oracle Database@Azure) marks name, location, and core cluster identity fields as replacement triggers. Evaluating tfplan.json catches these provider-specific replacement flags automatically without hardcoding every ForceNew field in Rego.
  • Terraform moved Block State-Graph Behavior: Introduced in Terraform 1.1 and supported in OpenTofu, a moved { from = ... to = ... } block rewrites the resource address inside state during plan and apply without invoking cloud provider destroy or create APIs. In tfplan.json, a valid moved refactor produces previous_address alongside actions: ["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 ForceNew specifications.

Where It Breaks

Automated policy gates introduce failure modes around state size, schema drift, and emergency operational paths.

Failure-path overlay showing monolithic state bottlenecks, self-approved tag bypass, schema drift, and missing moved blocks

Failure ConditionBreaks HowHow to DetectMitigation
Monolithic state fileThousands 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 tagAuthor 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 driftProvider 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 movedRefactoring 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 bundlesRunners 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 blockQuota 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_each loops, and provider ForceNew replacement flags.
  • Treat prevent_destroy as defense-in-depth, not a gate: Deleting a resource or module block deletes its lifecycle rule with it, and prevent_destroy cannot inspect NSG CIDRs or KMS keys.
  • Pair tag exemptions with CODEOWNERS: A Rego check for decommission_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.json evaluation fast, and SHA-pinned Rego bundles prevent runner policy drift.
  • Encrypt state at rest with OpenTofu 1.7+: Use aes_gcm with aws_kms and enforced = true to protect state files while running OPA on ephemeral CI runners.

What to Do Next

  • Problem: Human PR reviews miss buried -/+ database replacements and 0.0.0.0/0 exposures inside large Terraform execution plans, while prevent_destroy disappears when blocks are removed.
  • Solution: Gate every database IaC PR with OPA Rego policies evaluating tofu show -json (or terraform show -json) for deletions, public listener CIDRs, and mandatory CMEK keys, backed by CODEOWNERS and micro-states.
  • Proof: Export a real tfplan.json from your repository and verify with opa eval that an unapproved delete or 0.0.0.0/0 port 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.