# Infrastructure as Code in 2026: Terraform vs OpenTofu vs Pulumi

> Terraform vs OpenTofu vs Pulumi in 2026: state, modules, drift, plan/apply pipelines, policy, testing, migration, Infracost, and a full AWS ECS example.

Source: https://www.derar.dev/blog/terraform-vs-opentofu-infrastructure-as-code-guide-2026 · Published 2026-11-11 · Updated 2026-11-14 · By Derar Sattouf

Infrastructure as Code (IaC) is the practice that turns cloud consoles into reviewable, repeatable, versioned text. Done well, it gives you the same pull request workflow for a VPC that you have for an application: a diff, a review, an automated check, and a history. Done badly, it gives you a second, more dangerous console: one where a single `apply` can delete a production database and where the state file is a plaintext secret store with no owner.

Since 2023 a licensing change has complicated the picture. HashiCorp moved Terraform from the Mozilla Public License to the Business Source License, the community forked it as OpenTofu under the Linux Foundation, and the two projects have been diverging ever since. Meanwhile Pulumi and the cloud vendors' own tools offer different trade-offs. Choosing a tool is one decision. Operating IaC safely is the bigger one, and it looks the same whichever tool you pick.

Terraform and OpenTofu are still largely compatible for the HCL most teams write, but they have diverged. Choose OpenTofu if you want an open-source (MPL 2.0), foundation-governed tool and features such as built-in state encryption. Choose Terraform if you want HashiCorp/IBM's commercial platform (HCP Terraform) and its newest provider and ecosystem integrations. Both are valid; avoid mixing them in one state without a plan. Pulumi (and CDK-style tools) trade a DSL for real programming languages: pick them when your team prefers TypeScript, Python, or Go with real tests and loops, and pick HCL when you value a constrained declarative language that anyone can review.

Remote state with locking is non-negotiable for teams. On AWS use S3 with native lockfile support or DynamoDB locking, and verify the backend options for your version. Encrypt state, restrict access like production credentials, and never put it in git. Prefer directories (or separate root modules) per environment over workspaces for anything with a different blast radius, different accounts, or different approval rules, and use small, composable state files. Version your modules, pin providers with a lockfile, and treat module interfaces as APIs.

Plan on pull request and apply from the main branch, with a saved plan file, human approval for production, OIDC credentials instead of access keys, and locking so applies are serialized. Add policy as code (OPA/Conftest, Checkov, Trivy, Sentinel on HCP Terraform), tests (`terraform test` or `tofu test`, Terratest for integration), cost estimation (Infracost), and scheduled drift detection. And know the footguns: `prevent_destroy` and deletion protection, `count` versus `for_each` index shifts, sensitive values in state, `-target`, forced replacement, and unreviewed `apply -auto-approve`.

Version facts below are as of late 2026 and change quickly. The parts most likely to age first are S3 locking, state encryption syntax, and the OpenTofu and Terraform release lines. Anything marked "verify" should be confirmed against the official release notes before you act on it.

## Licensing, governance, and what happened

### Timeline in brief

| Date | Event |
| --- | --- |
| Aug 2023 | HashiCorp relicenses its products, including Terraform, from MPL 2.0 to the Business Source License (BSL 1.1) |
| Sept 2023 | The community fork (initially OpenTF) is announced and joins the Linux Foundation as OpenTofu |
| Jan 2024 | OpenTofu 1.6, the first stable release, as a drop-in replacement for Terraform 1.5.x |
| Apr 2024 | OpenTofu 1.7 adds client-side state encryption and other features Terraform lacks |
| 2024 | IBM announces its intent to acquire HashiCorp; the acquisition closes in early 2025 |
| 2025 | OpenTofu moves under the CNCF as a sandbox project (verify the current status) |
| Late 2025 | OpenTofu 1.11 adds ephemeral resources and write-only attributes plus the `enabled` meta-argument; Terraform 1.14 adds list resources, `terraform query`, and actions |
| 2026 | Both projects continue separate release lines; verify the latest versions below |

### What BSL means in practice

The BSL permits using, modifying, and redistributing the source, with a restriction: you cannot use the software in a way that competes with HashiCorp's commercial offerings. For the overwhelming majority of companies, which use Terraform to manage their own infrastructure, the license does not restrict day-to-day use. It matters most for:

- **Vendors** building products that embed or wrap Terraform (CI/CD platforms, internal developer portals that resell the capability, managed IaC services).
- **Organizations with open-source-only policies**, where BSL-licensed tools require legal review.
- **Distribution packagers**, where BSL software cannot be shipped in some Linux distributions.
- **Long-term risk assessment**: governance by a single vendor means licensing and roadmap are that vendor's decision. HashiCorp's BSL grants convert to an open-source license after a change date, but that is a long horizon.

OpenTofu is licensed under MPL 2.0 and governed by a technical steering committee under a foundation, with contributions from multiple companies. That is the principal non-technical argument for it.

Read the actual license text and the vendor's FAQ with your counsel if you are a vendor. This article is not legal advice.

### Current versions (verify)

Trackers in late 2026 show roughly this state:

| Tool | Recent versions reported | Notes |
| --- | --- | --- |
| Terraform | 1.14 line (released Nov 2025, 1.14.9 in April 2026); 1.15 and 1.16 releases appear in package trackers through Sept 2026 | HashiCorp supports GA releases for a limited window and expects users to stay within a couple of minor versions of the latest; verify on releases.hashicorp.com |
| OpenTofu | 1.11 (Dec 2025); 1.12 (2026, patch releases through 1.12.x); a 1.13 release reported for late Sept 2026 | Verify on the OpenTofu GitHub releases page; secondary sources disagreed on the newest version |

Do not copy version constraints from this article. Run `terraform version` or `tofu version`, read the release notes for every minor version between your current and target, and test upgrades in a non-production workspace first.

## Terraform vs OpenTofu vs Pulumi

### Feature comparison

| Area | Terraform (HashiCorp/IBM) | OpenTofu | Pulumi |
| --- | --- | --- | --- |
| License | BSL 1.1 | MPL 2.0 | Apache 2.0 (CLI and SDK); commercial Pulumi Cloud service |
| Governance | HashiCorp, part of IBM | Linux Foundation / CNCF, steering committee | Pulumi Corporation, open-source core |
| Language | HCL | HCL (Terraform-compatible, with extensions) | TypeScript, Python, Go, C#, Java, YAML |
| Providers | Terraform providers (registry.terraform.io) | Same provider protocol; OpenTofu registry mirrors most providers | Native providers plus a bridge to Terraform providers |
| State | Local, remote backends, HCP Terraform | Same backends; client-side state encryption built in | Pulumi Cloud, or self-managed backends (S3, GCS, Azure Blob, local) |
| State encryption | Rely on backend encryption (server side) | Built-in client-side encryption with AES-GCM and KMS key providers | Encrypted secrets in state with a configurable secrets provider |
| Ephemeral values and write-only attributes | Ephemeral resources (1.10) and write-only attributes (1.11) | Ephemeral resources and write-only attributes (1.11) | Secrets are encrypted in state; ephemeral concepts differ |
| Conditional resources | `count = var.enabled ? 1 : 0` | Same, plus the `enabled` meta-argument (1.11, verify) | Ordinary language conditionals |
| Testing | `terraform test` (native), Terratest | `tofu test` (native), Terratest | Unit tests with language test frameworks plus mocks; integration tests |
| Policy | Sentinel (HCP Terraform), OPA | OPA, Checkov, and others | CrossGuard policy as code |
| Commercial platform | HCP Terraform and Terraform Enterprise | Third parties: Spacelift, env0, Scalr, Terrateam, Atlantis and others | Pulumi Cloud |
| Import | `import` blocks, config generation | `import` blocks | `pulumi import`, convert tools |
| Converting from Terraform | n/a | Drop-in for most 1.5.x-compatible configurations | `pulumi convert --from terraform` assists |

### Choosing: a decision table

| If this describes you | Prefer |
| --- | --- |
| Open-source licensing is a requirement; or you are a vendor embedding IaC | OpenTofu |
| You already use HCP Terraform and value its workflows, run tasks, and private registry | Terraform |
| You want client-side state encryption without extra tooling | OpenTofu |
| You need a specific newest Terraform-only feature (for example a particular HCP-integrated capability) | Terraform |
| Your team wants real programming constructs, strong testing, and shared code with applications | Pulumi |
| You want a constrained language that non-developers (platform, security, ops) can review | HCL (Terraform or OpenTofu) |
| You are all-in on one cloud and its native tooling | CloudFormation/CDK, Bicep, Deployment Manager alternatives; consider the cost of lock-in |
| You operate in Kubernetes and want infrastructure as resources | Crossplane or cloud controllers, often alongside Terraform/OpenTofu for the base layer |
| You are a small team with a few resources | Whichever your team knows; the migration cost later is lower than a bad start |

### CDK-style tools

AWS CDK synthesizes CloudFormation from TypeScript, Python, Java, C#, and Go, giving you programming-language ergonomics on AWS only. CDK for Terraform (CDKTF) offered the same idea for Terraform providers; HashiCorp has announced its deprecation (verify the current status before adopting it for new work). Pulumi remains the multi-cloud, general-language option. If you want programming-language IaC and multi-cloud, evaluate Pulumi; if you are AWS only, evaluate CDK against Terraform honestly, including how each handles rollbacks and drift.

### Mixed fleets

Many organizations end up using more than one tool: Terraform or OpenTofu for foundations, a Kubernetes-native tool for application platform resources, CloudFormation for vendor-supplied stacks. That is acceptable provided each resource has exactly one owner. Two tools managing the same resource is how drift wars start.

## Project structure

### Principles

1. **One state file per blast radius.** A single state for an entire company means every change risks everything and every plan takes forever. Split by environment, by region or account, and by lifecycle (network, data, application).
2. **Separate slow-changing from fast-changing.** VPCs and IAM change rarely and are high impact; application stacks change daily.
3. **Reusable modules, thin root modules.** Root modules wire modules together with environment-specific values; logic lives in modules.
4. **Everything in version control, nothing sensitive in version control.**

### A layout that scales

```text
infrastructure/
├── modules/                      # reusable, versioned building blocks
│   ├── vpc/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   ├── outputs.tf
│   │   ├── versions.tf
│   │   └── tests/vpc.tftest.hcl
│   ├── ecs-service/
│   └── rds-postgres/
├── live/                         # root modules: one directory = one state
│   ├── dev/
│   │   ├── network/
│   │   │   ├── main.tf
│   │   │   ├── backend.tf
│   │   │   ├── terraform.tfvars
│   │   │   └── .terraform.lock.hcl
│   │   └── app-api/
│   ├── staging/
│   │   ├── network/
│   │   └── app-api/
│   └── prod/
│       ├── network/
│       ├── data/
│       └── app-api/
├── policy/                       # OPA / Conftest rules
├── .github/workflows/
│   ├── plan.yml
│   └── apply.yml
└── README.md
```

Within a root module, a conventional file layout helps reviewers: `main.tf` (resources and module calls), `variables.tf`, `outputs.tf`, `versions.tf` (required versions and providers), `backend.tf` (state configuration), `locals.tf`, and `data.tf` when large.

### Wiring root modules together

Root modules can read each other's outputs through the `terraform_remote_state` data source, but this couples them to each other's state layout and requires read access to the whole state, which may contain secrets. Alternatives that keep coupling looser:

- **Data sources** that look up resources by tag or name (for example `data "aws_vpc"` with a filter).
- **A parameter store** (SSM Parameter Store, Secrets Manager, Consul) where producer stacks publish values.
- **Orchestration tools** such as Terragrunt, which add dependency blocks and DRY configuration, if you accept the extra tool.

Whatever you choose, keep the dependency direction one way: network, then data, then application.

### Workspaces versus directories

Terraform and OpenTofu **workspaces** let one configuration keep multiple state files under one backend, selected by `terraform.workspace`. They are tempting for dev, staging, and prod. In practice:

| Aspect | Workspaces | Directories (separate root modules) |
| --- | --- | --- |
| Code duplication | None | Some, mitigated by modules |
| Different backends or accounts per environment | Awkward; same backend config for all | Natural; each root has its own backend and provider config |
| Different approval rules, permissions | Hard; one pipeline path | Easy; per-directory pipeline rules and IAM roles |
| Divergence between environments | Hidden behind conditionals on the workspace name | Explicit and visible in code review |
| Risk of applying to the wrong environment | High (the current workspace is invisible state) | Lower (the working directory is explicit) |
| Good for | Ephemeral copies of the same stack (per-PR preview environments, feature branches) | Long-lived environments such as dev, staging, and production |

Recommendation: directories (or an equivalent such as Terragrunt stacks) for environments, workspaces only for short-lived clones of identical stacks.

## Remote state and locking

### What state is and why it needs care

State maps your configuration to real resources (IDs, attributes) and holds metadata used to compute plans. It also often contains sensitive attributes in plaintext (database passwords, private keys, generated tokens). Treat it as a secret and as a production database: encrypted, access-controlled, backed up, versioned.

### AWS S3 backend

```hcl
# backend.tf
terraform {
  backend "s3" {
    bucket         = "acme-tfstate-prod-eu-west-1"
    key            = "prod/network/terraform.tfstate"
    region         = "eu-west-1"
    encrypt        = true
    kms_key_id     = "alias/tfstate"
    use_lockfile   = true        # S3-native locking (verify availability for your version)
    # dynamodb_table = "acme-tfstate-locks"   # legacy locking; being phased out in favour of use_lockfile
  }
}
```

S3 native state locking through a `.tflock` object (`use_lockfile`) was introduced in recent Terraform and OpenTofu releases and removes the DynamoDB table requirement; the DynamoDB option is documented as deprecated in current releases. Verify the exact version in which your tool supports it, and keep your S3 bucket configured with versioning and conditional writes support as the docs require.

Create the state bucket carefully (this is a bootstrap problem; many teams create it once by hand or with a small separate configuration that uses local state):

```hcl
resource "aws_s3_bucket" "tfstate" {
  bucket = "acme-tfstate-prod-eu-west-1"
}

resource "aws_s3_bucket_versioning" "tfstate" {
  bucket = aws_s3_bucket.tfstate.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "tfstate" {
  bucket = aws_s3_bucket.tfstate.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm     = "aws:kms"
      kms_master_key_id = "alias/tfstate"
    }
  }
}

resource "aws_s3_bucket_public_access_block" "tfstate" {
  bucket                  = aws_s3_bucket.tfstate.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}
```

### Backend options

| Backend | Locking | Notes |
| --- | --- | --- |
| S3 (AWS) | Native lockfile or DynamoDB | Most common on AWS; enable versioning and KMS |
| GCS (Google Cloud) | Native | Object versioning and CMEK |
| Azure Blob Storage | Native lease-based | Use private endpoints and managed identity |
| HCP Terraform / Terraform Enterprise | Built in | State, runs, RBAC, policy in one product |
| Third-party platforms (Spacelift, env0, Scalr, and others) | Built in | Manage state and runs; verify backend compatibility |
| PostgreSQL, Consul, HTTP (GitLab-managed state) | Varies | GitLab offers Terraform/OpenTofu state storage per project |
| Local | File lock only | Only for experiments; never for teams |

### Rules for state

1. **Locking on, always.** Concurrent applies corrupt state. A lock held after a crashed job is released with `terraform force-unlock LOCK_ID` after confirming nothing is running.
2. **Least privilege.** Read access to state is read access to its secrets. Give CI a role for the specific state keys it needs; give humans read-only access through a role that requires MFA.
3. **Versioning and backups.** Enable bucket versioning; practice restoring a previous state version.
4. **Never edit state by hand.** Use `terraform state mv`, `rm`, and `import` (or `moved` and `import` blocks), reviewed and run deliberately.
5. **One writer.** Only the pipeline applies production. Humans plan; the pipeline applies.
6. **Encrypt.** Server-side (KMS) at minimum; with OpenTofu consider client-side encryption (see the state encryption section).
7. **Keep state small.** Split large states; a 10,000-resource state makes plans slow and risky.

## Modules and versioning

### What makes a good module

A module is a function from variables to resources and outputs. Design it like an API:

- A **narrow purpose** (a VPC, an ECS service, a Postgres instance) with **opinionated defaults** (encryption on, deletion protection on for stateful resources) and **escape hatches** only where needed.
- **Typed, validated variables** with descriptions.
- **Few, meaningful outputs**, not everything.
- **No provider configuration inside modules** (accept providers from the caller), except in rare aliased cases.
- **Documentation and examples**, including a tested `examples/` directory.

```hcl
# modules/ecs-service/variables.tf
variable "name" {
  type        = string
  description = "Service name, used for tags and resource names."

  validation {
    condition     = can(regex("^[a-z][a-z0-9-]{2,30}$", var.name))
    error_message = "name must be 3-31 characters, lowercase letters, digits and hyphens."
  }
}

variable "cpu" {
  type        = number
  default     = 256
  description = "Fargate task CPU units."

  validation {
    condition     = contains([256, 512, 1024, 2048, 4096], var.cpu)
    error_message = "cpu must be a valid Fargate size."
  }
}

variable "environment" {
  type        = map(string)
  default     = {}
  description = "Plain environment variables. Do not put secrets here; use secret_arns."
}

variable "secret_arns" {
  type        = map(string)
  default     = {}
  description = "Map of env var name to Secrets Manager or SSM ARN, injected by ECS at runtime."
}
```

### Module sources and versioning

```hcl
# From the public registry, pinned with a version constraint
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"            # verify the current major version before pinning
  # ...
}

# From a private git repository, pinned to an immutable tag
module "ecs_service" {
  source = "git::https://github.com/acme/terraform-modules.git//ecs-service?ref=v2.3.1"
  # ...
}
```

Rules:

1. **Pin versions.** An unpinned module changes under you on the next `init -upgrade`. Pin to exact versions or tight ranges (`~>`).
2. **Semantic versioning** for your own modules: breaking changes to variables, outputs, or resource addresses bump the major version.
3. **Resource address changes are breaking changes.** Renaming a resource inside a module causes destroy and create unless you add a `moved` block.
4. **Publish releases from a tag** with a changelog; consumers upgrade deliberately via Dependabot or Renovate pull requests that show the plan.
5. **Avoid mega-modules** that wrap an entire cloud. Prefer composition: small modules plus a root module that connects them.
6. **Be careful with community modules.** They are convenient and often excellent, but they are third-party code that creates IAM roles in your account. Read the code, pin versions, and consider vendoring critical ones.

### `moved` blocks for refactoring

```hcl
# Rename a resource without destroying it
moved {
  from = aws_s3_bucket.logs
  to   = aws_s3_bucket.access_logs
}

# Move a resource into a module
moved {
  from = aws_ecs_cluster.main
  to   = module.cluster.aws_ecs_cluster.this
}
```

`moved` blocks are declarative, reviewable refactors that show up in the plan as moves instead of destroy and create. Keep them in the code until all environments have applied them.

### Provider versions and the lock file

```hcl
# versions.tf
terraform {
  required_version = ">= 1.9.0, < 2.0.0"    # adjust to the versions you have actually tested

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"                     # verify the current major version of the provider
    }
  }
}
```

Commit `.terraform.lock.hcl`. It records provider versions and checksums so that every machine and CI run uses the same provider builds. Generate hashes for the platforms you use (`terraform providers lock -platform=linux_amd64 -platform=darwin_arm64`). Update providers deliberately with `init -upgrade` in a pull request.

## Secrets in state and in code

### The problem

If a resource has an attribute such as a database password, the value is stored in state in plaintext, even if marked `sensitive` (which only hides it from CLI output). Anyone with state read access can read it. Generated secrets (`random_password`, `tls_private_key`) are stored in state too.

### Options, in order of preference

| Technique | How it helps | Caveat |
| --- | --- | --- |
| Do not manage the secret in IaC | Let the service generate it (RDS managed master password in Secrets Manager, for example) and reference the ARN | Best option when the platform supports it |
| Ephemeral resources and write-only attributes | The value is never written to plan or state (Terraform 1.10 and 1.11 and later; OpenTofu 1.11 and later) | Requires provider support for write-only attributes; verify per resource |
| Reference secrets by ARN or path | Pass ARNs to workloads that fetch the secret at runtime | Still need to create the secret value somewhere |
| Client-side state encryption (OpenTofu) | State and plan files encrypted before they reach the backend | Key management becomes critical; verify supported key providers |
| Restrict and encrypt the state backend | Server-side KMS plus tight IAM | Does not hide secrets from authorized readers |
| SOPS or Vault for variable files | Keep secret inputs encrypted in git or fetched at run time | Value still flows into state if used in a non-ephemeral attribute |

### Example: managed database password without a secret in state

```hcl
resource "aws_db_instance" "main" {
  identifier                  = "acme-prod"
  engine                      = "postgres"
  instance_class              = "db.t4g.medium"
  allocated_storage           = 50
  username                    = "app_admin"
  manage_master_user_password = true            # RDS generates and rotates in Secrets Manager
  storage_encrypted           = true
  deletion_protection         = true
  skip_final_snapshot         = false
  final_snapshot_identifier   = "acme-prod-final"
  backup_retention_period     = 14
}

output "db_secret_arn" {
  value = aws_db_instance.main.master_user_secret[0].secret_arn
}
```

The application receives the secret ARN and reads the value at runtime. The password never appears in your configuration, and by design is not in state in a form you manage.

### General rules

1. **Never commit `.tfvars` with secrets** and never commit state. Use `.gitignore` for `*.tfstate*`, `.terraform/`, and secret var files.
2. **Mark outputs and variables `sensitive = true`** to avoid logging them, while remembering that it does not remove them from state.
3. **Scan for secrets** in the repository with push protection and a scanner such as gitleaks.
4. **Short-lived credentials for providers**: OIDC from CI to the cloud, not access keys in pipeline secrets (see the plan and apply pipelines section).

## Drift detection

**Drift** is any difference between the real infrastructure and what code and state describe: a manual console change, an auto-scaling event, another tool modifying the same resource, or an expired/rotated resource.

### Detect

A scheduled pipeline that runs `plan` against every root module and alerts on a non-empty plan:

```yaml
name: drift-detection

on:
  schedule:
    - cron: "17 5 * * *"       # daily, off the hour
  workflow_dispatch:

permissions:
  contents: read
  id-token: write
  issues: write

jobs:
  drift:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        stack: [prod/network, prod/data, prod/app-api]
    steps:
      - uses: actions/checkout@v4
      - uses: opentofu/setup-opentofu@v1
        with:
          tofu_version: 1.11.x          # pin to the version you run; verify current
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/iac-plan-readonly
          aws-region: eu-west-1
      - name: Plan (detailed exit code)
        id: plan
        working-directory: live/${{ matrix.stack }}
        run: |
          tofu init -input=false
          set +e
          tofu plan -input=false -lock=false -detailed-exitcode -no-color > plan.txt
          echo "code=$?" >> "$GITHUB_OUTPUT"
      - name: Open or update an issue when drift is found
        if: steps.plan.outputs.code == '2'
        env:
          GH_TOKEN: ${{ github.token }}
          STACK: ${{ matrix.stack }}
        run: |
          gh issue create --title "Drift detected: $STACK" \
            --body-file live/$STACK/plan.txt --label drift || true
```

`-detailed-exitcode` returns 0 for no changes, 1 for errors, and 2 when changes are present. Use a read-only role for the scheduled plan (so a compromised drift job cannot apply), and `-lock=false` for read-only plans to avoid blocking real applies, understanding the plan may be slightly inconsistent if an apply runs concurrently. Replace the action versions with pinned, reviewed SHAs per the hardening post linked at the end.

### Respond

Triage each drift item into one of three outcomes:

1. **Revert the manual change** by applying the code (the usual case, the code is the source of truth).
2. **Adopt the change** by updating the code to match (an intentional emergency fix).
3. **Ignore deliberately** with `lifecycle { ignore_changes = [...] }` for attributes owned by something else, like `desired_count` managed by autoscaling. Document why.

### Prevent

Reduce console access in production (read-only by default, break-glass write roles with audit), use SCPs or policy to block changes outside the pipeline for managed resource types, and enable CloudTrail alerts for write calls from human identities.

## State encryption and OpenTofu-specific features

OpenTofu 1.7 introduced **client-side state and plan encryption**: data is encrypted before it is written to the backend and decrypted when read, with keys from providers such as AES-GCM with a passphrase through PBKDF2, AWS KMS, GCP KMS, or OpenBao. Configuration (verify syntax in the current OpenTofu docs):

```hcl
terraform {
  encryption {
    key_provider "aws_kms" "main" {
      kms_key_id = "alias/tofu-state"
      region     = "eu-west-1"
      key_spec   = "AES_256"
    }

    method "aes_gcm" "default" {
      keys = key_provider.aws_kms.main
    }

    state {
      method = method.aes_gcm.default
    }

    plan {
      method = method.aes_gcm.default
    }
  }
}
```

Operational consequences: losing the key means losing the state, so key management must be as disciplined as backup management; migrating from unencrypted to encrypted state is supported with a documented fallback procedure; and Terraform cannot read OpenTofu-encrypted state, which makes encryption a one-way door in practice if you might switch back.

Other OpenTofu differences to know (verify against current release notes): `for_each` on provider configurations, early variable evaluation allowing variables in module sources and backend blocks, the `enabled` meta-argument, dynamic `prevent_destroy` expressions in 1.12, and the OpenTofu registry as the default provider source. Terraform has features OpenTofu lacks or implements differently as well (for example list resources and `terraform query`, actions, and HCP-integrated capabilities). Before depending on a divergent feature, ask whether you are willing to be locked into that tool.

## Plan and apply pipelines

### Principles

1. **Plan on every pull request; apply only from the default branch.**
2. **Apply the plan you reviewed.** Save the plan to a file in the plan job and apply that exact file after approval, so what was reviewed is what runs. (If a lot of time passes, the plan may go stale, and apply will refuse; re-plan.)
3. **Humans approve production applies.** Use GitHub environments with required reviewers or equivalent.
4. **Serialize applies per state** with `concurrency` groups and state locking.
5. **No long-lived cloud credentials.** Use OIDC with narrow roles: a read-only plan role and a more powerful apply role bound to the protected environment.
6. **The pull request shows the plan.** Reviewers should see the diff of infrastructure, not only code.
7. **Never `apply -auto-approve` from a laptop** against production.

### Plan workflow

```yaml
# .github/workflows/plan.yml
name: iac-plan

on:
  pull_request:
    paths:
      - "live/**"
      - "modules/**"
      - ".github/workflows/plan.yml"

permissions:
  contents: read
  id-token: write
  pull-requests: write

concurrency:
  group: plan-${{ github.event.pull_request.number }}
  cancel-in-progress: true

env:
  STACK: live/prod/app-api

jobs:
  static-checks:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: opentofu/setup-opentofu@v1
        with:
          tofu_version: 1.11.x
      - run: tofu fmt -check -recursive
      - run: tofu init -backend=false -input=false
        working-directory: ${{ env.STACK }}
      - run: tofu validate
        working-directory: ${{ env.STACK }}
      - name: Policy and security scan (Checkov)
        uses: bridgecrewio/checkov-action@v12
        with:
          directory: ${{ env.STACK }}
          framework: terraform
          soft_fail: false

  plan:
    needs: static-checks
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: opentofu/setup-opentofu@v1
        with:
          tofu_version: 1.11.x
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/iac-plan-readonly
          aws-region: eu-west-1
      - name: Init
        working-directory: ${{ env.STACK }}
        run: tofu init -input=false
      - name: Plan
        working-directory: ${{ env.STACK }}
        run: |
          tofu plan -input=false -no-color -out=tfplan | tee plan.txt
          tofu show -json tfplan > plan.json
      - name: Infracost breakdown
        uses: infracost/actions/setup@v3
        with:
          api-key: ${{ secrets.INFRACOST_API_KEY }}
      - name: Cost diff
        working-directory: ${{ env.STACK }}
        run: infracost breakdown --path plan.json --format table
      - name: Policy check on the plan (Conftest/OPA)
        working-directory: ${{ env.STACK }}
        run: |
          curl -sSL -o conftest.tgz https://github.com/open-policy-agent/conftest/releases/download/v0.56.0/conftest_0.56.0_Linux_x86_64.tar.gz
          tar xzf conftest.tgz conftest
          ./conftest test --policy ../../../policy plan.json
      - name: Comment the plan on the pull request
        uses: actions/github-script@v7
        env:
          STACK_PATH: ${{ env.STACK }}
        with:
          script: |
            const fs = require('fs');
            const plan = fs.readFileSync(`${process.env.STACK_PATH}/plan.txt`, 'utf8').slice(-60000);
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: '#### OpenTofu plan\n```\n' + plan + '\n```'
            });
```

Notes: the Conftest version and download URL in this example are illustrative, so use a version you verified and ideally pin by checksum. Secrets are not available to pull requests from forks, so infrastructure repositories normally disallow fork PRs or run plans only for branches in the repository. The plan job uses a **read-only role**. The plan text goes into a pull request comment, so make sure the plan does not contain secrets (mark sensitive values, prefer ephemeral and write-only attributes).

### Apply workflow with approval

```yaml
# .github/workflows/apply.yml
name: iac-apply

on:
  push:
    branches: [main]
    paths:
      - "live/prod/app-api/**"
      - "modules/**"

permissions:
  contents: read
  id-token: write

concurrency:
  group: apply-prod-app-api
  cancel-in-progress: false      # never cancel an apply

env:
  STACK: live/prod/app-api

jobs:
  plan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: opentofu/setup-opentofu@v1
        with:
          tofu_version: 1.11.x
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/iac-plan-readonly
          aws-region: eu-west-1
      - working-directory: ${{ env.STACK }}
        run: |
          tofu init -input=false
          tofu plan -input=false -no-color -out=tfplan
          tofu show -no-color tfplan > plan.txt
      - uses: actions/upload-artifact@v4
        with:
          name: tfplan
          path: |
            ${{ env.STACK }}/tfplan
            ${{ env.STACK }}/plan.txt
          retention-days: 3

  apply:
    needs: plan
    runs-on: ubuntu-latest
    environment: production-infra     # required reviewers + only main branch
    steps:
      - uses: actions/checkout@v4
      - uses: opentofu/setup-opentofu@v1
        with:
          tofu_version: 1.11.x
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/iac-apply-prod
          aws-region: eu-west-1
      - uses: actions/download-artifact@v4
        with:
          name: tfplan
          path: ${{ env.STACK }}
      - working-directory: ${{ env.STACK }}
        run: |
          tofu init -input=false
          tofu apply -input=false tfplan
```

The reviewers on the `production-infra` environment see the plan artifact before approving. The apply role is distinct from the plan role and its trust policy accepts only the environment subject, as described in the GitHub Actions hardening post linked at the end. Saved plan files may contain sensitive values, so keep artifact retention short and treat plan artifacts as secrets (or enable plan encryption in OpenTofu).

### Platforms versus DIY

| Option | When it fits | Trade-off |
| --- | --- | --- |
| GitHub Actions or GitLab CI as above | Small to medium teams, desire for control | You build and maintain the glue: comments, locks, drift, multi-stack ordering |
| Atlantis (open source, self-hosted) | PR-driven `plan` and `apply` comments, multi-repo | You operate a service that holds credentials |
| HCP Terraform / Terraform Enterprise | Terraform-centric organizations wanting managed runs, state, RBAC, Sentinel | Cost and vendor lock-in |
| Spacelift, env0, Scalr, Terrateam and similar | Policy, stacks, drift detection, and both Terraform and OpenTofu support | Cost; evaluate their security model |
| Terragrunt with CI | DRY configs across many stacks | Another layer to learn |

## Policy as code

Policy as code stops dangerous changes before apply. Layer it.

### Tool comparison

| Tool | Stage | What it checks | Notes |
| --- | --- | --- | --- |
| `fmt`, `validate`, TFLint | Static | Syntax, style, provider-specific mistakes (invalid instance types) | Fast; run on every commit |
| Checkov | Static (and plan) | Hundreds of security and compliance rules for Terraform, CloudFormation, Kubernetes, and others | Easy start; tune suppressions |
| Trivy (includes the former tfsec rules) | Static | Misconfigurations in IaC, images, and more | Verify current rule coverage in Trivy docs |
| OPA with Conftest | Plan (JSON) | Custom organizational rules written in Rego | Maximum flexibility; you write the rules |
| Sentinel | Plan | HashiCorp's policy language in HCP Terraform and Terraform Enterprise | Terraform-only, commercial platform |
| Cloud-native guardrails (AWS SCPs, Azure Policy, GCP organization policies) | Runtime | Prevent forbidden API calls regardless of tool | The backstop when the pipeline is bypassed |

### A Rego policy on a plan

```text
package terraform.policy

import rego.v1

# Deny public S3 buckets and unencrypted databases
deny contains msg if {
  some rc in input.resource_changes
  rc.type == "aws_db_instance"
  rc.change.after.storage_encrypted != true
  msg := sprintf("%s: RDS instance must have storage_encrypted = true", [rc.address])
}

deny contains msg if {
  some rc in input.resource_changes
  rc.type == "aws_security_group_rule"
  rc.change.after.type == "ingress"
  "0.0.0.0/0" in rc.change.after.cidr_blocks
  rc.change.after.from_port == 22
  msg := sprintf("%s: SSH must not be open to the internet", [rc.address])
}

# Require approval-style tags
deny contains msg if {
  some rc in input.resource_changes
  rc.change.actions[_] == "create"
  startswith(rc.type, "aws_")
  rc.change.after.tags != null
  not rc.change.after.tags.owner
  msg := sprintf("%s: missing required tag owner", [rc.address])
}
```

Run it with `conftest test --policy policy plan.json` where `plan.json` is the output of `tofu show -json tfplan`. Verify the Rego syntax for the OPA version you use (the `import rego.v1` form is the modern one), and keep a rule's failure message actionable.

### Governance of exceptions

Every suppression needs an owner, a reason, and an expiry. Store them in code (`#checkov:skip=CKV_AWS_18:Access logging handled by central log bucket`) so they show up in review. A policy system people routinely bypass is worse than none because it creates false confidence.

### Guard destructive changes specifically

Add a policy that fails (or requires an extra approval) when a plan contains deletions of stateful resources:

```text
package terraform.guard

import rego.v1

stateful_types := {"aws_db_instance", "aws_rds_cluster", "aws_s3_bucket", "aws_dynamodb_table", "aws_efs_file_system", "aws_kms_key"}

deny contains msg if {
  some rc in input.resource_changes
  rc.type in stateful_types
  "delete" in rc.change.actions
  msg := sprintf("%s: plan deletes a stateful resource; needs explicit approval", [rc.address])
}
```

## Testing IaC

Infrastructure tests are slower and costlier than application tests, so build a pyramid.

### The pyramid

| Level | Tool | What it tests | Cost |
| --- | --- | --- | --- |
| Static | `fmt`, `validate`, TFLint, Checkov, Trivy | Syntax, style, known misconfigurations | Seconds |
| Plan-level unit tests | `terraform test` or `tofu test` with `command = plan` and mocked providers | Module logic, conditionals, outputs, validation rules | Seconds to a minute; no real resources |
| Integration | `terraform test` with `command = apply`, or Terratest | A module applied in a sandbox account, then destroyed | Minutes; real cloud cost |
| End-to-end and smoke | Scripts, synthetic checks after environment deploy | The deployed system actually works | Minutes |
| Policy tests | `opa test`, Conftest tests | Rules behave as expected | Seconds |

### Native tests

Terraform 1.6 introduced `terraform test` with `.tftest.hcl` files, and OpenTofu provides `tofu test`. Mock providers (added in Terraform 1.7 and supported in OpenTofu, verify your version) let you test plan logic without credentials.

```hcl
# modules/vpc/tests/vpc.tftest.hcl
mock_provider "aws" {}

variables {
  name       = "test"
  cidr_block = "10.20.0.0/16"
  az_count   = 3
}

run "creates_three_private_subnets" {
  command = plan

  assert {
    condition     = length(aws_subnet.private) == 3
    error_message = "Expected one private subnet per availability zone."
  }
}

run "rejects_invalid_cidr" {
  command = plan

  variables {
    cidr_block = "not-a-cidr"
  }

  expect_failures = [var.cidr_block]
}
```

Run `tofu test` (or `terraform test`) from the module directory. Apply-mode `run` blocks create real resources in the credentials' account and destroy them at the end; run them in a dedicated sandbox account with budgets and automatic cleanup for leaks.

### Terratest

Terratest (Go) deploys real infrastructure and tests it with arbitrary code, such as HTTP calls:

```go
package test

import (
	"testing"

	"github.com/gruntwork-io/terratest/modules/http-helper"
	"github.com/gruntwork-io/terratest/modules/terraform"
)

func TestEcsServiceResponds(t *testing.T) {
	t.Parallel()

	opts := &terraform.Options{
		TerraformDir:    "../examples/ecs-service",
		TerraformBinary: "tofu",
		Vars:            map[string]interface{}{"name": "tt-" + random(6)},
	}
	defer terraform.Destroy(t, opts)
	terraform.InitAndApply(t, opts)

	url := terraform.Output(t, opts, "url")
	http_helper.HttpGetWithRetry(t, url+"/healthz", nil, 200, "ok", 20, 15*1e9)
}
```

The `random` helper is yours to define. The key practices: unique names per run, `defer Destroy`, a sandbox account, timeouts, and a reaper job that deletes leaked test resources older than a day. Use `TerraformBinary: "tofu"` to run against OpenTofu.

### What to test

- **Module contracts**: variable validation, default values, outputs for the documented examples.
- **Security invariants**: encryption on, public access off, logging on.
- **Upgrade paths**: apply the previous module version, then plan the new version and assert no destroy of stateful resources.
- **Do not test the provider**: asserting that AWS creates an S3 bucket tests nothing you own.

## Importing existing resources

Most real projects begin with infrastructure that already exists. Bring it under management incrementally.

### Import blocks

Since Terraform 1.5 (and in OpenTofu), `import` blocks are declarative and appear in plans:

```hcl
import {
  to = aws_s3_bucket.assets
  id = "acme-assets-prod"
}

resource "aws_s3_bucket" "assets" {
  bucket = "acme-assets-prod"
}
```

Then `tofu plan` shows the import, and `tofu apply` executes it. You can ask the tool to draft the resource configuration:

```bash
tofu plan -generate-config-out=generated.tf
```

Generated configuration is a starting point: it is verbose, contains computed attributes you should remove, and may include defaults you do not want to pin. Review it, simplify it, move it into a module, and iterate until `plan` shows no changes.

### Procedure

1. **Inventory** what exists: use the cloud's resource explorer or a tool such as AWS Config, Terraformer, or aws2tf (verify maintenance status), or an export script.
2. **Prioritize**: foundational and high-risk resources first (network, IAM, data stores), disposable ones later.
3. **Import into a fresh root module** with its own state, one logical group at a time.
4. **Reach a clean plan**: zero changes. Any change on the first plan means your code differs from reality; decide which is right.
5. **Add safeguards** (`prevent_destroy`, deletion protection) on stateful resources before anyone else touches the stack.
6. **Cut over ownership**: announce that these resources are now code-managed, tighten console permissions, and enable drift detection.
7. **Refactor into modules afterward**, with `moved` blocks, not before. Refactoring and importing in one step doubles the risk.

### Pitfalls

- Importing a resource into two states, producing two owners.
- Import IDs vary by resource type (for example some use a composite `cluster/service`). Read the provider documentation's import section.
- Importing resources managed by another system (CloudFormation, CDK) without removing them there first leads to conflict. Decouple with `DeletionPolicy: Retain` and removal from the stack.
- Attributes absent from the provider schema or write-only secrets cannot be imported, so plan to set them after.

## Cost estimation with Infracost

Infrastructure cost is a design property, and the cheapest time to discover a 5,000 dollar a month mistake is in the pull request.

### What Infracost does

Infracost reads your plan or configuration and prices resources using cloud price lists (it supports Terraform and OpenTofu), then shows a monthly cost estimate and a diff for the pull request. It cannot know usage-based costs (data transfer, requests) unless you provide a usage file.

```bash
# Local
infracost breakdown --path plan.json
infracost diff --path plan.json --compare-to baseline.json

# Provide usage assumptions for usage-based resources
infracost breakdown --path plan.json --usage-file infracost-usage.yml
```

```yaml
# infracost-usage.yml
version: 0.1
resource_usage:
  aws_nat_gateway.main:
    monthly_gb_data_processed: 500
  aws_s3_bucket.assets:
    standard:
      storage_gb: 2000
      monthly_tier_1_requests: 5000000
```

### Making it useful

1. **Comment the cost diff on every infrastructure pull request.**
2. **Set guardrails**: fail or require approval when the monthly delta exceeds a threshold, using Infracost's policy support or a Conftest rule on its JSON output.
3. **Tag everything** (cost-center, service, environment) with `default_tags` in the provider so the cloud bill can be attributed. Cost estimation before, tags after.
4. **Know the big levers**: NAT gateways and data transfer, idle load balancers, oversized databases, over-retained logs and snapshots, multi-AZ everywhere including dev.
5. **Combine with budgets** (AWS Budgets, GCP budgets) as runtime alarms.

Check Infracost's current pricing and free tier before adopting it at scale; an open-source CLI exists, with a hosted option for pull request automation.

## Migrating from Terraform to OpenTofu

OpenTofu began as a fork of Terraform 1.5.x and remains largely compatible, but divergence grows with each release. The migration is usually straightforward if you plan it.

### Compatibility check

Before starting, answer:

| Question | Why it matters |
| --- | --- |
| Which Terraform version produced your state? | OpenTofu's documented drop-in path is from specific Terraform versions; state written by newer Terraform versions may use features OpenTofu does not support. Verify the official migration guide for your version |
| Do you use Terraform-only features (for example HCP Terraform-specific integrations, features introduced after the fork that OpenTofu does not implement)? | These need rewriting or removal |
| Which provider versions and registry sources do you use? | OpenTofu uses its own registry by default; most providers are mirrored. Check any private or unusual providers |
| Where do you run Terraform (CI, HCP Terraform, Atlantis, Spacelift)? | The runner or platform needs OpenTofu support |
| Who consumes state (remote state data sources across stacks)? | Mixed Terraform and OpenTofu readers of one state is a risk once either writes newer features |

### Step-by-step

1. **Freeze changes** to the stack for the duration (no other applies) and take a **backup of the state** (copy the S3 object version or run `terraform state pull > backup.tfstate`).
2. **Upgrade Terraform to the latest version your target OpenTofu release is compatible with**, per the migration guide, and apply once so state is in a known format. Verify the supported source versions in the official guide.
3. **Install OpenTofu** (`brew install opentofu`, the official installers, or `opentofu/setup-opentofu` in CI). Pin the version.
4. **Run `tofu init` in the stack** (use `-upgrade` only if you intend to bump providers). OpenTofu will install providers from its registry and write the lock file.
5. **Run `tofu plan` and require a no-op plan.** Any change means either a provider version difference or a language divergence; investigate before proceeding.
6. **Apply once with OpenTofu** (even a no-op apply writes state with OpenTofu's version). From now on, Terraform should not touch this state.
7. **Update CI** to use `tofu` commands and the setup action; update pre-commit hooks, TFLint, and editor tooling.
8. **Update the lock file** and commit. Regenerate hashes for all your platforms.
9. **Roll out stack by stack**, starting with non-production and low-risk stacks.
10. **Adopt OpenTofu features deliberately**, one at a time (state encryption first, for most teams), with a rollback plan, because using OpenTofu-only features makes returning to Terraform harder.

```bash
# Backup, then migrate a stack
cd live/staging/network
terraform state pull > ../../../backups/staging-network.tfstate   # backup first
tofu init
tofu plan -out=tfplan          # must show: No changes
tofu apply tfplan              # writes state with OpenTofu
```

### Rollback

If something goes wrong before the first OpenTofu apply, you have lost nothing: continue with Terraform. After the first apply, restore the backed-up state version in the backend and re-run Terraform, assuming no OpenTofu-only features were used and no resources changed in between. Rehearse in a throwaway stack first.

### Moving to HCP Terraform or away from it

If you currently use HCP Terraform and want to move to a self-managed backend with OpenTofu, migrate state out first (`terraform state pull`, then configure an S3 or GCS backend and `init -migrate-state`), and replace Sentinel policies with OPA and Checkov equivalents. Plan for the loss of run history and private registry modules by mirroring modules to your own registry or git tags.

## A full AWS example: VPC and ECS Fargate service

This example builds a small, realistic stack: a VPC with public and private subnets, an Application Load Balancer, an ECS Fargate cluster, and a service pulling an image by digest, with logs, least-privilege roles, and secrets injected from Secrets Manager. It is written for clarity, not as a drop-in production design. Verify provider arguments against the current AWS provider documentation.

### Layout

```text
live/prod/app-api/
├── backend.tf
├── versions.tf
├── providers.tf
├── variables.tf
├── main.tf        # network + alb + ecs wiring
├── outputs.tf
└── terraform.tfvars
```

### versions.tf and providers.tf

```hcl
# versions.tf
terraform {
  required_version = ">= 1.9.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}
```

```hcl
# providers.tf
provider "aws" {
  region = var.region

  default_tags {
    tags = {
      project     = "app-api"
      environment = var.environment
      owner       = "platform-team"
      managed_by  = "opentofu"
    }
  }
}
```

### variables.tf

```hcl
variable "region" {
  type    = string
  default = "eu-west-1"
}

variable "environment" {
  type = string
}

variable "image_digest" {
  type        = string
  description = "Full image reference by digest, for example 123456789012.dkr.ecr.eu-west-1.amazonaws.com/app-api@sha256:..."
}

variable "desired_count" {
  type    = number
  default = 2
}

variable "container_port" {
  type    = number
  default = 8080
}

variable "db_secret_arn" {
  type        = string
  description = "Secrets Manager ARN holding the database credentials JSON."
}
```

### Network: VPC, subnets, routing

```hcl
data "aws_availability_zones" "available" {
  state = "available"
}

locals {
  name = "app-api-${var.environment}"
  azs  = slice(data.aws_availability_zones.available.names, 0, 2)
}

resource "aws_vpc" "main" {
  cidr_block           = "10.10.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true
  tags                 = { Name = local.name }
}

resource "aws_internet_gateway" "main" {
  vpc_id = aws_vpc.main.id
  tags   = { Name = local.name }
}

resource "aws_subnet" "public" {
  for_each                = toset(local.azs)
  vpc_id                  = aws_vpc.main.id
  availability_zone       = each.value
  cidr_block              = cidrsubnet(aws_vpc.main.cidr_block, 8, index(local.azs, each.value))
  map_public_ip_on_launch = false
  tags                    = { Name = "${local.name}-public-${each.value}" }
}

resource "aws_subnet" "private" {
  for_each          = toset(local.azs)
  vpc_id            = aws_vpc.main.id
  availability_zone = each.value
  cidr_block        = cidrsubnet(aws_vpc.main.cidr_block, 8, 10 + index(local.azs, each.value))
  tags              = { Name = "${local.name}-private-${each.value}" }
}

resource "aws_route_table" "public" {
  vpc_id = aws_vpc.main.id
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.main.id
  }
  tags = { Name = "${local.name}-public" }
}

resource "aws_route_table_association" "public" {
  for_each       = aws_subnet.public
  subnet_id      = each.value.id
  route_table_id = aws_route_table.public.id
}

# One NAT gateway per AZ for resilience; for dev, use a single one to cut cost.
resource "aws_eip" "nat" {
  for_each = aws_subnet.public
  domain   = "vpc"
}

resource "aws_nat_gateway" "main" {
  for_each      = aws_subnet.public
  allocation_id = aws_eip.nat[each.key].id
  subnet_id     = each.value.id
  depends_on    = [aws_internet_gateway.main]
  tags          = { Name = "${local.name}-${each.key}" }
}

resource "aws_route_table" "private" {
  for_each = aws_subnet.private
  vpc_id   = aws_vpc.main.id
  route {
    cidr_block     = "0.0.0.0/0"
    nat_gateway_id = aws_nat_gateway.main[each.key].id
  }
  tags = { Name = "${local.name}-private-${each.key}" }
}

resource "aws_route_table_association" "private" {
  for_each       = aws_subnet.private
  subnet_id      = each.value.id
  route_table_id = aws_route_table.private[each.key].id
}
```

Note the use of `for_each` keyed by availability zone name instead of `count`, so adding or removing a zone does not shift indexes and recreate unrelated subnets. NAT gateways are a major cost driver (each has an hourly charge plus per-GB processing), which is exactly the kind of line Infracost will surface in the pull request.

### Security groups and load balancer

```hcl
resource "aws_security_group" "alb" {
  name_prefix = "${local.name}-alb-"
  vpc_id      = aws_vpc.main.id
  description = "Public ALB"

  ingress {
    description = "HTTPS from the internet"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    description     = "To tasks only"
    from_port       = var.container_port
    to_port         = var.container_port
    protocol        = "tcp"
    security_groups = [aws_security_group.task.id]
  }

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_security_group" "task" {
  name_prefix = "${local.name}-task-"
  vpc_id      = aws_vpc.main.id
  description = "ECS tasks"

  egress {
    description = "Outbound for AWS APIs and image pulls"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_security_group_rule" "task_from_alb" {
  type                     = "ingress"
  from_port                = var.container_port
  to_port                  = var.container_port
  protocol                 = "tcp"
  security_group_id        = aws_security_group.task.id
  source_security_group_id = aws_security_group.alb.id
  description              = "From the ALB"
}

resource "aws_lb" "main" {
  name                       = local.name
  load_balancer_type         = "application"
  security_groups            = [aws_security_group.alb.id]
  subnets                    = [for s in aws_subnet.public : s.id]
  drop_invalid_header_fields = true
  enable_deletion_protection = true
}

resource "aws_lb_target_group" "app" {
  name        = local.name
  port        = var.container_port
  protocol    = "HTTP"
  target_type = "ip"
  vpc_id      = aws_vpc.main.id

  health_check {
    path                = "/healthz/ready"
    healthy_threshold   = 2
    unhealthy_threshold = 3
    interval            = 15
    timeout             = 5
    matcher             = "200"
  }

  deregistration_delay = 30
}

resource "aws_lb_listener" "https" {
  load_balancer_arn = aws_lb.main.arn
  port              = 443
  protocol          = "HTTPS"
  ssl_policy        = "ELBSecurityPolicy-TLS13-1-2-2021-06"
  certificate_arn   = var.certificate_arn

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.app.arn
  }
}
```

Add `variable "certificate_arn"` with an ACM certificate ARN to the variables file. The ALB egress rule and the task security group enforce that only the load balancer reaches tasks. Task egress is limited to HTTPS; if the service also talks to a database in the same VPC, add a rule to that database's security group.

### ECS cluster, roles, task, and service

```hcl
resource "aws_cloudwatch_log_group" "app" {
  name              = "/ecs/${local.name}"
  retention_in_days = 30
}

resource "aws_ecs_cluster" "main" {
  name = local.name

  setting {
    name  = "containerInsights"
    value = "enabled"
  }
}

data "aws_iam_policy_document" "ecs_tasks_assume" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ecs-tasks.amazonaws.com"]
    }
  }
}

# Execution role: lets ECS pull the image, write logs, and read the secret
resource "aws_iam_role" "execution" {
  name               = "${local.name}-execution"
  assume_role_policy = data.aws_iam_policy_document.ecs_tasks_assume.json
}

resource "aws_iam_role_policy_attachment" "execution_managed" {
  role       = aws_iam_role.execution.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}

data "aws_iam_policy_document" "read_secret" {
  statement {
    actions   = ["secretsmanager:GetSecretValue"]
    resources = [var.db_secret_arn]
  }
}

resource "aws_iam_role_policy" "execution_secret" {
  name   = "read-db-secret"
  role   = aws_iam_role.execution.id
  policy = data.aws_iam_policy_document.read_secret.json
}

# Task role: what the application code itself may do (keep minimal)
resource "aws_iam_role" "task" {
  name               = "${local.name}-task"
  assume_role_policy = data.aws_iam_policy_document.ecs_tasks_assume.json
}

resource "aws_ecs_task_definition" "app" {
  family                   = local.name
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  cpu                      = 512
  memory                   = 1024
  execution_role_arn       = aws_iam_role.execution.arn
  task_role_arn            = aws_iam_role.task.arn

  runtime_platform {
    operating_system_family = "LINUX"
    cpu_architecture        = "ARM64"
  }

  container_definitions = jsonencode([
    {
      name      = "app"
      image     = var.image_digest
      essential = true
      portMappings = [
        { containerPort = var.container_port, protocol = "tcp" }
      ]
      readonlyRootFilesystem = true
      environment = [
        { name = "APP_ENV", value = var.environment },
        { name = "PORT", value = tostring(var.container_port) }
      ]
      secrets = [
        { name = "DATABASE_CREDENTIALS", valueFrom = var.db_secret_arn }
      ]
      logConfiguration = {
        logDriver = "awslogs"
        options = {
          awslogs-group         = aws_cloudwatch_log_group.app.name
          awslogs-region        = var.region
          awslogs-stream-prefix = "app"
        }
      }
    }
  ])
}

resource "aws_ecs_service" "app" {
  name            = local.name
  cluster         = aws_ecs_cluster.main.id
  task_definition = aws_ecs_task_definition.app.arn
  desired_count   = var.desired_count
  launch_type     = "FARGATE"

  deployment_minimum_healthy_percent = 100
  deployment_maximum_percent         = 200

  deployment_circuit_breaker {
    enable   = true
    rollback = true       # automatic rollback when a deployment fails to stabilize
  }

  network_configuration {
    subnets          = [for s in aws_subnet.private : s.id]
    security_groups  = [aws_security_group.task.id]
    assign_public_ip = false
  }

  load_balancer {
    target_group_arn = aws_lb_target_group.app.arn
    container_name   = "app"
    container_port   = var.container_port
  }

  lifecycle {
    ignore_changes = [desired_count]    # owned by autoscaling below
  }

  depends_on = [aws_lb_listener.https]
}

resource "aws_appautoscaling_target" "app" {
  max_capacity       = 10
  min_capacity       = var.desired_count
  resource_id        = "service/${aws_ecs_cluster.main.name}/${aws_ecs_service.app.name}"
  scalable_dimension = "ecs:service:DesiredCount"
  service_namespace  = "ecs"
}

resource "aws_appautoscaling_policy" "cpu" {
  name               = "${local.name}-cpu"
  policy_type        = "TargetTrackingScaling"
  resource_id        = aws_appautoscaling_target.app.resource_id
  scalable_dimension = aws_appautoscaling_target.app.scalable_dimension
  service_namespace  = aws_appautoscaling_target.app.service_namespace

  target_tracking_scaling_policy_configuration {
    target_value = 60
    predefined_metric_specification {
      predefined_metric_type = "ECSServiceAverageCPUUtilization"
    }
  }
}
```

Design points worth noting: the image is referenced **by digest** (build once, deploy many, see the CI/CD post linked below), which makes every deploy a plan diff of the digest. The ECS **deployment circuit breaker** rolls back a failed rollout automatically. `desired_count` is in `ignore_changes` because autoscaling owns it, and that is documented next to the code. Secrets are injected by ECS at task start from Secrets Manager, so they are not in the Terraform state or the task definition's environment. The task root filesystem is read-only, and the task role starts empty and grows only as the application needs.

### outputs.tf and deploying new versions

```hcl
output "alb_dns_name" {
  value = aws_lb.main.dns_name
}

output "service_name" {
  value = aws_ecs_service.app.name
}
```

A new application release changes one variable, `image_digest`, which produces a one-resource-plus-task-definition diff reviewed like any other change. For frequent application deploys many teams split infrastructure (this stack) from deployment (a pipeline that updates the task definition), accepting `ignore_changes` on the task definition. Choose one owner for that attribute; do not let both Terraform and a deployment script write it.

### Applying it

```bash
cd live/prod/app-api
tofu init
tofu fmt -check && tofu validate
tofu plan -var-file=terraform.tfvars -out=tfplan
tofu show tfplan              # read it, all of it
tofu apply tfplan
```

In production this runs through the plan and apply pipeline described earlier, not from a laptop.

## Common footguns

1. `count` for things that have identity. Removing the second item of a list shifts indexes and destroys the third. Use `for_each` over a stable key.
2. No lifecycle protection on stateful resources. Add `lifecycle { prevent_destroy = true }` plus the service's own deletion protection (RDS `deletion_protection`, ALB `enable_deletion_protection`, S3 versioning and object lock) to databases, buckets, keys, and anything you cannot recreate.
3. Forced replacement hidden in a plan. Changing an immutable attribute (for example an RDS identifier, a subnet CIDR) shows `-/+` (destroy and re-create). Read every replacement line. Search plans for `must be replaced` and `forces replacement`.
4. `-target` as a habit. It skips dependencies and leaves state inconsistent with code. Use it only for emergencies and follow up with a full plan.
5. `terraform apply -auto-approve` from laptops. Bypasses review and hides drift. Remove production write permissions from human roles.
6. Secrets in state, logs, and plan comments. See the section on secrets in state and in code. Remember that plan output pasted into PR comments is public to the repository.
7. Local state or a shared state for everything. Local state gets lost; a monolithic state is a blast radius and a performance problem.
8. Unpinned providers and modules. A silent upgrade changes behaviour. Commit the lock file; pin modules.
9. Using `latest` image tags in the task definition, so a plan shows no change while behaviour changes. Use digests.
10. Circular dependencies between stacks or reading remote state from many places. Keep dependency direction one way; publish contracts through a parameter store or outputs.
11. Provisioners (`local-exec`, `remote-exec`) for configuration management. They are a last resort, are not part of the plan, and fail in confusing ways. Use user data, images, or a config tool.
12. `ignore_changes = all` that silently disables drift detection for a resource. Ignore specific attributes and comment why.
13. Data sources that change every run (timestamps, `latest` AMI lookups) causing perpetual diffs or surprise replacements. Pin AMI IDs or use controlled lookup filters with an explicit schedule for updates.
14. Huge plans nobody reads. Split states and PRs so reviewers can really review. A 2,000-line plan is rubber-stamped.
15. Mixing Terraform and OpenTofu on one state without a deliberate cutover. Pick one writer.
16. Creating the state bucket without versioning or protection and then deleting it with `destroy`.
17. Over-permissive CI roles: administrator access on the apply role. Scope IAM to the services the stack manages and add permission boundaries.
18. No cleanup of test infrastructure, leaking cloud spend from integration tests.

## When not to use IaC (or this much of it)

- Truly one-off, throwaway resources. A short-lived experiment in a sandbox account may not need a repository. Tag it, set a budget, and delete it.
- Highly dynamic resources owned by an application. Per-tenant or per-request resources (for example thousands of queues created at runtime) belong in application code using cloud SDKs, with IaC owning only the platform they depend on.
- Stateful data migrations. IaC creates the database; it does not migrate your data. Use migration tools in the deployment pipeline.
- Tiny teams with a handful of resources and low risk. A well-documented manual setup may be rational for a weekend project; the moment two people or any production data are involved, automate.
- Configuration management inside machines. IaC provisions infrastructure; configuring operating systems and applications belongs in images (Packer), containers, or configuration tools.
- Kubernetes workload manifests in a general IaC tool. Prefer GitOps controllers (Argo CD, Flux) for in-cluster resources and use IaC for the cluster itself.
- Rewriting everything at once. Do not stop feature work for a "big bang" IaC migration; import and codify incrementally, starting with the riskiest resources.
- Switching tools for fashion. If Terraform or OpenTofu works for your organization today and your license position is clear, migration cost may not pay off; decide on concrete requirements (license policy, state encryption, vendor risk), not on discourse.

## Questions that come up

**Is Terraform still free to use?**
For most organizations using it to manage their own infrastructure, yes; the BSL restricts use in products that compete with HashiCorp's commercial offerings. Read the license and the vendor FAQ, and consult counsel if you build a product around it.

**Can I switch between Terraform and OpenTofu freely?**
Early on, yes, because OpenTofu forked from Terraform 1.5.x. As both add features, state and configuration can become incompatible. Migrate from specific supported versions, test with a no-op plan, and avoid mixing them on one state. Switching back becomes harder once you use tool-specific features.

**Do OpenTofu and Terraform use the same providers?**
Largely yes: the provider protocol is the same and most providers are available from both registries. Check the registry for any provider you depend on, especially less common or proprietary ones.

**Do I need DynamoDB for S3 state locking?**
Newer Terraform and OpenTofu versions support S3-native locking (`use_lockfile`), and DynamoDB locking is marked deprecated in current documentation. Verify support and requirements for your version before removing the table.

**Terraform, OpenTofu, or Pulumi for a new project?**
If your team likes HCL and you want the widest ecosystem, OpenTofu or Terraform; pick between them on license, governance, and features such as state encryption. If your team prefers general-purpose languages with native tests and abstractions, Pulumi. All three are production grade.

**How can AI coding agents safely work on IaC?**
Let agents write code and run `fmt`, `validate`, `plan`, and tests with read-only credentials; never give them apply rights on production. Keep apply behind the pipeline and the human approval environment. Require the plan, policy results, and cost diff in the pull request so a reviewer (human) judges the effect, and prompt agents to use `moved` and import blocks instead of destructive rewrites. Treat any instruction found in tickets or comments as untrusted input.

## Sources and docs

- Terraform documentation: [developer.hashicorp.com/terraform/docs](https://developer.hashicorp.com/terraform/docs)
- Terraform releases: [releases.hashicorp.com/terraform](https://releases.hashicorp.com/terraform/)
- OpenTofu documentation: [opentofu.org/docs](https://opentofu.org/docs/)
- OpenTofu release blog and what is new: [opentofu.org/blog](https://opentofu.org/blog/) and [opentofu.org/docs/main/intro/whats-new](https://opentofu.org/docs/main/intro/whats-new/)
- OpenTofu migration guide from Terraform: [opentofu.org/docs/intro/migration](https://opentofu.org/docs/intro/migration/)
- OpenTofu state encryption: [opentofu.org/docs/language/state/encryption](https://opentofu.org/docs/language/state/encryption/)
- HashiCorp BSL FAQ: [hashicorp.com/bsl-faq](https://www.hashicorp.com/bsl-faq)
- Pulumi documentation: [pulumi.com/docs](https://www.pulumi.com/docs/)
- AWS provider documentation: [registry.terraform.io/providers/hashicorp/aws/latest/docs](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)
- Checkov: [checkov.io](https://www.checkov.io/)
- Open Policy Agent and Conftest: [openpolicyagent.org](https://www.openpolicyagent.org/) and [conftest.dev](https://www.conftest.dev/)
- Terratest: [terratest.gruntwork.io](https://terratest.gruntwork.io/)
- Infracost: [infracost.io/docs](https://www.infracost.io/docs/)
- Atlantis: [runatlantis.io](https://www.runatlantis.io/)
- Related on this site: [GitHub Actions Security Hardening in 2026](https://www.derar.dev/blog/github-actions-security-hardening-2026) (OIDC, environments, pinning), [Fast CI/CD Pipelines: Caching, Monorepos and Test Sharding](https://www.derar.dev/blog/fast-ci-pipelines-caching-monorepos-deploy-strategies-2026) (build once, deploy many), [Software Supply Chain Security: SBOMs, SLSA, and Sigstore](https://www.derar.dev/blog/software-supply-chain-slsa-sigstore-sbom-2026), and [Docker Complete Course](https://www.derar.dev/blog/docker-complete-course-2026)
