27 November 2026

Policy as Code Terraform Guide: Test and Enforce in CI

Reza Khosravi

Table of Contents

Policy as Code Terraform Guide: Test and Enforce in CI

Your Terraform pull request is green. terraform validate passes, the plan looks reasonable, and the coding agent has explained why the change should work. Then a reviewer notices that the storage configuration doesn't meet your encryption standard, and nobody knows whether the emergency exception from the last release still applies.

Policy as code for Terraform should resolve that uncertainty before deployment. The hard part isn't writing a deny expression. It's proving the plan contains enough evidence, testing the rule against awkward changes, and deciding who owns the control when it blocks a legitimate release.

Where Policy Checks Run in a Terraform Workflow

What each Terraform stage gives a policy

StageWhat policy can readGood forLimit
terraform validateConfiguration syntax and schemaCatching malformed blocksSays nothing about security
terraform plan JSONPlanned changes and known valuesRegion, encryption, public exposure, deletesComputed and unknown values aren't available as concrete values
Apply timeProvider-generated IDs and final valuesChecks that depend on realized stateToo late to prevent creation
After deploymentRealized resourcesDrift and detective controlsViolations already exist

terraform validate catches malformed configuration and schema errors. It doesn't establish that a valid configuration is safe. A resource can satisfy its provider schema while violating your organization's network, location, or encryption requirements.

The saved plan gives OPA or Sentinel a different input: the proposed infrastructure change. This is the useful preventive gate between planning and applying, when a policy can inspect resolved configuration and stop provisioning. Configuration checks can run earlier, but they don't have the same evaluated change context.

In OPA's 2021 community survey, more than 150 organizations responded, 91% reported some stage of OPA adoption, and Terraform validation accounted for 25% of reported use cases, behind Kubernetes admission control at 54%. Those community-based figures are adoption signals, not estimates of universal market penetration.

Separate provider failures from policy failures

A provider authentication problem or malformed provider response isn't a security-policy denial. Keep those failure categories separate in CI so developers don't request policy exceptions to fix infrastructure tooling.

For redirect resources specifically, RedirHub's Terraform provider troubleshooting for redirects is a useful diagnostic resource before investigating the policy evaluator. A policy job needs a valid plan before it can make a meaningful decision.

Run terraform plan -out=tfplan, then terraform show -json tfplan > plan.json. Inspect the relevant resource under resource_changes, including change.after and change.after_unknown, and confirm that the required attribute is present and known.

Plan-time boundary: If the fact your rule needs is unknown until apply, the plan cannot prove that fact compliant.

How to Write a Plan-Time Terraform Policy

Use a governed workflow: requirements, development, testing, review, and release. HashiCorp's account of Fannie Mae's Sentinel development process describes this progression and emphasizes documenting policies and tests so maintainers can understand them later.

Choose the engine before implementing the rule. OPA with Rego fits a portable CI workflow, often through Conftest; Sentinel fits checks managed through HCP Terraform or Terraform Enterprise. DevArmor's guide to Rego explains the language if your team is taking the OPA route.

A five-step infographic illustrating the process of creating plan-time Terraform policies, from requirements to release.

Turn the requirement into an executable decision

  1. Write a pass/fail condition. Specify the resource types, applicable actions, and required attributes, such as requiring newly provisioned storage buckets to have an approved encryption configuration. This makes the requirement testable; “secure storage” is an objective, not a policy specification.

  2. Generate tfplan with terraform plan -out=tfplan, then convert it using terraform show -json tfplan > plan.json. Locate the actual fields your policy needs rather than copying attribute paths from provider documentation, because the JSON structure and resource relationships matter.

  3. Implement against stable plan fields. Start with resource_changes[*].type, address, change.actions, and relevant values under change.after; use an explicit action filter so updates and replacements aren't accidentally excluded. The common mistake is treating every change as a simple create or assuming a deleted resource has an after-state.

  4. Give unavailable evidence its own outcome, such as needs review. Inspect unknown markers before interpreting an absent or null attribute, because missing configuration and unresolved configuration aren't automatically the same condition.

  5. Save compliant and intentionally violating plans as fixtures, with expected decisions and resource addresses. A passing fixture proves the rule accepts something legitimate; the violating fixture proves it can reject the condition it was written to stop.

  6. Require independent review before release. Have another engineer examine the predicates, resource associations, messages, and exception path, then merge through a version-controlled feature branch. Skipping the rationale and fixture documentation leaves the next maintainer guessing whether an awkward condition is deliberate.

Make the bucket rule match the provider model

A bucket-encryption deny rule should identify the affected aws_s3_bucket address and explain the missing approved configuration. However, don't assume encryption lives directly inside that resource's change.after.

When the provider models encryption through aws_s3_bucket_server_side_encryption_configuration, the policy must associate that configuration with its bucket. An unresolved bucket identifier may require configuration-reference analysis or a review outcome. A rule that checks the wrong resource shape isn't strict security; it's a false-positive generator.

Test Cases That Catch the Failures Teams Miss

A Terraform policy can only decide from its input. OPA's Terraform documentation describes evaluation over generated plan JSON and a testing workflow, making the plan's available evidence the starting point for fixture design.

Inventory which inputs are known, unknown, sensitive, or computed before writing assertions. Provider-generated identifiers and other apply-time facts can't support the same preventive guarantees as explicit configuration.

Plan test cases every policy needs

Test casePlan changeCommon missExpected result
CreateNew resource with the settingMissing encryption on new bucketsFail when the setting is absent
UpdateExisting resource changes an attributeSettings loosened in placeFail on the changed value
DeleteResource removed from configurationRules that only check createsPass only if the deletion is allowed
ReplacementDestroy and create in one planInsecure resource recreated unnoticedEvaluate the new resource
Unknown valueAttribute computed at apply timeFalse negatives from null valuesFlag for review, never pass silently
Sensitive valueAttribute marked sensitive in planSecrets leaking into logsRedacted output, still checked
Compliant baselineFully compliant planFalse positivesPass
Intentional violationKnown bad settingRule that never firesFail with the correct resource address

Test decisions, not just execution

Creates are straightforward, which makes them a dangerous stopping point. An update fixture should demonstrate that the rule catches a previously acceptable resource becoming unsafe, rather than merely noticing that a resource exists.

Deletion requires a separate decision. An encryption requirement shouldn't fail because a deleted bucket has no after-state, while a retention control may legitimately prohibit removing that bucket. Replacement fixtures must inspect the proposed replacement, whether the action ordering creates first or destroys first.

Name fixtures after the control and outcome, such as encrypted-bucket-create-fail. Assert the decision, control identifier, and resource address, not merely that evaluation completed without an error.

Unknown-value fixtures should exercise change.after_unknown. Sensitive-value fixtures should verify both the decision and the output: the evaluator may need the value, but the pull request comment doesn't. Never use real credentials in committed test plans.

Keep preventive and detective checks distinct

Compare each rule against a compliant baseline to expose overbroad predicates. If adding an unrelated resource makes the baseline fail, investigate the policy's scope before blaming the fixture.

For requirements that cannot be established during planning, use split enforcement: block the determinable unsafe configuration before apply, then inspect the realized resource afterward. Give the post-deployment check an owner and a remediation path rather than pretending it offers preventive coverage.

A policy with no violating fixture hasn't proved that it can fire.

Wiring the Policy Gate into CI Pull Requests

A useful CI gate connects a specific commit, Terraform root module, workspace, plan artifact, and policy-bundle revision. If those identities aren't recorded together, a green result can belong to the wrong infrastructure change.

Treat the evaluator as part of your CI/CD pipeline security boundary. Pull request code shouldn't gain unrestricted cloud credentials because the job needs to produce a plan.

A five-step infographic showing the automated workflow for wiring policy gates into CI pull requests using Terraform.

Build the blocking path explicitly

  1. Run policy tests on every pull request. Use opa test policies/ tests/ for a compatible OPA test layout, and require success before planning. A broken policy bundle shouldn't proceed to infrastructure evaluation.

  2. Initialize and plan each affected root module with terraform init and terraform plan -out=tfplan. Include roots affected by shared-module changes, not just directories with directly modified files, and select the intended backend, workspace, and variable inputs.

  3. Convert the saved plan. Run terraform show -json tfplan > plan.json in the matching Terraform environment. Fail the job if planning or conversion fails; an empty or stale JSON file is not a substitute.

  4. Evaluate plan.json against the pinned policy bundle using OPA or a wrapper, for example conftest test plan.json -p policies/. If using opa eval directly, explicitly translate the decision into an exit status: successful query execution doesn't mean the queried policy allowed the change.

  5. Post actionable findings. Each pull request comment should contain the control identifier, resource address, remediation note, and enforcement mode. Link an approved exception record when one applies, without printing sensitive input values.

  6. Configure the blocking job as a required status check. Make missing evaluation, policy-engine errors, and unresolved mandatory decisions fail closed rather than disappear as skipped jobs.

  7. Retain the evaluated plan JSON and decision record as restricted build artifacts. Apply an appropriate retention policy and access controls because machine-readable plans can contain sensitive values.

Prevent the convincing false pass

Never apply a plan that wasn't evaluated. Pass the same saved binary plan from evaluation to apply, and bind its approval to the commit and deployment context.

If your workflow replans after merge, evaluate that new plan before applying it. A successful pull request check doesn't authorize a different deployment plan.

Another failure is subtler: the policy job reads a valid artifact from the wrong workspace. Include the root module and workspace in artifact names, verify metadata on download, and reject mismatches before evaluation.

Keep advisory rules in a separate non-blocking job so experimental findings don't hold up releases. A healthy run has green policy tests, an identified plan, a completed evaluation, a useful comment, and an open merge gate only when mandatory decisions permit it.

Rolling Out Enforcement in Three Modes

Introducing policy late creates a migration problem as well as a security problem. In a 2026 empirical study of policy-as-code adoption, researchers examined 10,560 files across 499 open-source repositories and found that only 28% introduced policy during the first 20% of development, with policies arriving after a median of 43.4% of the development lifecycle.

That evidence describes open-source adoption timing, not regulated-enterprise behavior. The practical implication is still useful: start evaluating controls early, before making every new rule a release blocker requires an infrastructure cleanup project.

Enforcement modes and when to use each

ModeBehaviorOverridePromote whenExample controls
AdvisoryReports failures, never blocksNot neededViolation volume is measured and understoodTag coverage, naming conventions
Soft-mandatoryBlocks unless an authorized override existsNamed owner with logged, time-bound exceptionRemediation owners and exception paths are definedNon-production region drift, missing tags on shared resources
Hard-mandatoryStops the run until the violation is fixedNo overrideRule has proven high confidence in soft modeProhibited regions, public exposure, missing encryption

Measure before blocking

Advisory mode is an evaluation period, not a permanent parking lot. Assign someone to classify findings as genuine violations, policy bugs, unsupported resource models, or accepted design exceptions.

Existing infrastructure may produce findings when the plan includes unchanged resources or when a rule evaluates the complete proposed state. Decide whether each control governs newly introduced risk, any touched resource, or the entire planned estate. Otherwise, an unrelated change can become responsible for an old violation.

Agree on a cleanup window with resource owners before enabling blocking. Keep that migration agreement distinct from permission to introduce new violations.

Make promotion an operational decision

Soft-mandatory enforcement only works when an authorized person can make an attributable risk decision. A developer adding an ignore flag to the same pull request isn't an approval process.

Hard-mandatory enforcement should mean no run-level override. If a legitimate deployment cannot satisfy the control, change the governed policy or design through review rather than bypassing the job.

Apply the same discipline to CI credentials: a trustworthy policy result is little comfort if an exposed automation secret permits direct deployment. For the credential-handling side, API key safety advice from Mailbeam provides a complementary resource.

Promote a control only after its violation volume stays acceptably low over an agreed observation period, its false positives are resolved, and owners accept the remediation and exception paths. Don't promote it merely because the rollout calendar says it's time.

Governing Exceptions and Policy Drift

Unmanaged exceptions become the policy people follow. A repository can contain strict-looking rules while its override list authorizes the infrastructure those rules were supposed to prevent.

Practitioner analysis of OPA and Sentinel policy testing identifies interdependent-rule complexity and exemption growth as operational limitations. Treat the rule catalog and exception register as governed artifacts, not incidental configuration.

A diagram illustrating the Terraform policy lifecycle with development, testing, review, and release stages shown clearly.

Give every control an accountable owner

Maintain a rule record alongside its implementation:

  • Owner and rationale: Name the team responsible and explain the risk the control addresses.
  • Affected assets and severity: Define resource scope and the consequence of failure.
  • Test fixtures: Link the evidence that proves intended decisions.
  • Escalation path: Identify who resolves disputed findings and conflicting requirements.
  • Expiry or review deadline: Require an explicit decision to retain, revise, or retire the control.

Exception record fields

FieldPurpose
Linked design decisionTies the exception to the approved design it deviates from
Compensating controlNames the control that reduces risk while the exception lasts
ApproverNamed owner who accepted the risk
Review dateDate the exception is re-examined
Expiry dateHard end date after which the exception lapses

Scope an exception to the control and affected assets. Avoid broad team-level exemptions that also apply to future resources.

Resolve conflicts instead of accumulating bypasses

Say a general network rule prohibits public ingress, but an approved edge-service design requires a public listener. Define the narrowly scoped precedence relationship and test the combined rules as a fixture. Don't leave developers to discover which policy wins through failed releases.

Repeated renewals should trigger reassessment. I would treat recurring renewal of the same exception as a reason to review whether the rule is too broad, the compensating control should become standard, or remediation has no accountable owner.

Review the catalog quarterly, sorting by violation count, exception count, and exception age. Investigate rules that produce constant review outcomes because their inputs can't be established during planning; move the unverifiable portion to an owned detective check rather than repeatedly approving uncertainty.

An exception without an expiry date is a policy change made quietly.

Decide Which Controls to Block First

Agent-generated Terraform needs security review even when it parses cleanly. An IEEE Software article examining generated infrastructure code reports research in which 91% of LLM-generated Terraform files contained at least one misconfiguration and 68% contained a high- or critical-severity issue.

Those benchmark results aren't a prediction about every coding agent or repository. They do establish why syntactic success shouldn't substitute for a security decision.

Require provenance and human ownership for agent-produced changes. Label the pull request, identify the responsible engineer, and route the rendered plan through the same gate as human-authored infrastructure.

Start with high-impact, provable controls

Rank candidate controls by potential blast radius and the reliability of their plan evidence. I would begin with public exposure, prohibited regions, and missing approved encryption, provided the policy can correctly model the relevant provider resources.

For AWS environments, use an AWS cloud security baseline to connect those checks to the assets and access paths you're protecting. Keep less mature controls advisory until their findings are understood.

Before enabling hard blocking, verify the complete workflow:

  • Violating plan: The pipeline fails for the intended reason.
  • Compliant plan: The same control permits an acceptable change.
  • Developer feedback: The comment identifies the affected resource and fix.
  • Merge protection: The required status check prevents an unsafe merge.
  • Exception handling: Soft-mandatory exceptions expire correctly, while hard-mandatory controls cannot be overridden.

At DevArmor, we connect security standards to real threat models and approved design context, so a blocked change can be explained in terms of the decision it violates. We analyze specs and tickets to generate explainable security feedback and policy checks, then push design controls and guardrails to downstream tools.

This week, write the initial hard-block candidates and their fixtures. Promote them only after the tests, plan evidence, and ownership model justify blocking.


DevArmor enforces Policy-as-Code on every pull request, with the option to block unsafe merges and maintain traceable review outcomes. Visit DevArmor to connect your Terraform guardrails to living threat models, approved design decisions, and security feedback developers can act on.

Table of Contents

Subscribe