Topic guide

Infrastructure as code and policy as code

Infrastructure as code declares the networks, servers and permissions you want in versioned files, and a tool works out how to get there. Policy as code checks every proposed change against your rules first. This guide follows one change from code to drift.

main.tfTerraform

resource "aws_security_group" "bastion" {  name   = "bastion"  vpc_id = var.vpc_id   ingress {    from_port   = 22    to_port     = 22    protocol    = "tcp"    cidr_blocks = ["0.0.0.0/0"]  }}

The JSON plan is the policy's input

policy/network.regoOPA Rego

package terraform.network deny contains msg if {  some rc in input.resource_changes  rc.type == "aws_security_group"  some rule in rc.change.after.ingress  rule.from_port <= 22  rule.to_port >= 22  "0.0.0.0/0" in rule.cidr_blocks  msg := sprintf("%s: SSH open to all",    [rc.address])}

Policy check failed: plan not appliedaws_security_group.bastion: SSH open to all

Illustration: a Terraform resource and the OPA rule that blocks it.

How it works

How does infrastructure as code work?

HashiCorp describes the core Terraform workflow as write, plan and apply. Production teams add three stages around it: a policy check, a human review and a scheduled drift check. Each stage leaves something you can inspect.

  1. Write

    *.tf
    # on a branch

    Declare the end state: resources, settings and connections. Nothing changes yet.

  2. Plan

    terraform plan
    -out=tfplan

    Terraform reads what exists, compares it with the code and proposes changes.

  3. Policy check

    Gate

    terraform show
    -json tfplan

    Rules read the JSON plan, with planned values and actions, and fail violations.

  4. Review

    Gate

    # pull request
    plan + policy

    A person reviews the plan, not just the diff, starting with deletes.

  5. Apply

    terraform apply
    tfplan

    The reviewed plan runs as saved. Terraform treats the plan file as approval.

  6. Detect drift

    terraform plan
    -refresh-only

    A scheduled plan reports what changed outside Terraform.

Drift found: the fix starts again at 01, in code.

Illustration: six stages of an infrastructure change, with two gates.

Declarative state

Why does Terraform need a state file?

Terraform configuration is declarative: it describes the end state, not the steps. To plan, Terraform must know what it already built and which real object belongs to each resource. That record is the state, and HashiCorp's documentation gives it four jobs.

Mapping
Links each resource in the code to a real object, such as an instance ID.
Metadata
Keeps dependencies, so removed resources are deleted in the right order.
Performance
Caches attribute values, so large estates aren't queried in full every run.
Syncing
With remote state and locking, a team works from one current copy.

Codemain.tf

aws_security_group.bastion
cidr_blocks = ["0.0.0.0/0"]

What you declared

Stateterraform.tfstate

aws_security_group.bastion
id = "sg-0a1b2c3d"

What Terraform built, by address and ID

Real infrastructureprovider API

sg-0a1b2c3d
ingress tcp/22 from 0.0.0.0/0

What actually runs

Illustration: state links each resource to one real object.

Treat state as a secret

State is stored in plain text, secrets included, and sensitive only hides values in output. Restrict and encrypt the backend, or use OpenTofu's built-in state encryption.

Lock it

Locking is automatic on operations that write state, but not every backend supports it. Use one that does, and apply only from the pipeline.

Split it

One state for everything means every plan reads everything, and every mistake can reach it. Split by owner and rate of change: network, data, applications.

The pipeline that applies all this holds strong credentials too; see Secrets Management in 2026: Sprawl, Non-Human Identities, and the Vault vs Workload Identity Decision.

Policy as code

What is policy as code, and where does it run?

Policy as code turns rules like “no SSH from the internet” into code that an engine evaluates on every change. Open Policy Agent (OPA) is an open-source, general-purpose engine and a graduated CNCF project. Its Rego policies can check what Terraform is about to change before it changes it, and HCP Terraform checks each run's plan against Sentinel, OPA or beta HCL policies.

The same rule can run at three points:

Where it runsWhat it readsWhat it catchesWhat it misses
Before commitEditor or pre-commit hook, such as Conftest on .tf files The source Mistakes visible in code, at the cheapest moment Values that exist only at plan time. It runs on a laptop: advice, not control.
On the plan, in CIA required check between plan and apply The JSON plan: planned values and actions What will really change, deletes included Values known only after apply, a limit OPA's docs note. Changes that skip the pipeline.
At admissionCloud or cluster API: Azure Policy's deny effect, OPA Gatekeeper The create or update request Changes from any path, the console included Little, but feedback arrives late, during apply.

Tools at each point

  • Before commit Conftest runs Rego policies against your files; Checkov and Trivy, which now includes tfsec, scan for known misconfigurations with built-in rules.
  • On the plan, in CI OPA or Conftest on the JSON plan; HCP Terraform runs Sentinel or OPA policies on every run.
  • At admission Kyverno, with policies written in YAML, or OPA Gatekeeper in Kubernetes; Azure Policy in Azure; service control policies in AWS Organizations, which cap what accounts may do.

CI step: policy checkShell

terraform plan -out=tfplanterraform show -json tfplan > tfplan.jsonopa exec --fail-non-empty \  --decision terraform/network/deny \  --bundle policy/ tfplan.json
Illustration: the policy check as a CI step.

With --fail-non-empty, the step fails on any denial. Make it a required check: the plan has the fullest picture. Save admission rules for what must hold on every path.

Drift

What causes configuration drift, and how do you prevent it?

Drift is the gap between state and real infrastructure. In HashiCorp's drift tutorial, manual changes leave the state “out of sync”. It usually starts with one of these:

  • A console fix during an incident, never written back to code.
  • A setting another system owns, like an autoscaler or a tagging agent.
  • Two configurations or teams managing one object.

To find it, schedule terraform plan -refresh-only: it reports outside changes and proposes no infrastructure changes. A normal plan with -detailed-exitcode returns exit code 2 on any difference, which is easy to alert on. HCP Terraform's health assessments do this for you.

Prevention means the pipeline is the only normal path to production: no standing console write access, logged break-glass access, and admission rules for what must never change. GitOps goes further, with agents that continuously reconcile. See GitOps in 2026: Reconciliation, Drift, and the Argo CD vs Flux Decision.

Where code and reality disagree, ask:

  1. A mistake, or an unapproved fix?

    Revert A normal plan and apply restores the declared values.

    terraform apply

  2. A fix worth keeping?

    Codify Change the code to match. A refresh-only apply updates state, not infrastructure.

    terraform apply -refresh-only

  3. Owned by another system?

    Hand over ignore_changes leaves that attribute to it. Each is a blind spot.

    ignore_changes = [tags]

  4. Unknown to any code?

    Import An import block adopts it, and the plan can draft its configuration.

    terraform plan
    -generate-config-out=gen.tf

Illustration: a decision guide for each drifted resource.

Testing

How do you test infrastructure as code?

In layers, from checks that take seconds and need no credentials to tests that build real resources. Run the cheap ones on every commit.

  1. Format and validate

    Fmt checks style. Validate checks syntax, names and types, and never calls provider APIs or remote state.

    terraform fmt -checkterraform validate

    Seconds, no credentials

  2. Policy unit tests

    OPA runs every rule named test_, so each policy meets passing and failing input.

    opa test policy/

    Seconds

  3. Plan-mode module tests

    terraform test with mock providers checks module logic without creating anything or needing credentials.

    command = plan

    Seconds to minutes

  4. Apply-mode tests

    The default mode builds short-lived resources, checks assertions, then destroys them. tofu test works the same way.

    command = apply

    Minutes, sandbox account

  5. Checks in production

    Check blocks warn without blocking, and HCP Terraform's continuous validation re-runs them.

    check "api_health" {}

    On a schedule

Illustration: five test layers, cheapest first. Bars show relative cost per run.

Module strategy

How should you structure Terraform modules?

A module is a collection of resources that Terraform manages together. You run plan in the root module, which calls child modules. Four rules cover most of the strategy.

  1. Name a concept, not a resource

    HashiCorp advises against thin wrappers around one resource type. If the module's name is the resource's name, use the resource.

  2. Keep the tree flat

    HashiCorp strongly recommends one level of child modules, with dependencies passed in.

  3. Pin every shared module

    A Git source without a ref uses the default branch. Give registry modules a version constraint.

  4. Vary inputs, not code

    Then staging runs what production will run, and promotion is a one-line version change.

envs/staging/main.tf

module "network" {  source  = "acme/network/aws"  version = "3.2.0"   environment  = "staging"  cidr_block   = "10.20.0.0/16"  nat_gateways = 1}

envs/production/main.tf

module "network" {  source  = "acme/network/aws"  version = "3.2.0"   environment  = "production"  cidr_block   = "10.30.0.0/16"  nat_gateways = 3}
Illustration: same module and version; only the highlighted inputs differ.

In a real engagement

At Nike, bot provisioning went from 45 minutes of hands-on work to a self-service flow of about 3 minutes, and environment changes went the same way. The stack was Jenkins with Python, Groovy, Ansible and Bash, but the lesson carries over: one definition, inputs per environment.

Read the Nike case
“Previously, moving CI workflows between Dev, Staging, and Prod required manual, uncommitted code changes. Mateusz implemented a solution that reduced this to a single line of code, streamlining the process and enabling faster iteration for both developers and our team.”
Jon V., Mobile Release Engineer Lead, Nike

Shared modules are where a platform team sets defaults once; see Platform Engineering vs DevOps: What an Internal Developer Platform Actually Buys You.

Pitfalls

What are the most common infrastructure as code mistakes?

Most show up first as a strange plan.

SymptomUsual causeFix
A rename makes the plan replace a database. A new address reads as destroy, then create. A moved block per rename, and prevent_destroy on data stores.
Secrets turn up in state. State is plain text, and sensitive only masks output. Encrypt and restrict the backend. Use ephemeral values and write-only arguments where available.
Every plan shows changes nobody made. Another system owns the attribute, or fixes happen in the console. ignore_changes for settings owned elsewhere. Codify or revert the rest.
One module update breaks several teams. Shared modules used without a pinned version. Pin versions, keep a changelog, and test before tagging.
A policy passed, yet the resource is wrong. The value was unknown until apply. Check it with a postcondition, or at admission.

Self-check

Where does your team stand?

Count how many are true today.

  1. State lives in a remote backend with locking, encryption and access control.
  2. Every change goes through a pull request, and the pipeline applies the reviewed plan.
  3. Policies run on the plan as a required check, with tests of their own.
  4. A drift check runs on a schedule, and someone owns its alerts.
  5. Nobody has standing write access to production outside break-glass.
  6. Shared modules are pinned and tested before each release.
  7. The hand-made resources that matter have been imported.

Where to start

Fewer than four? Begin with the first two. Policy needs a reviewed plan to read, and drift detection needs a state you trust.

FAQ

Questions engineers ask

Terraform or OpenTofu?

OpenTofu is a fork of Terraform, created after HashiCorp moved its products to the Business Source License in August 2023, and given to the Linux Foundation. Both share the write, plan and apply workflow, and OpenTofu uses Terraform's providers through its own registry. Infrastructure as Code in 2026: Drift, Policy, and the Terraform vs OpenTofu Decision compares them.

OPA or Sentinel?

Sentinel is HashiCorp's policy-as-code framework and integrates with HashiCorp products such as Terraform and Vault. OPA is general-purpose, so one language can cover Terraform plans, Kubernetes admission and more. HCP Terraform runs either. Rules that reach beyond Terraform favor one engine everywhere.

How does this relate to GitOps and CI/CD?

CI/CD runs the workflow above; see CI/CD automation. GitOps adds agents that pull the desired state and continuously reconcile it; see GitOps. For the platforms underneath, see cloud infrastructure.

Free Release Check

See where your releases still wait on people

The Release Check asks 11 questions about your last release and shows what it costs a year, with three fixes. No call needed.