Infrastructure as Code: Terraform State, Modules, Plan/Apply, Pulumi, CDK, CloudFormation
"HashiCorp Terraform is an infrastructure as code tool that lets you define both cloud and on-prem resources in human-readable configuration files that you can version, reuse, and share." — Terraform documentation, What is Terraform? (developer.hashicorp.com/terraform/intro)
Summary: Infrastructure as Code describes networks, databases, queues and permissions in versioned files instead of console clicks; Terraform (and its open-source fork OpenTofu) reads those declarative files, compares them with a state file that maps every resource address to a real object, shows the difference as a plan, and applies exactly that plan through provider APIs, while Pulumi, AWS CDK, CloudFormation, Bicep and Crossplane solve the same problem with real programming languages, AWS-managed stacks, Azure-native templates or Kubernetes controllers. Focus: Declarative vs imperative, idempotence, drift and immutable infrastructure; HCL, providers and the Terraform Registry, the dependency lock file; resources and data sources; variables, locals, outputs, tfvars and variable precedence; expressions, functions, for_each, count and dynamic blocks; lifecycle meta-arguments (create_before_destroy, prevent_destroy, ignore_changes) and why provisioners are a last resort; terraform init / validate / fmt / plan / apply / destroy, the plan file as a contract, -target and -replace; state (what terraform.tfstate stores, secrets in state, sensitive), remote backends (S3 with use_lockfile or the deprecated DynamoDB lock, GCS, azurerm, HCP Terraform) and state locking; terraform state mv / rm, import, moved and removed blocks; drift detection with plan -refresh-only; modules (root module, module source and version, composition, registry modules, anti-patterns); directory per environment vs workspaces, Terragrunt; terraform test with mock_provider, tflint, Checkov, Trivy, OPA and Sentinel; CI (plan on PR, apply on merge, OIDC, plan artifact, concurrency); ephemeral values and write-only arguments, the Vault provider; the BSL license change and OpenTofu (state encryption); Pulumi, AWS CDK (cdk synth), CloudFormation stacks, change sets and drift, Bicep and ARM templates, Crossplane, Ansible; the kubernetes and helm providers vs GitOps; an AWS stack for the Go service and the Laravel app (VPC module, RDS, ElastiCache, S3 bucket, SES, SQS, ECS) and a Go program that reads terraform output -json. Learning goal: Write a Terraform root module that is safe to plan in CI and apply on merge; explain exactly what the state file contains and how it is locked, shared and protected; rename, adopt and retire resources without destroying them; split a system into modules and environments that a team can own; test modules without a cloud account; keep secrets out of state where the provider allows it; and choose between Terraform, OpenTofu, Pulumi, CDK, CloudFormation and Crossplane for a given team.
This is the infrastructure chapter of the Delivery & Infrastructure group. It provisions what the other chapters run on. The pipeline mechanics that run terraform plan (runners, caches, OIDC, environments) are CI/CD Pipelines; reconciling Kubernetes objects from Git, and Crossplane as a Kubernetes-native alternative, are GitOps; rolling out a new task definition or image behind a load balancer is Deployment Strategies; what VPCs, subnets, IAM, managed databases and DNS are across AWS, Azure and GCP is Cloud Provider Primitives; configuring software inside servers (packages, files, services) is Configuration Management; charts that Terraform's helm provider could install are Packaging for Kubernetes; Secrets, External Secrets and the Vault side of secret delivery inside a cluster are Kubernetes Config, Secrets & Storage; and deployment stamps, geodes and other reliability patterns that an infrastructure layout implements are Cloud Design Patterns II. The Git workflow around an infrastructure repository (branches, reviews) is Git & Version Control.
Verified against: Terraform v1.17.2 and OpenTofu v1.13.10 (darwin/arm64 release binaries, SHA-256 checked against the published SHA256SUMS), providers hashicorp/random v3.9.1, hashicorp/local v2.9.1, hashicorp/tls v4.4.2 and hashicorp/aws v6.74.0, Go 1.27.4, Terraform docs (developer.hashicorp.com, latest = v1.17.x), OpenTofu docs v1.13, Laravel 13.x, on 2026-11-29. Every Terraform and OpenTofu transcript on this page was produced on the build host by scripts/lab.sh (cloud-free providers) or scripts/aws-check.sh (validate and mocked tests); nothing was planned or applied against a real AWS account (see Lab).
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why clicking in a console stops working | Why it exists |
| CloudFormation 2011, Terraform 0.1 2014, 1.0, BSL, OpenTofu, 1.10, 1.11 | Where it comes from |
| Declarative, idempotent, drift, immutable infrastructure | IaC fundamentals |
HCL, blocks, providers, the Terraform Registry, .terraform.lock.hcl | HCL and providers |
resource, data, references, the dependency graph | Resources and data sources |
variable, locals, output, tfvars, which value wins | Variables, locals, outputs |
for_each, count, dynamic, for expressions, functions | Repetition and expressions |
create_before_destroy, prevent_destroy, ignore_changes, provisioners | Lifecycle and provisioners |
init, validate, fmt, plan, apply, destroy, -out, -target, -replace | The core workflow |
What terraform.tfstate holds, secrets in it | State |
S3 + use_lockfile, DynamoDB lock, GCS, azurerm, HCP Terraform, locking | Remote backends and locking |
state mv, state rm, import, moved, removed | Refactoring state |
plan -refresh-only, drift detection | Drift |
| Root module, child modules, sources, versions, composition | Modules |
| Directory per environment, workspaces, Terragrunt | Environments |
terraform test, mock_provider, tflint, Checkov, Trivy, OPA, Sentinel | Testing and policy |
| Plan on PR, apply on merge, OIDC, plan artifact | CI for infrastructure |
sensitive, ephemeral, write-only, Vault provider | Secrets |
| BSL 2023, OpenTofu and how it differs | Licensing and OpenTofu |
| Pulumi, AWS CDK, CloudFormation, Bicep, Crossplane, Ansible | The alternatives |
| kubernetes and helm providers vs Argo CD / Flux | Terraform and Kubernetes |
| What plan and apply do inside, knobs, error messages | Mechanics |
| Code | Go, Laravel, The Terraform code |
| Classic problems and fixes | Solving the classic problems |
| Which tool, which layout, which backend | Choosing |
| From one stack to many regions | In architecture |
| Commands with real output | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
Terraform in one table.
| Thing | What it is | Where it lives | Trap |
|---|---|---|---|
| Configuration | .tf files in HCL: what should exist | Git, one directory = one module | Files in a directory are merged; names, not files, matter |
| Provider | A plugin that talks to one API (aws, google, azurerm, kubernetes, random) | Downloaded by terraform init from the Terraform Registry into .terraform/ | Pin versions; commit .terraform.lock.hcl |
| Resource | One managed object (aws_db_instance.postgres) | Declared in code, recorded in state | Renaming the address = destroy + create, unless moved |
| Data source | A read-only lookup (data "aws_iam_policy_document") | Read on every plan | Unknown values at plan time make dependent values unknown too |
| State | The map from addresses to real object IDs plus last known attributes | terraform.tfstate locally, or a remote backend | Contains every attribute, including passwords, in plain text |
| Plan | The diff between configuration and refreshed state | Printed, or saved with -out=tfplan | An unsaved plan may differ from what apply later does |
| Module | A directory of .tf files called with module "x" { source = ... } | Local path, Git, the Terraform Registry | A module is a reusable unit, not an environment |
| Workspace | Another state for the same configuration and backend | terraform.tfstate.d/<name>/ or a key prefix | Same code, same credentials: not an isolation boundary |
The commands that matter.
| Command | Does | Writes state? |
|---|---|---|
terraform init | Installs providers and modules, configures the backend, writes .terraform.lock.hcl | No |
terraform fmt -check -recursive / terraform validate | Canonical formatting / syntax, types and references, no API calls | No |
terraform plan -out=tfplan | Refresh, diff, save the plan | No (but takes the lock) |
terraform apply tfplan | Execute exactly the saved plan; fails if the state changed since ("Saved plan is stale") | Yes |
terraform plan -refresh-only / apply -refresh-only | Show / accept drift into state without changing infrastructure | Only apply |
terraform plan -replace=ADDR | Plan a destroy-and-create of one object (replaces taint) | No |
terraform state list / show / mv / rm | Inspect or edit state directly | mv, rm yes |
terraform import ADDR ID / import {} block | Adopt an existing object | Yes / at apply |
terraform output -json | All root outputs as JSON, sensitive values in plain text | No |
terraform test | Run .tftest.hcl files (plan or apply in a throwaway state) | No (own state) |
terraform destroy | Plan and apply deletion of everything in this state | Yes |
State and backends in one table.
| Backend | Locking | Encryption at rest | Notes |
|---|---|---|---|
local (default) | Lock file next to the state (.terraform.tfstate.lock.info) | None | One laptop only; never commit the file |
s3 | use_lockfile = true (lock object <key>.tflock, GA in 1.11) or dynamodb_table (deprecated) | encrypt = true, bucket SSE/KMS | Enable bucket versioning to recover old states |
gcs | Built in (lock object) | Google-managed or kms_encryption_key | Bucket versioning recommended |
azurerm | Blob lease | Storage service encryption | Container per environment or key per environment |
HCP Terraform / cloud block | Workspace lock, queued runs | Managed | Also runs plans remotely, policy checks (Sentinel/OPA) |
| OpenTofu any backend | Same as the backend | Optional client-side encryption block (AES-GCM, PBKDF2/KMS keys) | Terraform cannot read encrypted state |
Why it exists
The Go orders-api and the Laravel shop in this course need a network with public and private subnets, a Postgres database, a Redis cache, an object-storage bucket for uploaded files, a verified mail domain, a job queue with a dead-letter queue, container services, log groups and a dozen IAM roles, in staging and in production. Built by hand in a cloud console, that is a few hundred clicks. The first time works. Then staging and prod differ in ways nobody wrote down, a security group rule added during an incident stays forever, nobody can say which IAM policy the worker really needs, and rebuilding the environment in another region is a project of its own. The console has no diff, no review and no history.
Infrastructure as Code turns that into files. The files are reviewed like application code, they create staging and production from the same source with different parameters, and a tool computes what has to change to make reality match them. Terraform adds one more idea that matters as much as the files: a state file that records which real object each block created, so the tool can update or delete exactly those objects later and can show, before touching anything, a plan of creates, updates, replacements and deletions.
| Simpler choice | Richer choice | What you buy | What you pay |
|---|---|---|---|
| Console clicks | Scripts calling the CLI (aws ec2 create-vpc ...) | Repeatable creation | No update or delete logic; reruns create duplicates |
| Imperative scripts | Declarative IaC (Terraform, CloudFormation, Bicep) | Idempotent runs, a plan before every change, updates and deletes computed for you | A state to protect (Terraform) or a managed stack (CloudFormation) |
| Local state on a laptop | Remote backend with locking | Shared, locked, versioned state | A bucket and IAM to bootstrap first |
| One big root module | Modules + one root per environment | Small blast radius, reuse, ownership per team | Wiring outputs to inputs; more states |
| Plans run by hand | Plan on PR, apply on merge | Review of the exact change, audit trail, no admin keys on laptops | A pipeline, OIDC roles, a plan artefact flow |
| HCL | Pulumi or CDK in a general-purpose language | Loops, classes, unit tests in your language | Less constrained code; more ways to be clever |
The analogy used through this page: an architect's drawings and the land registry. The .tf files are the architect's drawings: they say what should stand on each plot. The real buildings are the cloud resources. Terraform's state is the land registry: an entry per plot that says "plot aws_db_instance.postgres is the building with deed number shop-prod-pg". Without the registry the builder can see buildings but cannot tell which ones it put up and is responsible for; with a registry that two builders edit at the same time (no lock), entries get lost; and if the registry is copied into a public folder, anyone can read the private details written in it (secrets in state). A plan is the builder's written quote: "two walls to add, one window to replace, nothing to demolish". You sign the quote, not a promise to "do what the drawings say", which is why saved plans matter.
Three common misunderstandings, up front
- "
sensitive = truekeeps the password out of the state file." It does not. The lab's state contained the 24-character password three times (therandom_passwordresult, the file content and the output value);sensitiveonly hides it in plan and apply output, andterraform output -jsonprints it in clear. Only ephemeral values, write-only arguments, or a service that keeps the secret (RDSmanage_master_user_password) keep it out. See Secrets. - "Renaming a resource block is a cosmetic change." The address is the identity. Renaming
local_file.service_configtolocal_file.servicemakes Terraform plan to destroy the old objects and create new ones; amovedblock turns that into "has moved to" with zero changes (both shown in the Lab). - "
prevent_destroyprotects a resource." It rejects plans that would destroy the object while the block and itslifecyclesetting are in the configuration. Delete the block and Terraform destroys the object: the docs say the rule "doesn't prevent Terraform from destroying a resource if you remove its configuration". Use the provider's own deletion protection (RDSdeletion_protection) as well. See Lifecycle.
Where it comes from
| When | What happened | Source |
|---|---|---|
| 25 Feb 2011 | AWS introduces CloudFormation: templates describing a stack of AWS resources, provisioned and updated as one unit | AWS What's New, "Introducing AWS CloudFormation" |
| 28 Jul 2014 | Terraform v0.1.0 released by HashiCorp, open source under the Mozilla Public License 2.0 | GitHub release v0.1.0; OpenTofu manifesto ("open-sourced in 2014 under the Mozilla Public License (v2.0)") |
| 8 Jun 2021 | Terraform 1.0.0: the 1.x compatibility promise | Terraform v1.0 CHANGELOG |
| 8 Dec 2021 | Terraform 1.1.0: moved blocks "for refactoring within modules" | Terraform v1.1 CHANGELOG |
| 12 Jun 2023 | Terraform 1.5.0: import blocks ("Import is now a configuration-driven, plannable action"), -generate-config-out, check blocks | Terraform v1.5 CHANGELOG |
| 10 Aug 2023 | HashiCorp switches Terraform from MPL 2.0 to the Business Source License v1.1 | OpenTofu manifesto; Linux Foundation press release; Terraform LICENSE ("Terraform Version 1.6.0 or later") |
| 20 Sep 2023 | The Linux Foundation announces OpenTofu (formerly OpenTF), "an open source alternative to Terraform" under MPL 2.0 | Linux Foundation press release |
| 4 Oct 2023 | Terraform 1.6.0, the first BSL release: terraform test generally available (.tftest.hcl, run blocks) | Terraform v1.6 CHANGELOG; GitHub release v1.6.0 |
| 10 Jan 2024 | OpenTofu 1.6.0, "now stable" | GitHub release opentofu v1.6.0 |
| 17 Jan 2024 | Terraform 1.7.0: removed blocks, mock_provider / override_resource / override_data in tests | Terraform v1.7 CHANGELOG |
| 30 Apr 2024 | OpenTofu 1.7.0: client-side state encryption, provider-defined functions, removed block, loopable import blocks | OpenTofu blog "OpenTofu 1.7.0 is out"; What's new in 1.7 |
| 27 Nov 2024 | Terraform 1.10.0: ephemeral resources and ephemeral input/output values, "not persisted to the plan or state files" | Terraform v1.10 CHANGELOG |
| 27 Feb 2025 | Terraform 1.11.0: S3 native state locking (use_lockfile) generally available, DynamoDB arguments deprecated; write-only attributes | Terraform v1.11 CHANGELOG |
| Today | Terraform v1.17.2 (checkpoint API), OpenTofu v1.13.10 (latest GitHub release, 23 Nov 2026); the Terraform LICENSE names "International Business Machines Corporation (IBM)" as licensor | checkpoint-api.hashicorp.com; GitHub; LICENSE file on main |
Two lines of thought meet in this history. CloudFormation came from the cloud vendor: one cloud, the vendor keeps the state for you (the stack), and the template language is data (JSON, later YAML). Terraform came from a tool vendor that wanted one workflow for every API: a plugin per provider, a language designed for humans (HCL), and a state that you keep. That last choice is the source of most of this chapter: locking, remote backends, moved, import, removed, drift and secrets in state are all about taking care of that file. The 2023 license change split the tool in two: Terraform under the BSL (production use allowed, but not "offering the Licensed Work to third parties on a hosted or embedded basis in order to compete"), and OpenTofu under MPL 2.0 at the Linux Foundation, which kept the language and the provider protocol and has since added features of its own, such as state encryption. Pulumi and AWS CDK took the other road: real programming languages, with Pulumi keeping its own state service and CDK compiling ("synthesizing") to CloudFormation.
The concept catalogue
Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, how the tools differ, and the fix in this chapter's code.
IaC fundamentals: declarative, idempotent, drift, immutable infrastructure Must-know
In plain words: you write down the end result ("a private bucket called X, a queue with a dead-letter queue"), not the steps, and the tool works out the steps. Running it twice does nothing the second time. If someone changes the real thing by hand, the tool notices the difference.
Common misunderstanding: "Infrastructure as Code means scripts in Git." A Bash script that calls aws s3api create-bucket is code, but it is imperative: run it twice and the second run fails or creates a duplicate; delete a line and nothing is deleted in the cloud. Declarative IaC computes create, update and delete from the difference between the description and reality.
Definition: Declarative configuration describes the desired state; the engine plans the operations. A run is idempotent when applying the same configuration to an already matching system changes nothing ("No changes. Your infrastructure matches the configuration." in the lab). Drift is any difference between the real objects and the last recorded state that was not made by the tool (a console edit, another tool, an autoscaler). Immutable infrastructure replaces an object instead of modifying it in place: a new server image or task definition revision is created and the old one removed, so every running object is known to match a reviewed definition. The Terraform docs on provisioners say it plainly: "Terraform is primarily designed for immutable infrastructure operations".
desired (code) recorded (state) real (API) action
bucket private bucket private bucket private none (idempotent)
queue + DLQ queue queue create DLQ, update redrive
- (block deleted) old role old role delete old role
image @sha256:B task def rev 7 (A) rev 7 (A) new revision 8 (immutable), service -> 8
port 8000 port 8000 port 9999 (by hand) drift: plan restores 8000Real scenarios: a staging environment rebuilt from scratch every night proves the code is complete; an incident fix made in the console is detected by the next scheduled plan -refresh-only; a new AMI or container image is rolled out as a replacement instead of an SSH session into each host.
| Approach | Example tools | Re-run safe? | Deletes what you removed? | Drift visible? |
|---|---|---|---|---|
| Imperative scripts | Bash + AWS CLI, az, gcloud | Only if every step checks first | No | No |
| Declarative with own state | Terraform, OpenTofu, Pulumi | Yes | Yes (planned) | Yes, on refresh |
| Declarative, vendor-held state | CloudFormation (and CDK on top), Azure ARM/Bicep deployments | Yes | Yes (stack/complete mode) | CloudFormation drift detection; ARM what-if |
| Continuous reconciliation | Crossplane, Kubernetes controllers | Yes, constantly | Yes | Corrected automatically |
| Configuration management | Ansible, Chef, Puppet, Salt | Modules are idempotent, playbooks often not | Only if written | Check mode / reports |
Fix: every resource in this chapter's code is declarative; images are pinned by digest so a new release is a new task definition revision, never an in-place change; the CI workflow runs plan -detailed-exitcode so "something changed" is machine-visible.
HCL, blocks, providers and the Terraform Registry Must-know
In plain words: Terraform code is HCL, a configuration language of blocks with labels and arguments. Everything that talks to a real API is a provider, a separate program that terraform init downloads.
Common misunderstanding: "Terraform knows AWS." Terraform core knows nothing about any cloud. aws_s3_bucket is implemented in the hashicorp/aws provider (v6.74.0 here), released on its own schedule; its version, not Terraform's, decides which arguments exist.
Definition: HCL (HashiCorp Configuration Language) has blocks (resource "aws_sqs_queue" "default" { ... }: type, labels, body), arguments (name = "...") and expressions. All .tf files in a directory form one module; order of blocks and files does not matter. The terraform block declares required_version and required_providers (source address hashicorp/aws = registry.terraform.io/hashicorp/aws, a version constraint like ~> 6.0). terraform init resolves constraints, downloads providers from the Terraform Registry (OpenTofu: registry.opentofu.org), verifies signatures and records exact versions and hashes in .terraform.lock.hcl, which belongs in Git. A provider "aws" { region = ..., default_tags { ... } } block configures one instance; alias creates a second one (another region or account).
terraform init (local-lab, real run)
1 read required_providers: random ~> 3.9, local ~> 2.9, tls ~> 4.4
2 query the registry: "Finding hashicorp/local versions matching "~> 2.9"..."
3 download, verify: "Installed hashicorp/local v2.9.1 (signed by HashiCorp)"
4 write .terraform.lock.hcl (versions + hashes) and .terraform/providers/...
5 initialise the backend (local here: terraform.tfstate in the directory)
next init with the lock file present: the same versions, unless -upgradeReal scenarios: a provider major upgrade (aws v5 to v6) renames or removes arguments, so it is a reviewed PR that changes the constraint and the lock file together; a team with an internal registry mirrors providers (provider_installation in the CLI config); a CI cache keyed on the lock file avoids downloading a 100-plus-MB provider on every run (the build host's plugin cache held 788 MB after the AWS provider was added).
| Concept | Terraform | OpenTofu | Pulumi | CloudFormation |
|---|---|---|---|---|
| Language | HCL (or JSON) | HCL, same syntax | TypeScript, Python, Go, C#, Java, YAML | JSON / YAML templates |
| Plugins | Providers from registry.terraform.io | Same providers via registry.opentofu.org | Pulumi providers (many bridged from Terraform providers) | Built in; extensions via registry types / custom resources |
| Version pinning | required_providers + .terraform.lock.hcl | Same | Package manager lock file | Not needed (service-side) |
| Multiple accounts/regions | provider alias | Same, plus for_each on providers | Explicit provider objects | StackSets |
Fix: every root in The Terraform code pins required_version and provider constraints; fmt -check and validate run first in CI; the lock file is committed (lab runs show it being created).
Resources, data sources and the dependency graph Must-know
In plain words: a resource block is something Terraform creates and owns. A data block only reads something that exists. References between blocks tell Terraform the order.
Common misunderstanding: "depends_on is how you order things." Almost never: a reference (aws_subnet.private[k].id) already creates the dependency, and Terraform builds a graph and runs independent nodes in parallel (default -parallelism=10). depends_on is for hidden dependencies only, such as the NAT gateway needing the internet gateway in this chapter's network module.
Definition: a resource has a type and a name; its address is aws_db_instance.postgres, inside a module module.data.aws_db_instance.postgres, with an instance key when repeated (local_file.service_config["shop-web"], tls_private_key.service[0]). Arguments you set are inputs; computed attributes (IDs, ARNs, endpoints) are known only after apply and print as (known after apply) in a plan. A data source (data "aws_region" "current" {}, data "aws_iam_policy_document" "app") is read during plan when its arguments are known, otherwise deferred to apply. Terraform builds a graph from references and walks it: creates in dependency order, deletes in reverse.
graph for the Laravel cloud pieces (modules/laravel-app)
aws_sqs_queue.dead_letter ──▶ aws_sqs_queue.default (redrive_policy uses its arn)
aws_s3_bucket.storage ──▶ public_access_block, versioning, sse (all use bucket id)
aws_s3_bucket.storage + aws_sqs_queue.default + aws_sesv2_email_identity.domain
──▶ data.aws_iam_policy_document.app ──▶ aws_iam_role_policy.app["web"|"worker"|"scheduler"]
apply: dead_letter, storage, identity in parallel; then default queue and bucket settings;
then the policy document (needs the ARNs); then the role policies
destroy: the same graph in reverseReal scenarios: data "aws_ami" with most_recent = true changes on every plan once a new image is published, so a plan that was empty yesterday shows a replacement today; a data source that reads a resource created in the same run must wait for apply, making every attribute depending on it unknown in the plan; data "terraform_remote_state" reads another state's outputs (couples two states; prefer published outputs in SSM or a registry).
| Resource | Data source | Module output | |
|---|---|---|---|
| Creates objects | Yes | No | No (passes values) |
| In state | Yes, with all attributes | Yes, the last read result | Root outputs only |
| Read when | Refreshed every plan | Every plan (or apply if args unknown) | Evaluated with the graph |
| Typical use | aws_sqs_queue | aws_iam_policy_document, aws_region, existing VPC | module.network.vpc_id |
Fix: this chapter's modules avoid data sources that call APIs at plan time (AZs are passed in as a map), which keeps plans deterministic and lets terraform test with a mocked provider plan the whole stack.
Variables, locals, outputs, tfvars and variable precedence Must-know
In plain words: variables are a module's parameters, locals are named intermediate values, outputs are what a module hands back. .tfvars files fill in variables per environment.
Common misunderstanding: "An environment variable TF_VAR_environment overrides the tfvars file." It is the lowest priority of all value sources. The lab set TF_VAR_environment=dev, terraform.tfvars said staging and z.auto.tfvars said prod; terraform console printed "prod".
Definition: variable "x" { type, default, description, validation { condition, error_message }, sensitive, nullable, ephemeral }; types include string, number, bool, list(...), map(...), object({ a = string, b = optional(number, 1) }). locals { name_prefix = "${var.environment}-${random_pet.suffix.id}" } are referenced as local.name_prefix. output "x" { value, sensitive, description }; root outputs appear in terraform output and in state. Precedence, lowest to highest (Terraform docs, "Variable definition precedence"): environment variables TF_VAR_name; terraform.tfvars; terraform.tfvars.json; *.auto.tfvars / *.auto.tfvars.json in lexical order; -var and -var-file options in the order given on the command line, the last one winning.
real runs (13-precedence), later source wins
TF_VAR_environment=dev + terraform.tfvars (staging) + z.auto.tfvars (prod) -> "prod"
same, z.auto.tfvars deleted -> "staging"
-var-file=env/staging.tfvars -var environment=prod -> "prod"
-var environment=prod -var-file=env/staging.tfvars -> "staging"
-var environment=qa -> "Invalid value for variable ... environment must be one of dev, staging, prod."
(terraform console printed the error, then "qa", and exited 0; plan and apply stop on it)Real scenarios: CI writes images.auto.tfvars.json with the new image digests and commits it, so the release is a reviewed one-line diff; a validation block rejects environment = "qa" before any API call; optional(number, 1) gives object attributes defaults so callers can omit them (the lab's shop-web has no replicas).
| Source | Precedence | Use for | Avoid for |
|---|---|---|---|
default in the variable | Lowest | Safe defaults | Environment-specific values |
TF_VAR_name | 1 | CI secrets passed to a variable, wrappers | Anything you need to review |
terraform.tfvars | 2 | The environment's values (directory per env) | Secrets (it is in Git) |
*.auto.tfvars(.json) | 3, lexical order | Machine-written values (image digests) | Hand-edited overrides that surprise people |
-var-file, -var | 4, last wins | One-off runs, workspace setups | Routine CI (hide values from review) |
Fix: the lab's variables have types, descriptions and a validation; the AWS stack groups all per-environment sizes in one sizes object so the prod-vs-staging difference is one file; images are machine-written to images.auto.tfvars.json and validated as digests.
Repetition and expressions: for_each, count, dynamic blocks, functions Must-know
In plain words: count makes N numbered copies, for_each makes one copy per map key or set element, a dynamic block repeats a nested block. Expressions and functions compute values.
Common misunderstanding: "count and for_each are interchangeable." With count, instances are addressed by index ([0], [1]); remove the first element of a list and every later instance shifts, so Terraform plans to rewrite or replace all of them. With for_each, instances are addressed by key (["eu-central-1a"]) and removing one key touches only that instance.
Definition: count = var.enable_tls ? 1 : 0 is the idiomatic on/off switch (tls_private_key.service[0]). for_each = var.services (a map, or toset(list)) exposes each.key and each.value; keys must be known at plan time. A dynamic "subject" { for_each = ...; content { ... } } block renders zero or more nested blocks; the iterator is named after the block (subject.value). for expressions build lists and maps: { for name, svc in var.services : name => svc.port }; splat aws_subnet.private[*].id works on lists. Functions are built in (no user-defined functions in HCL; providers can ship provider-defined functions, called as provider::NAME::FUNCTION): cidrsubnet, jsonencode / jsondecode, merge, lookup, try, can, one, coalesce, templatefile, format, startswith, nonsensitive.
count vs for_each when a list loses its first element
count = length(["a","b","c"]) -> [0]=a [1]=b [2]=c
list becomes ["b","c"] -> [0] a->b (update/replace), [1] b->c, [2] destroyed
for_each = toset(["a","b","c"]) -> ["a"] ["b"] ["c"]
set becomes ["b","c"] -> ["a"] destroyed, ["b"] ["c"] untouchedReal scenarios: subnets per AZ keyed by AZ name (the network module) so adding a third AZ in prod adds two subnets and changes nothing else; security group ingress rules per client security group via dynamic "ingress"; the private route table gets a default route only when a NAT gateway exists (dynamic "route" { for_each = aws_nat_gateway.this ... }); the lab certificate's subject block is rendered only when var.cert_subject is not null.
| Construct | Addresses | Good for | Trap |
|---|---|---|---|
count | x[0], x[1] | 0/1 toggles, truly identical copies | Index shifts on list edits |
for_each (map/set) | x["key"] | Named things: AZs, services, users | Keys must be known at plan time |
dynamic block | Nested blocks inside one resource | Rules, routes, optional blocks | Overuse makes modules unreadable |
for expression | Values, not resources | Outputs, maps for for_each | Map keys must be unique |
Module for_each | module.laravel["web"] | One module per role/tenant | Moving into it needs moved |
Fix: the stack calls the ecs-service module with for_each over the three Laravel roles; switching a resource from count to for_each is done with moved { from = x[0] to = x["a"] } blocks, never with a destroy.
Lifecycle meta-arguments and why provisioners are a last resort Important
In plain words: the lifecycle block changes how Terraform replaces or protects a resource. Provisioners run scripts on a resource after it is created; avoid them.
Common misunderstanding: "ignore_changes means Terraform never touches the field." It means Terraform ignores differences for that field after creation; the value from the configuration is still used when the object is created or replaced. In the lab, local_file.motd with ignore_changes = [content] planned "No changes" for a new motd value; after the file was edited by hand (which the local provider reports as the object being gone), the next plan created it again with the new value "changed".
Definition: create_before_destroy = true reverses the default replacement order (the lab printed +/- create replacement and then destroy, then Destroying... of the "deposed object" after the new one existed); it propagates to dependencies and needs names that can coexist (name_prefix). prevent_destroy = true makes any plan that destroys the object an error ("Error: Instance cannot be destroyed ... Resource random_password.master has lifecycle.prevent_destroy set"); it cannot take a variable, and it is not recorded in state, so deleting the block deletes the protection. ignore_changes = [desired_count] (or all) suppresses diffs for fields another system owns. replace_triggered_by = [terraform_data.release] forces replacement when a referenced value changes. Custom conditions (precondition, postcondition) assert assumptions. Provisioners (local-exec, remote-exec, file) run once at create (or destroy), are not in the plan, cannot be re-run safely and leave a "tainted" resource when they fail; the docs recommend purpose-built tools instead (cloud-init/user data, image builds, configuration management, the provider's own features).
terraform apply -var release=r2 (guard/, real run, create_before_destroy on random_id.release)
1 plan: random_id.release must be replaced "+/- create replacement and then destroy"
2 random_id.release: Creating... -> new object exists
3 random_id.release (deposed object ...): Destroying... -> old one removed last
terraform destroy (random_password.master has prevent_destroy = true)
1 plan lists three destroys
2 "Error: Instance cannot be destroyed" -> nothing at all is destroyed, exit 1Real scenarios: a security group in use by a database cannot be deleted first, so create_before_destroy with name_prefix lets a changed group be swapped; ECS desired_count is owned by autoscaling, so ignore_changes = [desired_count] stops every apply from resetting it (the same problem as Helm and the HPA in Packaging for Kubernetes); a database engine minor version upgraded by AWS (auto_minor_version_upgrade) would otherwise show as a downgrade in every plan.
| Argument | Protects against | Does not protect against | Use in this chapter |
|---|---|---|---|
create_before_destroy | Downtime during replacement | Name collisions (use name_prefix) | Security groups |
prevent_destroy | A plan that destroys the object | Deleting the block; console deletes | State bucket, lab guard/ |
ignore_changes | Fighting another controller | Replacement with new values | ECS desired_count, RDS engine_version |
replace_triggered_by | Stale dependants | — | (shown in the cheat sheet) |
Provider deletion protection (deletion_protection) | Any delete via the API | Someone turning it off first | RDS in prod |
| Provisioners | — | — | None, on purpose |
Fix: the data-stores module sets RDS deletion_protection from the environment (prod on), uses ignore_changes for the engine version and create_before_destroy for security groups; the CI workflow's planguard step blocks plans that delete or replace protected types even when someone removed prevent_destroy.
The core workflow: init, validate, fmt, plan, apply, destroy; plan files, -target, -replace Must-know
In plain words: init once per checkout, plan to see the change, apply to make it. Save the plan to a file and apply that file, so what you reviewed is what runs.
Common misunderstanding: "terraform apply applies the plan I looked at a minute ago." Without a plan file, apply makes a new plan; if anything changed in between (another merge, a console edit), it may do something else. The lab's unsaved plans end with "Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions". A saved plan is refused if the state moved on: "Error: Saved plan is stale ... the state was changed by another operation after the plan was created."
Definition: terraform init (providers, modules, backend; -upgrade, -backend=false, -reconfigure, -migrate-state); terraform fmt (canonical style; -check -recursive -diff in CI); terraform validate (syntax, types, references; no remote calls; needs init); terraform plan (refresh, diff; -out=FILE, -detailed-exitcode: 0 no changes, 1 error, 2 changes; -var, -var-file, -lock-timeout, -parallelism, -refresh=false, -destroy); terraform apply [FILE] (with a file: no prompt, exactly that plan; without: plan + prompt, -auto-approve); terraform destroy (= apply -destroy). -replace=ADDR plans a destroy-and-create of one instance (it replaced terraform taint, which is deprecated). -target=ADDR limits the plan to one resource and its dependencies; Terraform warns "Resource targeting is in effect" and the docs reserve it for "exceptional circumstances".
lab 07-replace, real runs
plan -replace=random_password.db -> "random_password.db will be replaced, as requested"
local_sensitive_file.db_password must be replaced (its content)
Plan: 2 to add, 0 to change, 2 to destroy.
plan -target='local_file.service_config["orders-api"]' -var environment=staging
-> only that file and its dependency random_pet.suffix,
"Warning: Resource targeting is in effect"
plan -out=stale.tfplan; another apply changes state; apply stale.tfplan
-> "Error: Saved plan is stale", exit 1Real scenarios: CI saves the plan on main, uploads it as an artefact and applies exactly that file after an approval; -replace rotates a password or reboots a broken instance without editing code; -target gets you out of a dependency deadlock once, and then a normal plan must be clean.
| Command / flag | Use it when | Never |
|---|---|---|
plan -out=tfplan + apply tfplan | Always in automation | Commit plan files (they contain values) |
plan -detailed-exitcode | CI needs "changes or not" | Treat exit 2 as failure blindly |
apply -auto-approve | Throwaway environments, labs | Production without a reviewed plan |
-replace=ADDR | Forced recreation of one object | As a habit instead of fixing drift |
-target=ADDR | Recovery from an error | Routine partial deploys |
-lock-timeout=5m | Shared state in CI | -lock=false |
destroy | Ephemeral environments | Shared prod states (use removed / code deletes) |
Fix: the CI workflow plans with -out, guards the plan JSON, uploads it as an artefact and applies only that file inside a protected environment; the lab shows each flag's real output.
State: what terraform.tfstate stores, and secrets in state Must-know
In plain words: the state file is Terraform's memory: which real object belongs to which block, and what it looked like last time. Lose it and Terraform forgets it created anything; leak it and you leak every secret Terraform ever saw.
Common misunderstanding: "State is a cache; Terraform could just look at the cloud." The docs answer this directly: "State is a necessary requirement for Terraform to function", because "Terraform requires some sort of database to map Terraform config to the real world". Tags and names are not unique identities, many APIs cannot be searched, and deletes are only possible for objects Terraform knows it owns.
Definition: terraform.tfstate is JSON. Its top-level keys in the lab were check_results lineage outputs resources serial terraform_version version. lineage is a UUID fixed when the state is created (two states with different lineages are different histories); serial increments on every write (a write with an older serial is rejected by remote backends); resources lists every resource with mode (managed or data), type, name, provider, and per instance the attributes (every argument and computed value), sensitive_attributes, dependencies and the schema_version. Root outputs store values and a sensitive flag. Sensitive values are stored in plain text. The docs: "Terraform stores your state in a plaintext file, which includes any secret values you defined in your configuration." The lab's state held the password in outputs.db_password.value, resources.2.instances.0.attributes.content (the file) and resources.3.instances.0.attributes.result, and the TLS key resource held private_key_openssh private_key_pem private_key_pem_pkcs8.
what happens to state during one apply (local backend, real behaviour)
1 lock: .terraform.tfstate.lock.info written (ID, Operation: OperationTypeApply, Who, Version)
2 read terraform.tfstate (serial N)
3 refresh + diff + apply resource by resource; state is persisted as objects complete
4 write terraform.tfstate with serial N+1; previous copy kept as terraform.tfstate.backup
(state mv / rm also leave terraform.tfstate.<timestamp>.backup files)
5 unlock: lock file removedReal scenarios: a terraform.tfstate committed to a public repository exposes database passwords and private keys (the reason .gitignore files ship *.tfstate*); two engineers apply from laptops with local state and create every resource twice; a corrupted state is recovered from the S3 bucket's previous object version (why versioning on the state bucket is mandatory).
| Field | Meaning | Why you care |
|---|---|---|
version | State format version (4) | Old Terraform cannot read newer formats |
terraform_version | Version that last wrote it | Upgrading is one-way for a team |
serial | Write counter | Stale plans and stale writers are refused |
lineage | Identity of this state's history | Prevents pushing state from another project |
resources[].instances[].attributes | Every attribute, secrets included | Treat the whole file as a secret |
resources[].instances[].dependencies | Recorded dependencies | Correct destroy order after code is gone |
outputs | Root outputs, values in clear | Readable by anyone who can read state (terraform_remote_state) |
check_results | Results of check blocks and conditions | Continuous validation reporting |
Fix: remote state in a versioned, encrypted, private bucket that only the CI roles can read; secrets kept out of state where the provider allows it (RDS-managed master password, write-only arguments, ephemeral values; see Secrets); OpenTofu users can add client-side state encryption (OpenTofu).
Remote backends and state locking: S3, DynamoDB lock, use_lockfile, GCS, azurerm, HCP Terraform Must-know
In plain words: a backend is where state lives. A remote backend puts it in shared storage and adds a lock, so only one run at a time can change it.
Common misunderstanding: "S3 state needs a DynamoDB table for locking." Not any more: since Terraform 1.11.0 "S3 native state locking is now generally available. The use_lockfile argument enables users to adopt the S3-native mechanism", and the DynamoDB arguments are deprecated. The lock is an object next to the state (<key>.tflock) written with a conditional request.
Definition: the backend block inside terraform {} configures one backend per root module (no variables allowed; use -backend-config for partial configuration). The S3 backend docs: "Stores the state as a given key in a given bucket on Amazon S3. This backend also supports state locking which can be enabled by setting the use_lockfile argument to true", and "It is highly recommended that you enable Bucket Versioning on the S3 bucket to allow for state recovery". With use_lockfile, IAM needs s3:GetObject, s3:PutObject and s3:DeleteObject on the .tflock key. The deprecated dynamodb_table is "the DynamoDB Table to use for state locking and consistency. The table must have a partition key named LockID with a type of String." The gcs backend locks natively; azurerm uses blob leases; HCP Terraform (the cloud block) stores state per workspace, queues runs and locks the workspace. Locking itself: "State locking happens automatically on all operations that could write state. ... If state locking fails, Terraform does not continue." A crashed run leaves the lock behind: terraform force-unlock LOCK_ID.
lab 08-lock, real: an apply sits at its approval prompt, a second run plans
holder: terraform apply -var environment=staging (plan done, "Enter a value:" waiting)
.terraform.tfstate.lock.info: Operation: OperationTypeApply, Who: <redacted>, Version: 1.17.2
second: terraform plan -lock-timeout=3s
Acquiring state lock. This may take a few moments...
Error: Error acquiring the state lock
Error message: resource temporarily unavailable
Lock Info: ID: <uuid> Path: terraform.tfstate Operation: OperationTypeApply ...
[exit 1]
holder: stdin closed -> "Error: error asking for approval: EOF", lock releasedReal scenarios: two CI pipelines for the same environment start at once; the second waits (-lock-timeout=5m) instead of failing; an engineer's laptop dies mid-apply and the lock stays until someone checks the run is really gone and force-unlocks; staging and prod use different keys (and ideally different buckets and accounts), so a broken staging lock never blocks prod.
| Backend | Lock mechanism | Recovery of old state | Who can read secrets |
|---|---|---|---|
local | OS file lock + .lock.info | terraform.tfstate.backup | Anyone with the laptop |
s3 + use_lockfile | .tflock object, conditional write | Bucket versioning | IAM s3:GetObject on the key |
s3 + dynamodb_table (deprecated) | Item keyed LockID | Bucket versioning | Same, plus the table |
gcs | Lock object | Object versioning | IAM on the bucket |
azurerm | Blob lease | Blob versioning / snapshots | Storage account RBAC / keys |
| HCP Terraform | Workspace lock and run queue | State versions in the UI/API | Workspace permissions |
Fix: the bootstrap root creates the state bucket (versioning, KMS encryption, public access blocked, prevent_destroy) and the CI roles; each environment's backend.tf uses use_lockfile = true and its own key.
Refactoring state: terraform state mv, terraform state rm, import block, moved block, removed block Important
In plain words: sometimes the code changes but the real objects should not: a rename, a move into a module, adopting something built by hand, or handing something over to another state. Blocks in code do this as part of a reviewed plan; the state commands do it immediately.
Common misunderstanding: "terraform state mv is the normal way to rename." It edits state at once, outside any plan or review, per working directory and per environment, and it is easy to get wrong. The lab ran the rename both ways: with a moved block the plan said local_file.service_config["orders-api"] has moved to local_file.service["orders-api"] and Plan: 0 to add, 0 to change, 0 to destroy.; with terraform state mv local_file.service local_file.svc and no matching code, the next plan wanted to destroy and recreate.
Definition: a moved block (Terraform 1.1+) records from and to addresses (resources, instances, whole modules); planning moves the state entry first, shows "has moved to", and the block can stay in a module so every consumer's state is migrated. An import block (1.5+) declares to = ADDRESS and id = "provider-specific ID"; plan shows "will be imported" ("Plan: 1 to import, 0 to add, ..."), apply adopts it, and terraform plan -generate-config-out=generated.tf writes a starting configuration for imported objects without one; since 1.6 id accepts expressions, and since 1.7 for_each is allowed on import blocks. A removed block (1.7+) with lifecycle { destroy = false } drops the object from state without destroying it; the lab's plan said "random_integer.debug_port will no longer be managed by Terraform, but will not be destroyed (destroy = false is set in the configuration)" and its JSON action is forget. The CLI equivalents: terraform state mv SRC DST, terraform import ADDR ID ("Importing from ID ... Import prepared!"), terraform state rm ADDR.
lab 10-import / 11-removed, real
import.tf: resource random_integer.debug_port {min=9000 max=9099}; import { id = "9042,9000,9099" }
plan -> random_integer.debug_port: Preparing import... [id=9042,9000,9099]
# random_integer.debug_port will be imported
Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.
apply -> Apply complete! Resources: 1 imported, 0 added, 0 changed, 0 destroyed.
removed { from = random_integer.debug_port lifecycle { destroy = false } }
plan -> will no longer be managed by Terraform, but will not be destroyed
Warning: Some objects will no longer be managed by Terraform
apply -> object gone from `terraform state list`, still "exists" outside TerraformReal scenarios: splitting a monolithic root into network and app states (removed with destroy = false in one, import blocks in the other); converting count to for_each with one moved block per instance; adopting a bucket created by hand during an outage; a module author renames a resource and ships the moved block in the same release, so consumers upgrade without replacements.
| Need | Block (reviewed, planned) | Command (immediate) | Since |
|---|---|---|---|
| Rename / move into module | moved | terraform state mv | 1.1 |
| Adopt existing object | import (+ -generate-config-out) | terraform import | 1.5 |
| Stop managing, keep object | removed + destroy = false | terraform state rm | 1.7 |
| Recreate one object | — | plan/apply -replace=ADDR | 0.15.2 |
| Look at state | — | terraform state list / show, terraform show -json | — |
Fix: this chapter's refactors are all blocks in The Terraform code (steps/10-moved.tf, 20-import.tf, 30-removed.tf), and the planguard Go program reports moves and imports separately so a reviewer sees "moved=2" instead of a wall of no-ops.
Drift and drift detection: plan -refresh-only Important
In plain words: drift is reality changing behind Terraform's back. terraform plan -refresh-only shows what changed without proposing to undo it; a normal plan proposes to put things back.
Common misunderstanding: "terraform refresh is harmless." The old terraform refresh command writes the refreshed values into state without showing you anything first; it is deprecated in favour of terraform apply -refresh-only, which shows the changes and asks. Also: drift is not always wrong. An autoscaler changing desired_count is expected; the fix is ignore_changes, not a revert every night.
Definition: during every plan, Terraform first refreshes: it asks the provider to read each object in state. -refresh-only produces a plan whose only actions are updates to state ("Note: Objects have changed outside of Terraform"), apply -refresh-only accepts them, a plain plan + apply restores the configuration. A resource whose object has vanished is dropped from state on refresh ("has been deleted") and planned for creation. Drift detection in practice is a scheduled CI job running plan -detailed-exitcode (exit 2 = changes) or -refresh-only, or HCP Terraform health assessments.
lab 06-drift, real: out/shop-web.json overwritten by hand
plan -refresh-only -> # local_file.service_config["shop-web"] has been deleted (content no longer matches)
"This is a refresh-only plan, so Terraform will not take any actions to undo these."
plan -> # local_file.service_config["shop-web"] will be created
Plan: 1 to add, 0 to change, 0 to destroy.
apply -> file rewritten; next plan -detailed-exitcode: No changes, exit 0
first version of this chapter's outputs.tf (indexed the resource by var.services keys):
plan -refresh-only -> "Error: Invalid index ... local_file.service_config is object with 1 attribute
"orders-api"" -> outputs now iterate over the resource itselfReal scenarios: a security group rule opened during an incident and never closed shows up in the nightly drift job; RDS minor version upgrades by AWS appear as drift on engine_version (handled with ignore_changes); a Kubernetes namespace deleted by someone shows "has been deleted" and is recreated by the next apply.
| Tool | Drift detection | What it does with drift |
|---|---|---|
| Terraform / OpenTofu | Refresh on every plan; plan -refresh-only; scheduled CI | Shows it; plain apply reverts, apply -refresh-only accepts |
| HCP Terraform | Health assessments (drift detection) per workspace | Notifies; you run plans |
| Pulumi | pulumi refresh, pulumi preview --refresh | Updates state from the cloud |
| CloudFormation | DetectStackDrift, status IN_SYNC / DRIFTED | Reports per resource; you fix or re-import |
| Crossplane / Argo CD / Flux | Continuous reconciliation | Reverts automatically (self-heal) |
Fix: the outputs iterate over the resource map (fix found by the lab's first run), ECS desired counts and engine versions are ignored on purpose, and the scheduled drift job is the same plan -detailed-exitcode the PR job runs.
Modules: root module, module source, module version, module composition Must-know
In plain words: a module is a folder of Terraform code with inputs and outputs. The folder you run Terraform in is the root module; it calls child modules, which can call others.
Common misunderstanding: "A good module wraps a whole environment, configurable with flags." That is the one-module-to-rule-them-all anti-pattern: a hundred variables, count = var.enable_x ? 1 : 0 everywhere, every change touching every environment's plan. The Terraform docs on composition recommend the opposite: keep modules small and flat, and let the root "compose" them by passing outputs into inputs.
Definition: module "network" { source = "../../modules/network", ...inputs }; source can be a local path (./ or ../), the Terraform Registry (terraform-aws-modules/vpc/aws with version = "~> 6.0"; version only works for registry sources), a Git URL (git::https://github.com/acme/tf-modules.git//network?ref=v1.4.0), an HTTP archive, S3 or GCS. Outputs are read as module.network.vpc_id; for_each and count work on module calls (module.laravel["web"]), and providers = { aws = aws.eu } passes aliased providers. Composition patterns from the docs: dependency inversion (the caller creates shared things and passes them in), data-only modules (look things up), and multi-cloud abstraction with care.
how this chapter's stack composes (stacks/shop)
envs/prod ──calls──▶ stacks/shop (environment, azs, sizes, images)
stacks/shop ──▶ module.network -> vpc_id, private_subnet_ids
──▶ aws_security_group.app["orders-api"|"laravel"] (dependency inversion)
──▶ module.data(vpc, subnets, client SGs) -> postgres_endpoint, secret ARN, redis_endpoint
──▶ module.orders_api, module.laravel["web"|"worker"|"scheduler"] (endpoints, SGs)
──▶ module.laravel_cloud(task role names) -> bucket, queue prefix/name, DKIM tokens
first version (SGs inside ecs-service): "Error: Cycle: module.laravel ... module.data ..." (real)Real scenarios: the community VPC module (terraform-aws-modules/vpc/aws) gives subnets, NAT and flow logs in a few lines, at the price of a large input surface you must read; a platform team publishes versioned modules in a private registry and app teams pin version = "~> 2.3"; a module upgrade that renames a resource ships moved blocks so nobody's database is replaced.
| Source | Example | Versioning | Good for |
|---|---|---|---|
| Local path | ../../modules/network | With the repository | Mono-repo, early stage |
| Terraform Registry | terraform-aws-modules/vpc/aws, version = "~> 6.0" | SemVer constraint | Well-known building blocks |
| Private registry (HCP Terraform, others) | app.terraform.io/acme/network/aws | SemVer | Platform team modules |
| Git | git::https://...//network?ref=v1.4.0 | Tag or commit | Simple sharing without a registry |
| S3 / GCS / HTTP | s3::https://...module.zip | Object path | Air-gapped, artefact stores |
| Anti-pattern | Symptom | Better |
|---|---|---|
| One module to rule them all | 100+ variables, feature flags | Small modules, composed in a stack |
Module per resource (aws_s3_bucket wrapper) | Indirection without abstraction | Module per purpose (laravel-app) |
| Providers configured inside child modules | Cannot delete the module, cannot for_each it | Providers only in the root |
terraform_remote_state everywhere | Tight coupling between states | Outputs published in SSM, or one owner per value |
| Copy-pasted modules per environment | Drift between environments | One module, inputs per environment |
Fix: four small modules (network, data-stores, ecs-service, laravel-app), one composition module (stacks/shop) and thin roots per environment; the security groups moved into the stack after the real cycle error, which is the dependency-inversion pattern from the composition docs.
Environments: directory per environment, workspaces, tfvars, Terragrunt Important
In plain words: staging and prod should be separate states with separate credentials. The usual layout is a directory per environment that calls shared modules; CLI workspaces are a lighter tool for throwaway copies of the same thing.
Common misunderstanding: "Workspaces are how Terraform does environments." The Terraform docs: "Workspaces are not appropriate for system decomposition or deployments requiring separate credentials and access controls." All workspaces of a working directory share one backend configuration and the same credentials, and a terraform workspace select prod in the wrong terminal applies prod.
Definition: a workspace is another named state for the same configuration and backend (terraform workspace new staging; local state goes to terraform.tfstate.d/staging/, S3 uses a workspace_key_prefix); terraform.workspace returns the name inside expressions. A directory per environment (envs/staging, envs/prod) gives each environment its own root module, backend key, terraform.tfvars, provider configuration (allowed_account_ids) and CI job, at the cost of a few lines of duplicated wiring. Terragrunt (Gruntwork) is a wrapper that generates backend and provider blocks from one root.hcl, expresses dependencies between units (dependency "vpc" { config_path = "../vpc" }, mock_outputs) and runs many units at once (terragrunt run --all plan).
lab 12-workspaces, real
terraform workspace new staging -> Created and switched to workspace "staging"! ... a new, empty workspace
terraform workspace list -> default / * staging
echo terraform.workspace | terraform console -> "staging"
terraform plan -var-file=env/staging.tfvars -> Plan: 8 to add (the default workspace's objects are invisible)
terraform workspace select default; terraform workspace delete staging
note: both workspaces would write out/*.json: same paths, same names -> collisions are your problemReal scenarios: feature-branch environments (pr-123) as workspaces of a small stack, destroyed on merge; prod in a separate AWS account with its own state bucket and its own CI role; a platform with forty services per environment managed with Terragrunt units so that run --all plan shows every change.
| Layout | Isolation | Duplication | Best for |
|---|---|---|---|
| CLI workspaces | Same backend, same credentials | None | Ephemeral copies, PR environments |
| Directory per environment | Separate root, key, credentials, CI job | Thin root per env | Most teams, staging/prod |
| Separate repositories / accounts | Strongest | More | Regulated prod, many teams |
| Terragrunt | Per unit; generated backends | Lowest | Many units x many environments |
| HCP Terraform workspaces | Per workspace variables, permissions | None | Teams on HCP Terraform (not the same as CLI workspaces) |
Fix: aws/envs/staging and aws/envs/prod are separate roots with separate keys and allowed_account_ids; the lab uses a CLI workspace only to show the mechanics.
Testing and policy: terraform test, terraform fmt, validate, tflint, Checkov, Trivy, OPA, Sentinel Important
In plain words: check formatting and syntax first, then lint for provider-specific mistakes, then scan for insecure settings, then test that the module does what it promises, then let a policy decide whether the plan may be applied.
Common misunderstanding: "You cannot test Terraform without a cloud account." Since Terraform 1.7, mock_provider "can replace provider instances with mocked providers, allowing tests to execute in command = apply mode without requiring a configured cloud provider account and credentials." This chapter's AWS modules are tested that way: 6 runs, all pass, no credentials (with two real lessons, below).
Definition: terraform fmt -check -recursive (style), terraform validate (types, references). terraform test (GA in 1.6) runs *.tftest.hcl files: variables {} at file or run level, run "name" { command = plan|apply, assert { condition, error_message }, expect_failures = [var.environment] }; runs execute in order with their own state and are destroyed afterwards; mock_provider, override_resource, override_data, mock_data fake providers. tflint ("A Pluggable Terraform Linter") catches provider-specific errors such as invalid instance types, with rule plugins per cloud. Checkov is "a static code analysis tool for infrastructure as code" with "Over 1000 built-in policies", scanning HCL or plan JSON. Trivy (trivy config) scans Terraform code and plans for misconfigurations. OPA (Open Policy Agent) evaluates Rego policies against terraform show -json output, usually through conftest. Sentinel is HashiCorp's policy-as-code language enforced in HCP Terraform / Terraform Enterprise between plan and apply.
real runs on the build host
local-lab: terraform test -> 5 runs: staging_keeps_replicas, dev_runs_one_replica,
rejects_unknown_environment, tls_off_means_no_key, apply_writes_files
"Success! 5 passed, 0 failed." (same file under tofu test: 5 passed)
laravel-app: terraform test -> mocked AWS, 3 passed
stacks/shop: terraform test -> mocked AWS, plans the whole stack, 3 passed (incl. expect_failures on var.images)
first mocked run: "assume_role_policy" contains an invalid JSON policy: not a JSON object
-> mocks fill computed strings with random values; mock_data "aws_iam_policy_document" { defaults = { json = ... } }
mocked dkim_signing_attributes stayed an empty list -> output uses one(...[*].tokens) instead of [0]Real scenarios: a PR that opens a bucket to the public fails on Checkov/Trivy before review; a module refactor is protected by terraform test runs asserting outputs; a Sentinel or OPA policy blocks plans that delete RDS instances or create untagged resources.
| Layer | Tool | Needs init? | Needs cloud? | Catches |
|---|---|---|---|---|
| Style | terraform fmt -check | No | No | Formatting |
| Static | terraform validate | Yes | No | Types, references, required args |
| Lint | tflint (+ ruleset plugin) | No | No (optional deep check) | Invalid values, deprecated syntax, unused declarations |
| Security scan | Checkov, Trivy (trivy config) | No | No | Public buckets, unencrypted storage, wide security groups |
| Unit/integration | terraform test (+ mock_provider) | Yes | No with mocks; yes for real apply | Module behaviour, outputs, validations |
| Plan policy | OPA/conftest on plan JSON, Sentinel in HCP Terraform, this chapter's planguard | Plan | Yes (real plan) | Deletes of protected types, cost, tags |
Fix: the CI checks job runs fmt -check and the mocked tests on every PR; the plan job runs planguard on the plan JSON; tflint, Checkov and Trivy steps are listed in the Lab as "expected, not run" (no binaries on the build host).
CI for infrastructure: plan on PR, apply on merge, OIDC, plan artifact, concurrency Must-know
In plain words: every pull request shows the plan as a comment; merging applies it. CI gets short-lived cloud credentials from OIDC, not stored keys, and only one apply per environment runs at a time.
Common misunderstanding: "Apply the plan from the PR after merge." The PR's plan was made against the PR branch and the state of that moment; after merge, main may contain other changes and the state may have moved on. Either re-plan on main and apply that saved plan (this chapter), or apply before merge from the PR with a lock (the Atlantis model). A saved plan that no longer matches the state is refused ("Saved plan is stale").
Definition: plan on PR: init, validate, plan -out=tfplan -detailed-exitcode, convert with terraform show -json, guard, post a comment. Apply on merge: plan on main, upload the plan artifact (actions/upload-artifact@v7), then a job bound to a GitHub environment (required reviewers for prod) downloads it (actions/download-artifact@v8) and runs terraform apply tfplan. OIDC: the job requests id-token: write; aws-actions/configure-aws-credentials@v6 exchanges GitHub's token for a role session; the IAM role's trust policy checks token.actions.githubusercontent.com:aud = sts.amazonaws.com and :sub (repo:ORG/REPO:pull_request and, for the plan-on-main job, repo:ORG/REPO:ref:refs/heads/main for the read-only plan role; repo:ORG/REPO:environment:prod for the apply role, because a job bound to an environment gets the environment in its subject). Concurrency: GitHub Actions concurrency groups per environment with cancel-in-progress: false for applies, plus the backend lock as the last line of defence. Plan files contain values from state and must be treated as secrets (short retention).
lifecycle of one change (ci/terraform.yml)
1 PR opened: checks (fmt, mocked tests) -> plan staging + plan prod (plan role, read-only)
2 planguard summary + full plan posted as a PR comment; reviewers read the diff AND the plan
3 merge: plan-main per env (plan role) -> tfplan uploaded as artifact tfplan-<env>
4 apply staging (environment staging): download tfplan, terraform apply tfplan
5 apply prod waits for a required reviewer; then apply tfplan, or "Saved plan is stale" -> re-runReal scenarios: a PR comment shows replace=1 on the production database and the reviewer stops it; an expired static access key in CI is replaced by OIDC roles that cannot be leaked; two merges in a row queue their applies instead of fighting over the lock.
| Option | Plan where | Apply where | Notes |
|---|---|---|---|
| GitHub Actions (this chapter) | PR job | Environment-protected job after merge | Plan artifact, OIDC, concurrency groups |
| GitLab CI | MR pipeline (terraform plan, MR widget via terraform show -json report) | Manual or protected job on the default branch | GitLab can host state over HTTP backend |
| Atlantis | atlantis plan comment on PR | atlantis apply before merge, PR lock | Apply-before-merge model |
| HCP Terraform | Speculative plan on PR (VCS-driven) | Run on merge with policy checks | Remote execution, Sentinel/OPA |
| Jenkins / others | Pipeline stage | Input step | Same commands; you build the guard rails |
Fix: ci/terraform.yml implements the GitHub Actions column; the pipeline concepts (runners, environments, OIDC) are explained in depth in CI/CD Pipelines.
Secrets: sensitive, ephemeral, write-only arguments, the Vault provider Important
In plain words: sensitive hides a value on screen. Keeping it out of the state file needs either a value that is never stored (ephemeral, write-only) or a design where Terraform never sees the secret at all.
Common misunderstanding: "Mark the output sensitive and the Go service can safely read it from terraform output -json." The docs: "When using the -json or -raw command-line flags, Terraform displays sensitive values in plain text." The lab's output -json printed "sensitive": true next to the clear-text password; this chapter's Go tfoutputs.Secret type therefore redacts itself in every print path and refuses a secret output that is not marked sensitive.
Definition: sensitive = true on variables and outputs (and provider-marked attributes) replaces values with (sensitive value) in plans and <sensitive> in terraform output; it propagates through expressions (OpenTofu rejected an output of length(random_password.db.result) until it was wrapped in nonsensitive()). Ephemeral (Terraform 1.10+): ephemeral "type" "name" {} resources "are read anew during each phase of Terraform evaluation, and cannot be persisted to state storage"; variables and outputs can be ephemeral = true and "are not persisted to the plan or state files". Write-only arguments (1.11+, provider support required), such as password_wo with password_wo_version on aws_db_instance, accept ephemeral values and are "not persisted in state". The Vault provider (hashicorp/vault) reads and writes Vault secrets; read through data sources they land in state, through ephemeral resources they do not. Often the best design is for Terraform to create the place (an RDS-managed secret, a Secrets Manager ARN) and for the runtime to read the value: ECS secrets with valueFrom an ARN, External Secrets in Kubernetes.
where the database password lives in this chapter's AWS stack
1 aws_db_instance.postgres: manage_master_user_password = true -> RDS creates the secret in Secrets Manager
2 Terraform state: only master_user_secret[0].secret_arn (an ARN, not the password)
3 ecs-service: secrets = { DATABASE_SECRET_JSON = <ARN> } -> task definition "valueFrom"
4 ECS agent (execution role, secretsmanager:GetSecretValue) injects the value at container start
5 the Go service / Laravel reads an env var; Terraform never saw the passwordReal scenarios: a provider API key passed as TF_VAR_ stays out of state if the variable is only used in a provider block; a random password generated by random_password for a legacy database is in state forever (rotate it by -replace, and lock down the state); a short-lived database credential from Vault is fetched by an ephemeral resource just for the provider configuration.
| Technique | Hidden in output | Kept out of plan file | Kept out of state | Requires |
|---|---|---|---|---|
sensitive = true | Yes | No | No | Any version |
random_password | Yes (marked) | No | No | — |
| Ephemeral variable/output | Yes | Yes | Yes | Terraform 1.10+ |
| Ephemeral resource (e.g. Vault, Secrets Manager reads) | Yes | Yes | Yes | 1.10+ and provider support |
Write-only argument (password_wo) | Yes | Yes | Yes | 1.11+ and provider support |
Service-managed secret (RDS manage_master_user_password) | n/a | Yes | Yes (only the ARN) | Service feature |
| OpenTofu state encryption | No | Encrypted | Encrypted, not absent | OpenTofu 1.7+ |
Fix: RDS manages its own password, ECS injects it by ARN, nothing secret is an input variable; the lab keeps random_password precisely to show what lands in state.
Licensing and OpenTofu: the BSL license change and what differs Good to know
In plain words: in 2023 Terraform's license changed from open source (MPL 2.0) to the Business Source License. The community forked the last open version as OpenTofu, now a Linux Foundation project. Both read the same HCL and use the same providers; they are slowly growing apart.
Common misunderstanding: "The BSL forbids using Terraform in production." The additional use grant in the LICENSE allows production use "provided Your use does not include offering the Licensed Work to third parties on a hosted or embedded basis in order to compete with IBM Corp.'s paid version(s)". It matters for vendors building Terraform-as-a-service products, and for organisations whose policy requires OSI-approved licenses.
Definition: Terraform 1.6.0 and later are BSL 1.1 (the LICENSE: "Licensed Work: Terraform Version 1.6.0 or later"); 1.5.x and earlier remain MPL 2.0. OpenTofu forked from the MPL code, ships tofu with the same commands, reads .tf files and Terraform state, and installs providers from registry.opentofu.org (the same hashicorp/* providers, signed: "Installed hashicorp/random v3.9.1 (signed, key ID 0C0AF313E5FD9F80)" in the lab). Differences that exist today and were verified here: client-side state and plan encryption (terraform { encryption { key_provider "pbkdf2" ... method "aes_gcm" ... state { enforced = true } } }, OpenTofu 1.7+), with key providers for PBKDF2 passphrases, AWS KMS, GCP KMS, Azure Key Vault and OpenBao; the -exclude flag and -target-file / -exclude-file options (1.10). Some features arrived in both, separately: removed blocks and for_each on import blocks are in Terraform 1.7 and OpenTofu 1.7. Features on Terraform's side that OpenTofu implements differently or not at all include HCP Terraform integration (cloud block) and Terraform's newest language additions; check both changelogs before relying on one.
lab 17-tofu, real (OpenTofu v1.13.10, TF_VAR_state_passphrase set for the lab only)
tofu apply -> Apply complete! Resources: 1 added ... password_length = 24
jq keys terraform.tfstate -> encrypted_data encryption_version lineage meta serial
grep -c random_password terraform.tfstate -> 0 (resource names are encrypted too)
tofu state list -> random_password.db
terraform init (same dir) -> Error: Unsupported block type ... Blocks of type "encryption" are not expected here.
tofu plan, wrong passphrase-> Error acquiring the state lock ... decryption failed for all provided methods
... cipher: message authentication failed
first try: output length(random_password.db.result) -> "Error: Output refers to sensitive values"
-> nonsensitive(length(...))Real scenarios: a company with an OSI-only policy standardises on OpenTofu and keeps the same modules; a team that must not have readable secrets in its state bucket uses OpenTofu encryption with AWS KMS; a vendor of a hosted IaC platform cannot embed Terraform 1.6+.
| Terraform 1.17 | OpenTofu 1.13 | |
|---|---|---|
| License | BSL 1.1 (since 1.6.0) | MPL 2.0, Linux Foundation |
| Binary / CLI | terraform | tofu (same subcommands) |
| Registry | registry.terraform.io | registry.opentofu.org (mirrors the providers) |
| State format | v4 JSON | Same, or encrypted (encrypted_data) |
| State encryption | No (backend-side only) | Yes, client-side, AES-GCM, PBKDF2/KMS key providers |
| Testing | terraform test, mock_provider | tofu test, same file format (the lab's 5 runs passed under both) |
| Partial runs | -target | -target, -exclude, -target-file, -exclude-file |
| Managed service | HCP Terraform | Third parties (Harness, Spacelift, env0, Scalr and others backed the Linux Foundation launch) |
Fix: this chapter's HCL runs under both binaries (the lab ran init, plan and test with tofu too); the only OpenTofu-only root is tofu-encryption/, labelled as such.
The alternatives: Pulumi, AWS CDK, CloudFormation, Bicep and ARM, Crossplane, Ansible Important
In plain words: Pulumi and CDK let you write infrastructure in TypeScript, Python, Go or C#. CloudFormation and Bicep are the clouds' own declarative formats, where the cloud keeps the state. Crossplane runs IaC as Kubernetes controllers. Ansible configures servers and can also call cloud APIs, but has no state.
Common misunderstanding: "Pulumi has no state because it is code." It does: "Pulumi Cloud is the default backend", and the "DIY backend" stores state in S3, Azure Blob Storage, Google Cloud Storage, PostgreSQL or the local filesystem. The program describes desired state; the engine diffs it against the stored state exactly like Terraform.
Definition: Pulumi: programs in general-purpose languages declare resources (sqs.NewQueue(ctx, "default", ...) in Go); pulumi preview is the plan, pulumi up the apply, pulumi refresh the drift read; state per stack (dev, prod) in Pulumi Cloud or a DIY backend; many providers are bridged from Terraform providers. AWS CDK: constructs in TypeScript, Python, Java, C#, Go; cdk synth (cdk synthesize) produces "a cloud assembly, including an AWS CloudFormation template for each stack"; cdk diff, cdk deploy hand the template to CloudFormation. CloudFormation: "A stack is a collection of AWS resources that you can manage as a single unit"; AWS holds the state; a change set lets you "preview how proposed changes to a stack might impact your running resources" and executes only when you decide; CloudFormation drift detection compares stack resources with their template (status IN_SYNC, MODIFIED, DELETED per resource, stack DRIFTED); failed updates roll back automatically. Bicep: "a domain-specific language that uses declarative syntax to deploy Azure resources", compiled to ARM templates (JSON) and deployed by Azure Resource Manager, with what-if as the preview. Crossplane: "a control plane framework for platform engineering": cloud resources as Kubernetes custom resources, continuously reconciled, composed into higher-level APIs with Compositions; this section is a Crossplane preview only; the GitOps chapter covers it. Ansible: agentless, SSH-based configuration management with playbooks; cloud modules exist, but there is no state and no plan, so deletes and drift are your code's job; the Ansible comparison in depth is in the Ansible chapter.
the same SQS queue + DLQ, as each tool sees it
Terraform aws_sqs_queue.default { redrive_policy = jsonencode(...) } plan -> apply, state in S3
Pulumi (Go) sqs.NewQueue(ctx, "default", &sqs.QueueArgs{RedrivePolicy: ...}) preview -> up, state in Pulumi Cloud/S3
AWS CDK new sqs.Queue(this, 'Default', { deadLetterQueue: { queue: dlq, maxReceiveCount: 5 } }) (QueueProps)
cdk synth -> CloudFormation template -> change set -> stack update
Bicep not applicable (Azure): the Azure equivalent is a Service Bus queue resource
Crossplane a Queue managed resource of the AWS provider, in Git -> Argo CD applies -> reconciled forever
Ansible community.aws.sqs_queue: name=..., redrive_policy=... ; re-run safe, but no plan and no stateReal scenarios: a TypeScript team on AWS only chooses CDK for its high-level constructs and CloudFormation's managed state and rollbacks; a multi-cloud platform team keeps Terraform or OpenTofu for provider breadth; a platform built around Kubernetes offers developers a PostgresInstance API through Crossplane; Ansible stays for what happens inside VMs.
| Tool | Language | State | Preview | Clouds | Rollback on failure |
|---|---|---|---|---|---|
| Terraform / OpenTofu | HCL | Your backend (S3, GCS, azurerm, HCP Terraform) | plan | Any provider | No (partial apply stays; fix forward) |
| Pulumi | TS, Python, Go, C#, Java, YAML | Pulumi Cloud or DIY backend | pulumi preview | Any (many bridged) | No |
| AWS CDK | TS, Python, Java, C#, Go | CloudFormation (AWS-held) | cdk diff, change sets | AWS | Yes (CloudFormation) |
| CloudFormation | JSON/YAML | AWS-held stack | Change sets | AWS | Yes |
| Bicep / ARM templates | Bicep DSL / JSON | Azure deployments (no state file) | what-if | Azure | Partial (deployment history) |
| Crossplane | Kubernetes YAML | The Kubernetes API (etcd) | kubectl diff, GitOps diff | Any with providers | Continuous reconcile |
| Ansible | YAML playbooks | None | --check --diff (module-dependent) | Any via modules | No |
Fix: this chapter's code is Terraform/OpenTofu; the Choosing section maps team situations to tools.
Terraform and Kubernetes: kubernetes provider, helm provider, GitOps vs Terraform Important
In plain words: Terraform is good at creating the cluster and everything around it. Inside the cluster, a GitOps controller (Argo CD, Flux) is usually better, because it keeps reconciling and understands Kubernetes rollouts.
Common misunderstanding: "Manage everything, including every Deployment, with Terraform's kubernetes provider." It works, but Terraform only acts when someone runs apply; between runs nothing corrects drift, a provider configured from a cluster created in the same apply hits chicken-and-egg problems (the provider needs the endpoint before the cluster exists), and every image bump becomes an infrastructure pipeline run.
Definition: the cluster's nodes run a container runtime such as containerd (Containers Under the Hood) that Terraform never touches; Terraform's reach is the cluster API and the cloud around it. The kubernetes provider (hashicorp/kubernetes) manages Kubernetes objects (kubernetes_namespace, kubernetes_manifest for arbitrary YAML/CRDs), configured with host, cluster_ca_certificate and a token or exec plugin (aws eks get-token). The helm provider (hashicorp/helm) installs charts as Helm releases (helm_release with repository, chart, version, values). The common split: Terraform creates the EKS (or GKE/AKS) cluster, node groups, IAM roles for service accounts, DNS, databases, and bootstraps one thing in the cluster (Argo CD or Flux via helm_release); GitOps then owns every workload. GitOps vs Terraform is a question of who reconciles: a pull-based controller that runs continuously, or a push-based run triggered by CI.
bootstrap sequence that avoids the provider chicken-and-egg
1 root "cluster": aws_eks_cluster, node groups, OIDC provider, IAM roles (apply)
2 root "platform": provider "helm" configured from data "aws_eks_cluster" outputs of step 1
helm_release "argocd" (pinned chart version), root Application
3 Argo CD: syncs the GitOps repo: ingress controller (ingress-nginx or another Nginx-based one), cert-manager, apps
4 app releases: image digest commits in the GitOps repo, never terraform applyReal scenarios: ECS or EKS is the first fork: a team uses ECS instead of EKS (this chapter's stack) and Terraform owns the task definitions, so a release is a Terraform change of one digest; a team on EKS manages only the cluster and Argo CD with Terraform; a CRD installed by kubernetes_manifest fails to plan because the CRD's API is not known until it exists (separate apply or Helm chart).
| Concern | Terraform (kubernetes/helm providers) | GitOps (Argo CD / Flux) |
|---|---|---|
| When changes apply | On terraform apply | Continuously, pull from Git |
| Drift inside the cluster | Seen at the next plan | Corrected automatically (self-heal) |
| Cloud resources (VPC, RDS, IAM) | Native | Only via Crossplane / ACK controllers |
| Rollout awareness | Basic waits | Health checks, sync waves, progressive delivery |
| Best at | Cluster, cloud dependencies, bootstrapping GitOps | Workloads, add-ons, frequent releases |
Fix: this chapter provisions ECS services directly (no cluster to bootstrap) and leaves Kubernetes workloads to GitOps and Helm.
Mechanics
What terraform plan does, step by step
terraform plan -out=tfplan (Terraform 1.17, observed in the lab and described in the CLI docs)
1 load configuration: all .tf files of the root and every module (from .terraform/modules)
2 load providers from .terraform/providers, check them against .terraform.lock.hcl
3 acquire the state lock ("Acquiring state lock" is printed only when it has to wait)
4 read state; evaluate variables (precedence), locals; validate variable blocks
5 refresh: for each resource in state, the provider's Read ("Refreshing state... [id=...]")
objects that vanished are dropped ("has been deleted"); data sources are read
6 apply moved blocks, removed blocks, import blocks to the planned state ("Preparing import...")
7 build the graph; for each resource: PlanResourceChange (provider decides update vs replace,
marks computed values "(known after apply)"); lifecycle rules applied (prevent_destroy errors here)
8 print the diff (+ create, ~ update, -/+ or +/- replace, - destroy, "has moved to", "will be imported")
9 save tfplan: config snapshot, variable values, planned changes, prior state (values in clear)
10 release the lock; exit 0, or 2 with -detailed-exitcode when there are changesWhat terraform apply does with a saved plan
terraform apply tfplan
1 acquire the lock; compare the plan's prior state with the current state (lineage + serial)
mismatch -> "Error: Saved plan is stale" (lab), nothing changes
2 walk the graph: creates and updates in dependency order, up to -parallelism=10 at a time,
destroys in reverse order; create_before_destroy: new object first, then "deposed" old one
3 after each resource: persist state (a crash leaves a state that knows what was done)
4 a failed resource stops its dependants; independent branches continue; the run ends with errors
and a partially applied state: there is no rollback, the next plan shows what is left
5 write the final state (serial + 1), outputs, release the lockKnobs
| Knob | Where | Default | Notes |
|---|---|---|---|
-parallelism=n | plan / apply | 10 | Lower for rate-limited APIs |
-lock-timeout | plan / apply | 0s | 5m in CI |
-lock=false | most commands | locking on | Never on shared state |
-refresh=false | plan | refresh on | Faster plans, blind to drift |
-detailed-exitcode | plan | off | 0 none, 1 error, 2 changes |
-out=FILE | plan | none | Plan file holds values in clear |
-input=false / TF_INPUT=0 | all | prompts on | CI must not prompt |
TF_IN_AUTOMATION | env | unset | Shorter, automation-friendly messages |
TF_LOG=DEBUG, TF_LOG_PATH | env | off | Provider HTTP traces (contain secrets) |
TF_PLUGIN_CACHE_DIR | env / CLI config | unset | Shared provider cache (used on the build host) |
TF_CLI_ARGS_plan="-lock-timeout=5m" | env | unset | Per-command default flags |
required_version, required_providers | terraform {} | none | Pin both |
use_lockfile | S3 backend | false | S3-native lock, 1.11+ GA |
workspace_key_prefix | S3 backend | env: | Where workspace states go |
encryption {} | OpenTofu terraform {} | off | Client-side state/plan encryption |
Error messages you will actually see
| Message | Meaning | Fix |
|---|---|---|
Error: Error acquiring the state lock ... resource temporarily unavailable (real, local backend) | Another run holds the lock | Wait (-lock-timeout), check the holder, force-unlock only if it is dead |
Error: Saved plan is stale (real) | State changed after the plan was saved | Plan again |
Error: Instance cannot be destroyed (real) | prevent_destroy blocked the plan | Remove the destroy from the plan, or the guard knowingly |
Error: Cycle: module.laravel ... module.data ... (real, first version of the stack) | References form a loop across modules | Move the shared object up (dependency inversion) |
Error: Invalid index ... The given key does not identify an element in this collection value (real) | Indexing a resource map by a key that is not there (drift deleted it) | Iterate over the resource, or try() |
Error: Invalid value for variable (real) | A validation failed | Fix the input |
Error: Output refers to sensitive values (real, OpenTofu) | A root output derived from a sensitive value is not marked | sensitive = true or nonsensitive() knowingly |
Blocks of type "encryption" are not expected here. (real) | OpenTofu-only syntax read by Terraform | Run with tofu |
"assume_role_policy" contains an invalid JSON policy: not a JSON object (real, mocked test) | Mock produced a random string for a JSON attribute | mock_data defaults with valid JSON |
Error: Inconsistent dependency lock file | Lock file and required_providers disagree | terraform init -upgrade and commit the lock |
Error: Backend initialization required, please run "terraform init" | Backend changed | init -reconfigure or -migrate-state |
Error: No valid credential sources found | Provider found no AWS credentials | OIDC role in CI, aws sso login locally |
Warning: Resource targeting is in effect (real) | -target used | Follow with a full plan |
Go
The Go side has two jobs. The orders-api reads its infrastructure facts (environment, names, ports, where its certificate is, the database password) from the outputs of the root module that created them, so nobody copies a bucket name or an endpoint by hand. And a small Go tool, planguard, reads a saved plan as JSON in CI and stops an apply that would destroy or replace a protected resource. Both are tested against real documents produced by Terraform 1.17.2 in the lab. In short: Go reads outputs from the same JSON a pipeline would hand it.
Before
Infrastructure facts copied by hand into a per-environment config file, and a password in it, because "the config needs it":
// config/prod.go: edited by whoever last clicked in the console.
package config
var Prod = Config{
Environment: "prod",
DBHost: "shop-prod-pg.abc123.eu-central-1.rds.amazonaws.com", // copied from the console
DBPassword: "Winter2026!", // in Git, forever
Bucket: "shop-prod-storage-7f3a", // renamed last month? nobody knows
Replicas: 3,
}Every rename in the cloud silently breaks it, staging and prod drift apart, and the password is in the repository history.
After
tfoutputs decodes the terraform output -json document (one object per output: sensitive, type, value), with a generic Get[T] and a Secret type that redacts itself in %s, %v, %#v and JSON:
// Package tfoutputs decodes the document printed by `terraform output -json`
// (and `tofu output -json`): a JSON object with one entry per root-module
// output, each carrying "sensitive", "type" and "value".
package tfoutputs
import (
"encoding/json"
"errors"
"fmt"
"io"
)
// Output is one entry of `terraform output -json`.
type Output struct {
Sensitive bool `json:"sensitive"`
Type json.RawMessage `json:"type"`
Value json.RawMessage `json:"value"`
}
// Outputs maps output names to their entries.
type Outputs map[string]Output
// ErrMissing reports an output the configuration expects but the state does not have.
var ErrMissing = errors.New("output not found")
// Parse reads the whole `terraform output -json` document.
// An empty object ("{}") is valid: it is what Terraform prints before the first apply.
func Parse(r io.Reader) (Outputs, error) {
dec := json.NewDecoder(r)
var outs Outputs
if err := dec.Decode(&outs); err != nil {
return nil, fmt.Errorf("decode terraform output -json: %w", err)
}
if outs == nil {
return nil, errors.New("decode terraform output -json: document is null")
}
return outs, nil
}
// Get decodes the value of one output into T.
func Get[T any](outs Outputs, name string) (T, error) {
var v T
o, ok := outs[name]
if !ok {
return v, fmt.Errorf("%q: %w", name, ErrMissing)
}
if err := json.Unmarshal(o.Value, &v); err != nil {
return v, fmt.Errorf("%q: %w", name, err)
}
return v, nil
}
// GetSecret decodes a string output into a Secret and insists that the output
// is marked sensitive in the configuration, so the password is at least
// hidden from plan and apply logs.
func GetSecret(outs Outputs, name string) (Secret, error) {
o, ok := outs[name]
if !ok {
return "", fmt.Errorf("%q: %w", name, ErrMissing)
}
if !o.Sensitive {
return "", fmt.Errorf("%q: output holds a secret but is not marked sensitive", name)
}
s, err := Get[string](outs, name)
return Secret(s), err
}
// Secret is a string that never prints itself. `terraform output -json`
// prints sensitive values in plain text, so the program must hide them.
type Secret string
const redacted = "[redacted]"
// String implements fmt.Stringer (%s, %v, %q).
func (Secret) String() string { return redacted }
// GoString implements fmt.GoStringer (%#v).
func (Secret) GoString() string { return redacted }
// MarshalJSON keeps the secret out of JSON logs and debug dumps.
func (Secret) MarshalJSON() ([]byte, error) { return json.Marshal(redacted) }
// Reveal returns the value for the one place that needs it (a DSN).
func (s Secret) Reveal() string { return string(s) }package tfoutputs
import (
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
)
const doc = `{
"db_password": {"sensitive": true, "type": "string", "value": "s3cr3t-s3cr3t-s3cr3t"},
"plain_password": {"sensitive": false, "type": "string", "value": "oops"},
"port": {"sensitive": false, "type": "number", "value": 8080},
"tls_cert_file": {"sensitive": false, "type": "string", "value": null}
}`
func TestParseAndGet(t *testing.T) {
outs, err := Parse(strings.NewReader(doc))
if err != nil {
t.Fatal(err)
}
port, err := Get[int](outs, "port")
if err != nil || port != 8080 {
t.Fatalf("port = %d, %v", port, err)
}
cert, err := Get[*string](outs, "tls_cert_file")
if err != nil || cert != nil {
t.Fatalf("null output must decode to a nil pointer, got %v, %v", cert, err)
}
if _, err := Get[string](outs, "port"); err == nil {
t.Fatal("a number decoded into a string must fail")
}
if _, err := Get[string](outs, "redis_url"); !errors.Is(err, ErrMissing) {
t.Fatalf("missing output: %v", err)
}
}
func TestEmptyAndNullDocuments(t *testing.T) {
// `terraform output -json` prints {} when the state has no outputs yet
outs, err := Parse(strings.NewReader("{}\n"))
if err != nil || len(outs) != 0 {
t.Fatalf("{}: %v %v", outs, err)
}
if _, err := Parse(strings.NewReader("null")); err == nil {
t.Fatal("null must be rejected")
}
if _, err := Parse(strings.NewReader("No outputs found")); err == nil {
t.Fatal("non-JSON (human output) must be rejected")
}
}
func TestSecretNeedsSensitiveFlag(t *testing.T) {
outs, _ := Parse(strings.NewReader(doc))
if _, err := GetSecret(outs, "plain_password"); err == nil || !strings.Contains(err.Error(), "not marked sensitive") {
t.Fatalf("plain_password: %v", err)
}
s, err := GetSecret(outs, "db_password")
if err != nil || s.Reveal() != "s3cr3t-s3cr3t-s3cr3t" {
t.Fatalf("db_password: %v", err)
}
}
func TestSecretNeverPrints(t *testing.T) {
s := Secret("s3cr3t-s3cr3t-s3cr3t")
type cfg struct {
User string
Password Secret
}
c := cfg{User: "shop", Password: s}
js, err := json.Marshal(c)
if err != nil {
t.Fatal(err)
}
for _, out := range []string{
fmt.Sprint(s), fmt.Sprintf("%s|%v|%q|%#v", s, s, s, s),
fmt.Sprintf("%v %+v %#v", c, c, c), string(js),
} {
if strings.Contains(out, "s3cr3t") {
t.Fatalf("secret leaked: %s", out)
}
}
}appconfig turns the outputs into the service's configuration and reports every missing or invalid value at once (errors.Join); its test reads the lab's real output document (password replaced by a 24-character placeholder):
// Package appconfig builds the orders-api configuration from the outputs of
// the Terraform root module that created its infrastructure.
package appconfig
import (
"errors"
"fmt"
"io"
"sort"
"academy/infrastructure-as-code-terraform/tfoutputs"
)
// Service is one entry of the "services" output.
type Service struct {
Port int `json:"port"`
Replicas int `json:"replicas"`
ConfigFile string `json:"config_file"`
}
// Config is what the service needs at start-up.
type Config struct {
Environment string
NamePrefix string
Services map[string]Service
TLSCertFile string // empty when TLS is off (the output is null)
DBPassword tfoutputs.Secret
}
// Load reads `terraform output -json` and reports every problem at once.
func Load(r io.Reader) (Config, error) {
outs, err := tfoutputs.Parse(r)
if err != nil {
return Config{}, err
}
var c Config
var errs []error
collect := func(err error) {
if err != nil {
errs = append(errs, err)
}
}
c.Environment, err = tfoutputs.Get[string](outs, "environment")
collect(err)
c.NamePrefix, err = tfoutputs.Get[string](outs, "name_prefix")
collect(err)
c.Services, err = tfoutputs.Get[map[string]Service](outs, "services")
collect(err)
var cert *string // null output -> nil pointer
cert, err = tfoutputs.Get[*string](outs, "tls_cert_file")
collect(err)
if cert != nil {
c.TLSCertFile = *cert
}
c.DBPassword, err = tfoutputs.GetSecret(outs, "db_password")
collect(err)
if err := errors.Join(errs...); err != nil {
return Config{}, err
}
return c, c.validate()
}
func (c Config) validate() error {
var errs []error
switch c.Environment {
case "dev", "staging", "prod":
default:
errs = append(errs, fmt.Errorf("environment %q is not dev, staging or prod", c.Environment))
}
for _, name := range c.ServiceNames() {
s := c.Services[name]
if s.Port < 1 || s.Port > 65535 {
errs = append(errs, fmt.Errorf("service %s: port %d out of range", name, s.Port))
}
if s.Replicas < 1 {
errs = append(errs, fmt.Errorf("service %s: replicas %d < 1", name, s.Replicas))
}
}
if len(c.DBPassword.Reveal()) < 16 {
errs = append(errs, errors.New("db_password shorter than 16 characters"))
}
return errors.Join(errs...)
}
// ServiceNames returns the service names in a stable order.
func (c Config) ServiceNames() []string {
names := make([]string, 0, len(c.Services))
for n := range c.Services {
names = append(names, n)
}
sort.Strings(names)
return names
}package appconfig
import (
"os"
"strings"
"testing"
)
// testdata/outputs.json is the real `terraform output -json` of the lab
// (Terraform 1.17.2), with the 24-character password replaced by
// scripts/lab.sh with a 24-character placeholder.
func TestLoadRealOutputs(t *testing.T) {
f, err := os.Open("testdata/outputs.json")
if err != nil {
t.Fatal(err)
}
defer f.Close()
c, err := Load(f)
if err != nil {
t.Fatal(err)
}
if c.Environment != "dev" || !strings.HasPrefix(c.NamePrefix, "dev-") {
t.Fatalf("environment %q, prefix %q", c.Environment, c.NamePrefix)
}
if got := c.ServiceNames(); strings.Join(got, ",") != "orders-api,shop-web" {
t.Fatalf("services %v", got)
}
api := c.Services["orders-api"]
if api.Port != 8080 || api.Replicas != 1 || api.ConfigFile != "./out/orders-api.json" {
t.Fatalf("orders-api %+v (dev forces one replica)", api)
}
if c.TLSCertFile != "./out/tls.crt" {
t.Fatalf("tls cert file %q", c.TLSCertFile)
}
if n := len(c.DBPassword.Reveal()); n != 24 {
t.Fatalf("password length %d", n)
}
}
func TestLoadReportsEverythingAtOnce(t *testing.T) {
doc := `{
"name_prefix": {"sensitive": false, "type": "string", "value": "dev-x"},
"tls_cert_file": {"sensitive": false, "type": "string", "value": null},
"db_password": {"sensitive": false, "type": "string", "value": "0123456789abcdef"}
}`
_, err := Load(strings.NewReader(doc))
if err == nil {
t.Fatal("expected errors")
}
for _, want := range []string{`"environment": output not found`, `"services": output not found`, "not marked sensitive"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("error %q lacks %q", err, want)
}
}
}
func TestValidate(t *testing.T) {
doc := `{
"environment": {"sensitive": false, "type": "string", "value": "qa"},
"name_prefix": {"sensitive": false, "type": "string", "value": "qa-x"},
"services": {"sensitive": false, "type": ["map", "string"], "value": {"api": {"port": 70000, "replicas": 0, "config_file": "x"}}},
"tls_cert_file": {"sensitive": false, "type": "string", "value": null},
"db_password": {"sensitive": true, "type": "string", "value": "short"}
}`
_, err := Load(strings.NewReader(doc))
if err == nil {
t.Fatal("expected validation errors")
}
for _, want := range []string{`environment "qa"`, "port 70000", "replicas 0", "shorter than 16"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("error %q lacks %q", err, want)
}
}
}{
"db_password": {
"sensitive": true,
"type": "string",
"value": "REDACTED-BY-LAB-SCRIPT-0"
},
"environment": {
"sensitive": false,
"type": "string",
"value": "dev"
},
"name_prefix": {
"sensitive": false,
"type": "string",
"value": "dev-endless-foal"
},
"services": {
"sensitive": false,
"type": [
"object",
{
"orders-api": [
"object",
{
"config_file": "string",
"port": "number",
"replicas": "number"
}
],
"shop-web": [
"object",
{
"config_file": "string",
"port": "number",
"replicas": "number"
}
]
}
],
"value": {
"orders-api": {
"config_file": "./out/orders-api.json",
"port": 8080,
"replicas": 1
},
"shop-web": {
"config_file": "./out/shop-web.json",
"port": 8000,
"replicas": 1
}
}
},
"tls_cert_file": {
"sensitive": false,
"type": "string",
"value": "./out/tls.crt"
}
}The command the lab pipes terraform output -json into:
// Command orders-config reads `terraform output -json` on stdin and prints the
// configuration the orders-api would start with, with the secret redacted.
//
// terraform output -json | go run ./cmd/orders-config
package main
import (
"fmt"
"os"
"academy/infrastructure-as-code-terraform/appconfig"
)
func main() {
cfg, err := appconfig.Load(os.Stdin)
if err != nil {
fmt.Fprintln(os.Stderr, "config:", err)
os.Exit(1)
}
fmt.Printf("environment %s\n", cfg.Environment)
fmt.Printf("name prefix %s\n", cfg.NamePrefix)
for _, name := range cfg.ServiceNames() {
s := cfg.Services[name]
fmt.Printf("service %-10s port=%d replicas=%d file=%s\n", name, s.Port, s.Replicas, s.ConfigFile)
}
if cfg.TLSCertFile == "" {
fmt.Println("tls off")
} else {
fmt.Printf("tls on, certificate %s\n", cfg.TLSCertFile)
}
fmt.Printf("db password %v (%d characters)\n", cfg.DBPassword, len(cfg.DBPassword.Reveal()))
}planguard reads terraform show -json tfplan, folds the action lists (["delete","create"] and ["create","delete"] are both a replace), counts moves and imports, and reports deletions of protected types:
// Package planguard reads the JSON form of a saved plan
// (`terraform show -json tfplan`) and answers the two questions a pipeline
// asks before apply: what will change, and does anything protected get
// destroyed?
package planguard
import (
"encoding/json"
"fmt"
"io"
"slices"
"sort"
"strings"
)
// Plan is the subset of the plan JSON this package reads.
type Plan struct {
FormatVersion string `json:"format_version"`
TerraformVersion string `json:"terraform_version"`
Applyable *bool `json:"applyable"`
Errored bool `json:"errored"`
ResourceChanges []ResourceChange `json:"resource_changes"`
}
// ResourceChange is one entry of "resource_changes".
type ResourceChange struct {
Address string `json:"address"`
PreviousAddress string `json:"previous_address"`
Mode string `json:"mode"`
Type string `json:"type"`
Change struct {
Actions []string `json:"actions"`
Importing *struct {
ID string `json:"id"`
} `json:"importing"`
} `json:"change"`
ActionReason string `json:"action_reason"`
}
// Kind folds the action list into one word. "replace" covers both
// ["delete","create"] and ["create","delete"] (create_before_destroy).
func (rc ResourceChange) Kind() string {
a := rc.Change.Actions
switch {
case len(a) == 2 && slices.Contains(a, "delete") && slices.Contains(a, "create"):
return "replace"
case len(a) == 1:
return a[0]
default:
return strings.Join(a, ",")
}
}
// Deletes reports whether the object is destroyed (delete or either replace order).
func (rc ResourceChange) Deletes() bool { return slices.Contains(rc.Change.Actions, "delete") }
// Parse decodes a plan JSON document.
func Parse(r io.Reader) (Plan, error) {
var p Plan
if err := json.NewDecoder(r).Decode(&p); err != nil {
return Plan{}, fmt.Errorf("decode plan json: %w", err)
}
if p.FormatVersion == "" {
return Plan{}, fmt.Errorf("decode plan json: no format_version (is this `terraform show -json <planfile>` output?)")
}
if major, _, _ := strings.Cut(p.FormatVersion, "."); major != "1" {
return Plan{}, fmt.Errorf("decode plan json: unsupported format_version %s", p.FormatVersion)
}
return p, nil
}
// Summary counts managed-resource changes by kind, plus moves and imports.
type Summary struct {
Counts map[string]int
Moved []string // "old -> new"
Imports []string // "address (id)"
}
// Summarize ignores data sources ("read") and reports moves and imports
// separately, because a move or an import is often a no-op action.
func Summarize(p Plan) Summary {
s := Summary{Counts: map[string]int{}}
for _, rc := range p.ResourceChanges {
if rc.Mode == "data" {
continue
}
s.Counts[rc.Kind()]++
if rc.PreviousAddress != "" && rc.PreviousAddress != rc.Address {
s.Moved = append(s.Moved, rc.PreviousAddress+" -> "+rc.Address)
}
if rc.Change.Importing != nil {
s.Imports = append(s.Imports, fmt.Sprintf("%s (%s)", rc.Address, rc.Change.Importing.ID))
}
}
sort.Strings(s.Moved)
sort.Strings(s.Imports)
return s
}
// String prints the counts in a fixed order, for a PR comment.
func (s Summary) String() string {
var b strings.Builder
for _, k := range []string{"create", "update", "replace", "delete", "forget", "no-op"} {
if n := s.Counts[k]; n > 0 {
fmt.Fprintf(&b, "%s=%d ", k, n)
}
}
fmt.Fprintf(&b, "moved=%d imported=%d", len(s.Moved), len(s.Imports))
return b.String()
}
// Violation is a planned destruction of a protected resource type.
type Violation struct {
Address string
Kind string
Reason string
}
func (v Violation) String() string {
if v.Reason != "" {
return fmt.Sprintf("%s would be %sd (%s)", v.Address, v.Kind, v.Reason)
}
return fmt.Sprintf("%s would be %sd", v.Address, v.Kind)
}
// Check returns every delete or replace of a protected type. A pipeline runs it
// between plan and apply; a human approves the exceptions.
func Check(p Plan, protected []string) []Violation {
var out []Violation
for _, rc := range p.ResourceChanges {
if rc.Mode == "data" || !rc.Deletes() || !slices.Contains(protected, rc.Type) {
continue
}
out = append(out, Violation{Address: rc.Address, Kind: rc.Kind(), Reason: rc.ActionReason})
}
return out
}package planguard
import (
"os"
"slices"
"strings"
"testing"
)
// testdata/*.json: real `terraform show -json <planfile>` output from the lab
// (Terraform 1.17.2), trimmed by scripts/lab.sh with jq to the fields this
// package reads (no prior state, no values, so no secrets).
func load(t *testing.T, name string) Plan {
t.Helper()
f, err := os.Open("testdata/" + name + ".json")
if err != nil {
t.Fatal(err)
}
defer f.Close()
p, err := Parse(f)
if err != nil {
t.Fatal(err)
}
return p
}
func TestSummaries(t *testing.T) {
cases := map[string]string{
"create": "create=8 moved=0 imported=0",
"replace": "replace=2 no-op=6 moved=0 imported=0",
"moved": "no-op=8 moved=2 imported=0",
"import": "no-op=9 moved=0 imported=1",
"removed": "forget=1 no-op=8 moved=0 imported=0",
"destroy": "delete=8 moved=0 imported=0",
}
for name, want := range cases {
if got := Summarize(load(t, name)).String(); got != want {
t.Errorf("%s: got %q, want %q", name, got, want)
}
}
}
func TestMovesAndImportsAreNamed(t *testing.T) {
s := Summarize(load(t, "moved"))
want := `local_file.service_config["orders-api"] -> local_file.service["orders-api"]`
if !slices.Contains(s.Moved, want) {
t.Fatalf("moved %v", s.Moved)
}
s = Summarize(load(t, "import"))
if len(s.Imports) != 1 || s.Imports[0] != "random_integer.debug_port (9042,9000,9099)" {
t.Fatalf("imports %v", s.Imports)
}
}
func TestCheckBlocksProtectedTypes(t *testing.T) {
protected := []string{"random_password", "aws_db_instance"}
v := Check(load(t, "replace"), protected)
if len(v) != 1 || v[0].Address != "random_password.db" || v[0].Kind != "replace" || v[0].Reason != "replace_by_request" {
t.Fatalf("replace: %v", v)
}
v = Check(load(t, "destroy"), protected)
if len(v) != 1 || v[0].Kind != "delete" {
t.Fatalf("destroy: %v", v)
}
// forget (removed block with destroy = false) is not a deletion
for _, name := range []string{"create", "moved", "import", "removed"} {
if v := Check(load(t, name), []string{"random_integer", "local_file", "random_password"}); len(v) != 0 {
t.Errorf("%s: unexpected violations %v", name, v)
}
}
}
func TestCreateBeforeDestroyIsAReplace(t *testing.T) {
rc := ResourceChange{Type: "aws_security_group"}
rc.Change.Actions = []string{"create", "delete"}
if rc.Kind() != "replace" || !rc.Deletes() {
t.Fatalf("kind %q", rc.Kind())
}
}
func TestParseRejectsOtherDocuments(t *testing.T) {
for _, doc := range []string{
`{}`, // not a plan
`{"version": 4, "serial": 3, "resources": []}`, // a state file
`{"format_version": "2.0", "resource_changes": []}`,
} {
if _, err := Parse(strings.NewReader(doc)); err == nil {
t.Errorf("accepted %s", doc)
}
}
}// Command planguard prints a one-line plan summary and exits 2 when the plan
// destroys or replaces a protected resource type.
//
// terraform show -json tfplan > plan.json
// planguard -protect aws_db_instance,aws_s3_bucket plan.json
package main
import (
"flag"
"fmt"
"os"
"strings"
"academy/infrastructure-as-code-terraform/planguard"
)
func main() {
protect := flag.String("protect", "aws_db_instance,aws_elasticache_replication_group,aws_s3_bucket,random_password",
"comma-separated resource types that must not be deleted or replaced")
flag.Parse()
if flag.NArg() != 1 {
fmt.Fprintln(os.Stderr, "usage: planguard [-protect types] plan.json")
os.Exit(64)
}
f, err := os.Open(flag.Arg(0))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer f.Close()
plan, err := planguard.Parse(f)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Printf("terraform %s plan: %s\n", plan.TerraformVersion, planguard.Summarize(plan))
violations := planguard.Check(plan, strings.Split(*protect, ","))
for _, v := range violations {
fmt.Println("BLOCKED:", v)
}
if len(violations) > 0 {
os.Exit(2)
}
}{
"format_version": "1.2",
"terraform_version": "1.17.2",
"applyable": true,
"errored": false,
"resource_changes": [
{
"address": "local_file.service_config[\"orders-api\"]",
"mode": "managed",
"type": "local_file",
"change": {
"actions": [
"no-op"
],
"importing": null
}
},
{
"address": "local_file.service_config[\"shop-web\"]",
"mode": "managed",
"type": "local_file",
"change": {
"actions": [
"no-op"
],
"importing": null
}
},
{
"address": "local_file.tls_cert[0]",
"mode": "managed",
"type": "local_file",
"change": {
"actions": [
"no-op"
],
"importing": null
}
},
{
"address": "local_sensitive_file.db_password",
"mode": "managed",
"type": "local_sensitive_file",
"action_reason": "replace_because_cannot_update",
"change": {
"actions": [
"delete",
"create"
],
"importing": null
}
},
{
"address": "random_password.db",
"mode": "managed",
"type": "random_password",
"action_reason": "replace_by_request",
"change": {
"actions": [
"delete",
"create"
],
"importing": null
}
},
{
"address": "random_pet.suffix",
"mode": "managed",
"type": "random_pet",
"change": {
"actions": [
"no-op"
],
"importing": null
}
},
{
"address": "tls_private_key.service[0]",
"mode": "managed",
"type": "tls_private_key",
"change": {
"actions": [
"no-op"
],
"importing": null
}
},
{
"address": "tls_self_signed_cert.service[0]",
"mode": "managed",
"type": "tls_self_signed_cert",
"change": {
"actions": [
"no-op"
],
"importing": null
}
}
]
}module academy/infrastructure-as-code-terraform
go 1.24The Go angle
encoding/jsonis enough.terraform output -jsonandterraform show -jsonare documented, versioned formats (the plan JSON carriesformat_version, 1.2 in this Terraform), so a typed subset withjson.RawMessagefor the parts you do not need is stable;planguard.Parserefuses documents without aformat_versionor with a major version other than 1, and refuses a state file passed by mistake.- Generics for typed lookups.
Get[T any](outs, name)decodesmap[string]Service,stringor*string(anulloutput becomes a nil pointer) without one helper per type. - A secret type, not a convention. The lab printed
db password [redacted] (24 characters); the test formats the value with%s,%v,%q,%#v,%+vinside a struct andjson.Marshal, and fails if the text ever appears.GetSecretalso refuses an output that carries a secret but is not markedsensitive, so the password is at least hidden from plan logs. - Where the outputs come from at run time. In production the service should not run
terraformat all. The usual paths: CI writes the non-secret outputs into the service's environment (the ECS task definition'senvironment, which this chapter's stack does directly), or into SSM Parameter Store / a ConfigMap, and secrets arrive by reference (ECSsecretswith an ARN). The JSON reader is for tooling, smoke tests, local development and generated config. - Go is also the language of the ecosystem. Terraform, OpenTofu, providers (the Plugin Framework), Terragrunt, tflint and Pulumi's engine are written in Go;
hashicorp/terraform-execandterraform-jsonare the official Go libraries for driving Terraform and reading its JSON, and Terratest (Gruntwork) writes integration tests for real infrastructure in Go. This chapter stays on the standard library so the module has no dependencies (go.modhas norequire, so there is nogo.sum).
Laravel
Before
A Laravel production .env maintained by hand on the server, with long-lived access keys for a deploy user:
# .env on the prod server, edited over SSH
FILESYSTEM_DISK=s3
AWS_ACCESS_KEY_ID=AKIA................ # a deploy user's static key, never rotated
AWS_SECRET_ACCESS_KEY=....................
AWS_DEFAULT_REGION=eu-central-1
AWS_BUCKET=shop-prod-uploads # created in the console in 2023
QUEUE_CONNECTION=sqs
SQS_PREFIX=https://sqs.eu-central-1.amazonaws.com/123456789012
SQS_QUEUE=default # no dead-letter queue: poison jobs retry forever
MAIL_MAILER=ses # domain verified by hand, DKIM records copied manuallyAfter
The laravel-app module creates exactly what Laravel's s3 disk, sqs queue connection and ses mailer need, plus one IAM policy per task role, and outputs one value per Laravel environment variable:
# Laravel's cloud pieces: the "s3" filesystem disk, the "ses" mailer and the
# "sqs" queue connection, plus the IAM policy that lets the app use them.
resource "aws_s3_bucket" "storage" {
bucket_prefix = "${var.name}-storage-"
force_destroy = var.force_destroy_bucket
}
resource "aws_s3_bucket_public_access_block" "storage" {
bucket = aws_s3_bucket.storage.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_s3_bucket_versioning" "storage" {
bucket = aws_s3_bucket.storage.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "storage" {
bucket = aws_s3_bucket.storage.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
resource "aws_sqs_queue" "dead_letter" {
name = "${var.name}-default-dlq"
message_retention_seconds = 14 * 24 * 3600
sqs_managed_sse_enabled = true
}
resource "aws_sqs_queue" "default" {
name = "${var.name}-default"
visibility_timeout_seconds = var.queue_visibility_timeout
sqs_managed_sse_enabled = true
redrive_policy = jsonencode({
deadLetterTargetArn = aws_sqs_queue.dead_letter.arn
maxReceiveCount = var.max_receive_count
})
}
resource "aws_sesv2_email_identity" "domain" {
email_identity = var.mail_domain
}
data "aws_iam_policy_document" "app" {
statement {
sid = "Storage"
actions = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"]
resources = ["${aws_s3_bucket.storage.arn}/*"]
}
statement {
sid = "StorageList"
actions = ["s3:ListBucket"]
resources = [aws_s3_bucket.storage.arn]
}
statement {
sid = "Queue"
actions = [
"sqs:SendMessage", "sqs:ReceiveMessage", "sqs:DeleteMessage",
"sqs:ChangeMessageVisibility", "sqs:GetQueueAttributes", "sqs:GetQueueUrl",
]
resources = [aws_sqs_queue.default.arn]
}
statement {
sid = "Mail"
actions = ["ses:SendEmail", "ses:SendRawEmail"]
resources = [aws_sesv2_email_identity.domain.arn]
}
}
resource "aws_iam_role_policy" "app" {
for_each = var.task_role_names
name = "laravel-app"
role = each.value
policy = data.aws_iam_policy_document.app.json
}variable "name" {
type = string
}
variable "mail_domain" {
description = "Domain verified in SES for outgoing mail (DKIM CNAMEs come back as an output)."
type = string
}
variable "task_role_names" {
description = "Task roles (web, worker, scheduler) that get S3, SQS and SES access."
type = map(string)
}
variable "queue_visibility_timeout" {
description = "Seconds; SQS has no retry_after, this timeout decides redelivery: keep it above queue:work --timeout."
type = number
default = 120
}
variable "max_receive_count" {
description = "Deliveries before a message moves to the dead-letter queue."
type = number
default = 5
}
variable "force_destroy_bucket" {
description = "true only in throwaway environments: lets destroy delete a non-empty bucket."
type = bool
default = false
}# Each output maps to one Laravel environment variable.
output "bucket" {
description = "AWS_BUCKET"
value = aws_s3_bucket.storage.bucket
}
output "queue_prefix" {
description = "SQS_PREFIX (the queue URL without the queue name)"
value = trimsuffix(aws_sqs_queue.default.url, "/${aws_sqs_queue.default.name}")
}
output "queue_name" {
description = "SQS_QUEUE"
value = aws_sqs_queue.default.name
}
output "dkim_tokens" {
description = "Publish <token>._domainkey.<domain> CNAME <token>.dkim.amazonses.com for each."
# one() of the splat: null instead of an index error while SES has not filled it in
value = one(aws_sesv2_email_identity.domain.dkim_signing_attributes[*].tokens)
}Its tests run with a mocked AWS provider (three runs, all pass on the build host):
# Runs without an AWS account: mock_provider (Terraform 1.7+) returns fake
# values for every computed attribute.
mock_provider "aws" {
# A mocked data source returns random strings; IAM validates policy JSON
# at plan time, so give the policy documents a syntactically valid default.
mock_data "aws_iam_policy_document" {
defaults = {
json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"
}
}
override_resource {
target = aws_sqs_queue.default
values = {
url = "https://sqs.eu-central-1.amazonaws.com/123456789012/shop-test-default"
}
}
override_resource {
target = aws_sqs_queue.dead_letter
values = {
arn = "arn:aws:sqs:eu-central-1:123456789012:shop-test-default-dlq"
}
}
}
variables {
name = "shop-test"
mail_domain = "test.shop.example.com"
task_role_names = { web = "web-role", worker = "worker-role" }
}
run "queue_has_dead_letter_queue" {
command = apply
assert {
condition = jsondecode(aws_sqs_queue.default.redrive_policy).deadLetterTargetArn == aws_sqs_queue.dead_letter.arn
error_message = "default queue must redrive to the DLQ"
}
assert {
condition = jsondecode(aws_sqs_queue.default.redrive_policy).maxReceiveCount == 5
error_message = "maxReceiveCount must default to 5"
}
assert {
condition = output.queue_prefix == "https://sqs.eu-central-1.amazonaws.com/123456789012"
error_message = "SQS_PREFIX must be the queue URL without the queue name"
}
}
run "bucket_is_private_and_kept" {
command = plan
assert {
condition = alltrue([
aws_s3_bucket_public_access_block.storage.block_public_acls,
aws_s3_bucket_public_access_block.storage.block_public_policy,
aws_s3_bucket_public_access_block.storage.restrict_public_buckets,
])
error_message = "storage bucket must block public access"
}
assert {
condition = aws_s3_bucket.storage.force_destroy == false
error_message = "force_destroy must be off unless asked for"
}
}
run "every_role_gets_the_policy" {
command = plan
assert {
condition = toset(keys(aws_iam_role_policy.app)) == toset(["web", "worker"])
error_message = "one policy per task role"
}
}The stack runs the Laravel image (php-fpm with Nginx, built in Images & Dockerfiles) as three ECS services (web, queue:work sqs, schedule:work) and writes the outputs straight into their environment; the database password reaches the container by ARN, never through Terraform. The stack has no load balancer or ingress: the services run in private subnets and are unreachable from outside until an ALB (or API gateway) and its target group are added and passed to ecs-service as target_group_arn:
# The shop stack: one network, one data tier, three ECS services and the
# Laravel cloud pieces. Environments call this module with different sizes;
# they never copy its resources.
locals {
name = "shop-${var.environment}"
}
module "network" {
source = "../../modules/network"
name = local.name
cidr_block = var.cidr_block
azs = var.azs
nat_gateway = var.sizes.nat_gateway
}
# The app tier's security groups live here, not inside ecs-service: the data
# tier must allow them, and the services need the data tier's endpoints.
# Inside the service module that was a dependency cycle (see the Lab).
resource "aws_security_group" "app" {
for_each = toset(["orders-api", "laravel"])
name_prefix = "${local.name}-${each.key}-"
vpc_id = module.network.vpc_id
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
lifecycle {
create_before_destroy = true
}
}
resource "aws_ecs_cluster" "this" {
name = local.name
setting {
name = "containerInsights"
value = "enabled"
}
}
module "orders_api" {
source = "../../modules/ecs-service"
name = "${local.name}-orders-api"
cluster_arn = aws_ecs_cluster.this.arn
subnet_ids = module.network.private_subnet_ids
security_group_ids = [aws_security_group.app["orders-api"].id]
image = var.images.orders_api
port = 8080
cpu = var.sizes.orders_api_cpu
memory = var.sizes.orders_api_cpu * 2
environment = {
APP_ENV = var.environment
DATABASE_HOST = module.data.postgres_endpoint
REDIS_ADDR = "${module.data.redis_endpoint}:6379"
}
secrets = {
DATABASE_SECRET_JSON = module.data.postgres_secret_arn
}
}
# Laravel: one image, three roles (web, worker, scheduler) as in the Helm chapter
module "laravel" {
for_each = {
web = { command = null, port = 8000, count = var.sizes.web_count }
worker = { command = ["php", "artisan", "queue:work", "sqs", "--timeout=90", "--max-time=3600"], port = null, count = 1 }
scheduler = { command = ["php", "artisan", "schedule:work"], port = null, count = 1 }
}
source = "../../modules/ecs-service"
name = "${local.name}-laravel-${each.key}"
cluster_arn = aws_ecs_cluster.this.arn
subnet_ids = module.network.private_subnet_ids
security_group_ids = [aws_security_group.app["laravel"].id]
image = var.images.laravel
command = each.value.command
port = each.value.port
desired_count = each.value.count
environment = {
APP_ENV = var.environment
DB_CONNECTION = "pgsql"
DB_HOST = module.data.postgres_endpoint
REDIS_HOST = module.data.redis_endpoint
REDIS_SCHEME = "tls"
FILESYSTEM_DISK = "s3"
AWS_BUCKET = module.laravel_cloud.bucket
QUEUE_CONNECTION = "sqs"
SQS_PREFIX = module.laravel_cloud.queue_prefix
SQS_QUEUE = module.laravel_cloud.queue_name
MAIL_MAILER = "ses"
}
secrets = {
DB_SECRET_JSON = module.data.postgres_secret_arn
}
}
module "data" {
source = "../../modules/data-stores"
name = local.name
vpc_id = module.network.vpc_id
subnet_ids = module.network.private_subnet_ids
client_security_group_ids = [for sg in aws_security_group.app : sg.id]
postgres = {
instance_class = var.sizes.pg_class
multi_az = var.sizes.pg_multi_az
deletion_protection = var.environment == "prod"
}
redis = {
nodes = var.sizes.redis_nodes
}
}
module "laravel_cloud" {
source = "../../modules/laravel-app"
name = local.name
mail_domain = var.mail_domain
task_role_names = { for role, m in module.laravel : role => m.task_role_name }
force_destroy_bucket = var.environment != "prod"
}The Laravel angle
- Credentials from the task role, not from
.env. Laravel's SQS connector only passes explicit credentials when both are set:elseif (! empty($config['key']) && ! empty($config['secret']))inSqsConnector.php(13.x). LeaveAWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEYunset in ECS and the AWS SDK for PHP falls back to its default credential chain, which on ECS is the task role this chapter's module grants S3, SQS and SES permissions to. Thes3disk and thesesmailer read the same keys and behave the same way. - SQS has no
retry_after. The Laravel queue docs: "The only queue connection which does not contain a retry_after value is Amazon SQS. SQS will retry the job based on the Default Visibility Timeout". So the module'svisibility_timeout_seconds(120) must be larger than the worker's--timeout(90 in the stack), or a slow job is delivered twice;maxReceiveCount = 5moves a poison job to the dead-letter queue instead of retrying it forever. - The env var map. Laravel's
config/queue.phpbuilds the queue URL fromprefixandqueue:
// config/queue.php in a Laravel 13 application (excerpt from the docs; the overflow options are cut)
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],| Laravel variable | Terraform source | Notes |
|---|---|---|
FILESYSTEM_DISK=s3, AWS_BUCKET | module.laravel_cloud.bucket | Bucket private, versioned, encrypted; force_destroy only outside prod |
QUEUE_CONNECTION=sqs, SQS_PREFIX, SQS_QUEUE | queue_prefix (trimsuffix of the queue URL), queue_name | DLQ via redrive_policy |
MAIL_MAILER=ses | aws_sesv2_email_identity.domain | Publish the three DKIM CNAMEs from dkim_tokens (DNS: Email Delivery) |
DB_HOST, REDIS_HOST, REDIS_SCHEME=tls | module.data outputs | ElastiCache with transit_encryption_enabled needs TLS |
DB_SECRET_JSON | master_user_secret[0].secret_arn | ECS injects the JSON secret; the app (or an entrypoint) reads the password field |
AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY | none | Task role instead |
- Migrations are not Terraform's job. Run
php artisan migrate --forceas a one-off ECS task (or a deploy step) after the infrastructure exists and before the new web tasks; why the migration must stay backwards compatible is Zero-Downtime Schema Migrations.
The Terraform code
The cloud-free lab project (local, random, tls providers; every command really ran)
terraform {
# ephemeral values and resources arrived in Terraform 1.10
required_version = ">= 1.10"
required_providers {
random = {
source = "hashicorp/random"
version = "~> 3.9"
}
local = {
source = "hashicorp/local"
version = "~> 2.9"
}
tls = {
source = "hashicorp/tls"
version = "~> 4.4"
}
}
}variable "environment" {
description = "Deployment environment; selects sizes and names."
type = string
default = "dev"
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be one of dev, staging, prod."
}
}
variable "services" {
description = "One entry per service: the port it listens on and how many replicas run."
type = map(object({
port = number
replicas = optional(number, 1)
}))
default = {
orders-api = { port = 8080, replicas = 2 }
shop-web = { port = 8000 }
}
}
variable "enable_tls" {
description = "Create a private key and a self-signed certificate for local TLS."
type = bool
default = true
}
variable "cert_subject" {
description = "Optional certificate subject; null means no subject block."
type = object({
common_name = string
organization = optional(string, "Academy Lab")
})
default = { common_name = "orders.lab.internal" }
}
variable "output_dir" {
description = "Directory the rendered service files are written to."
type = string
default = "out"
}locals {
name_prefix = "${var.environment}-${random_pet.suffix.id}"
# dev runs one replica of everything, whatever the map says
replicas = {
for name, svc in var.services :
name => var.environment == "dev" ? 1 : svc.replicas
}
common_labels = {
environment = var.environment
managed_by = "terraform"
}
}
# A stable random name per environment; a new environment gets a new name.
resource "random_pet" "suffix" {
length = 2
keepers = {
environment = var.environment
}
}
# Stands in for a database password. The result is marked sensitive,
# but it is still written to the state file in plain text.
resource "random_password" "db" {
length = 24
special = false
}
# count: zero or one instance, switched by a bool
resource "tls_private_key" "service" {
count = var.enable_tls ? 1 : 0
algorithm = "ECDSA"
ecdsa_curve = "P256"
}
resource "tls_self_signed_cert" "service" {
count = var.enable_tls ? 1 : 0
private_key_pem = tls_private_key.service[0].private_key_pem
validity_period_hours = 24 * 30
early_renewal_hours = 24
allowed_uses = ["digital_signature", "key_encipherment", "server_auth"]
dns_names = [for name in keys(var.services) : "${name}.lab.internal"]
# dynamic block: render the subject block only when a subject is given
dynamic "subject" {
for_each = var.cert_subject == null ? [] : [var.cert_subject]
content {
common_name = subject.value.common_name
organization = subject.value.organization
}
}
}
# The certificate is public; it goes to a file, the private key stays in state.
resource "local_file" "tls_cert" {
count = var.enable_tls ? 1 : 0
filename = "${path.module}/${var.output_dir}/tls.crt"
content = tls_self_signed_cert.service[0].cert_pem
}
# for_each: one file per service, addressed by the map key
resource "local_file" "service_config" {
for_each = var.services
filename = "${path.module}/${var.output_dir}/${each.key}.json"
file_permission = "0644"
content = jsonencode({
service = each.key
name = "${local.name_prefix}-${each.key}"
port = each.value.port
replicas = local.replicas[each.key]
labels = local.common_labels
tls_enabled = var.enable_tls
})
}
# The secret file is written with 0600 and its content is hidden in plans,
# but the content is still stored in state.
resource "local_sensitive_file" "db_password" {
filename = "${path.module}/${var.output_dir}/db-password"
file_permission = "0600"
content = random_password.db.result
}output "environment" {
description = "The environment this state belongs to."
value = var.environment
}
output "name_prefix" {
description = "Prefix used for every name in this environment."
value = local.name_prefix
}
output "services" {
description = "Port, replicas and config file per service."
# Iterate over the resource, not over var.services: during a refresh-only
# plan a file deleted outside Terraform is missing from the resource map,
# and indexing it by a key from the variable fails (seen in the lab).
value = {
for name, f in local_file.service_config : name => {
port = var.services[name].port
replicas = local.replicas[name]
config_file = f.filename
}
}
}
output "tls_cert_file" {
description = "Path of the self-signed certificate; null when TLS is off."
value = var.enable_tls ? local_file.tls_cert[0].filename : null
}
output "db_password" {
description = "Database password. Hidden in plan and apply output, NOT in state or output -json."
value = random_password.db.result
sensitive = true
}environment = "staging"
services = {
orders-api = { port = 8080, replicas = 3 }
shop-web = { port = 8000, replicas = 2 }
}# terraform test: each run block plans (or applies) the root module
# with its own variables and checks assertions against the result.
variables {
environment = "staging"
}
run "staging_keeps_replicas" {
command = plan
assert {
condition = output.services["orders-api"].replicas == 2
error_message = "staging must keep the replica count from var.services"
}
assert {
condition = output.services["shop-web"].config_file == "./out/shop-web.json"
error_message = "config files must be written under ./out"
}
}
run "dev_runs_one_replica" {
command = plan
variables {
environment = "dev"
}
assert {
condition = output.services["orders-api"].replicas == 1
error_message = "dev must force one replica"
}
}
run "rejects_unknown_environment" {
command = plan
variables {
environment = "qa"
}
expect_failures = [var.environment]
}
run "tls_off_means_no_key" {
command = plan
variables {
enable_tls = false
}
assert {
condition = length(tls_private_key.service) == 0 && output.tls_cert_file == null
error_message = "enable_tls = false must create no key and no certificate"
}
}
run "apply_writes_files" {
command = apply
assert {
condition = length(random_password.db.result) == 24
error_message = "password must be 24 characters"
}
assert {
condition = jsondecode(local_file.service_config["shop-web"].content).port == 8000
error_message = "shop-web config must carry port 8000"
}
assert {
condition = startswith(output.name_prefix, "staging-")
error_message = "name prefix must start with the environment"
}
}The refactoring steps the lab copies in one at a time:
# Step 10 of the lab: main.tf and outputs.tf rename
# local_file.service_config to local_file.service. Without this block,
# the plan would destroy every file and create it again.
moved {
from = local_file.service_config
to = local_file.service
}# Step 20: adopt an object that already exists. For random_integer the
# import ID is "result,min,max" (from the provider docs); for an AWS
# resource it would be a bucket name, a DB identifier or an ARN.
resource "random_integer" "debug_port" {
min = 9000
max = 9099
}
import {
to = random_integer.debug_port
id = "9042,9000,9099"
}# Step 30: random_integer.debug_port and its import block are deleted from
# the configuration. This block tells Terraform to forget the object
# (drop it from state) instead of destroying it.
removed {
from = random_integer.debug_port
lifecycle {
destroy = false
}
}Lifecycle arguments, and OpenTofu's state encryption:
# The three lifecycle arguments people actually use, on cloud-free resources.
terraform {
required_version = ">= 1.10"
required_providers {
random = {
source = "hashicorp/random"
version = "~> 3.9"
}
local = {
source = "hashicorp/local"
version = "~> 2.9"
}
}
}
variable "release" {
description = "Changing it forces a new random_id (keepers)."
type = string
default = "r1"
}
variable "motd" {
description = "Content written by Terraform once; later edits are ignored."
type = string
default = "hello from terraform"
}
# create_before_destroy: the replacement exists before the old one is removed
resource "random_id" "release" {
byte_length = 4
keepers = {
release = var.release
}
lifecycle {
create_before_destroy = true
}
}
# ignore_changes: Terraform sets content at creation and then stops managing it
resource "local_file" "motd" {
filename = "${path.module}/out/motd.txt"
content = var.motd
lifecycle {
ignore_changes = [content]
}
}
# prevent_destroy: any plan that would destroy this object is an error
resource "random_password" "master" {
length = 20
special = false
lifecycle {
prevent_destroy = true
}
}
output "release_id" {
value = random_id.release.hex
}# OpenTofu only (1.7+): client-side state and plan encryption.
# Terraform rejects the encryption block; this root is run with `tofu`.
variable "state_passphrase" {
description = "At least 16 characters. Supplied as TF_VAR_state_passphrase, never committed."
type = string
sensitive = true
}
terraform {
required_providers {
random = {
source = "hashicorp/random"
version = "~> 3.9"
}
}
encryption {
key_provider "pbkdf2" "lab" {
passphrase = var.state_passphrase
}
method "aes_gcm" "lab" {
keys = key_provider.pbkdf2.lab
}
state {
method = method.aes_gcm.lab
enforced = true
}
plan {
method = method.aes_gcm.lab
enforced = true
}
}
}
resource "random_password" "db" {
length = 24
special = false
}
# length() of a sensitive value is still sensitive; nonsensitive() says
# "this derived number is safe to show".
output "password_length" {
value = nonsensitive(length(random_password.db.result))
}The AWS modules (validated and tested with a mocked provider; planned against no account, applied nowhere)
resource "aws_vpc" "this" {
cidr_block = var.cidr_block
enable_dns_support = true
enable_dns_hostnames = true
tags = { Name = var.name }
}
resource "aws_internet_gateway" "this" {
vpc_id = aws_vpc.this.id
tags = { Name = var.name }
}
# for_each over a map keyed by AZ: adding an AZ adds subnets without
# renumbering the existing ones (count would shift every index).
resource "aws_subnet" "public" {
for_each = var.azs
vpc_id = aws_vpc.this.id
availability_zone = each.key
cidr_block = cidrsubnet(var.cidr_block, 4, each.value)
map_public_ip_on_launch = true
tags = { Name = "${var.name}-public-${each.key}", tier = "public" }
}
resource "aws_subnet" "private" {
for_each = var.azs
vpc_id = aws_vpc.this.id
availability_zone = each.key
cidr_block = cidrsubnet(var.cidr_block, 4, each.value + 8)
tags = { Name = "${var.name}-private-${each.key}", tier = "private" }
}
resource "aws_route_table" "public" {
vpc_id = aws_vpc.this.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.this.id
}
tags = { Name = "${var.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
}
resource "aws_eip" "nat" {
count = var.nat_gateway ? 1 : 0
domain = "vpc"
tags = { Name = "${var.name}-nat" }
}
resource "aws_nat_gateway" "this" {
count = var.nat_gateway ? 1 : 0
allocation_id = aws_eip.nat[0].id
subnet_id = aws_subnet.public[sort(keys(var.azs))[0]].id
tags = { Name = var.name }
depends_on = [aws_internet_gateway.this]
}
resource "aws_route_table" "private" {
vpc_id = aws_vpc.this.id
# dynamic block: the default route exists only when there is a NAT gateway
dynamic "route" {
for_each = aws_nat_gateway.this
content {
cidr_block = "0.0.0.0/0"
nat_gateway_id = route.value.id
}
}
tags = { Name = "${var.name}-private" }
}
resource "aws_route_table_association" "private" {
for_each = aws_subnet.private
subnet_id = each.value.id
route_table_id = aws_route_table.private.id
}variable "name" {
description = "Name prefix, e.g. shop-staging."
type = string
}
variable "cidr_block" {
description = "VPC CIDR."
type = string
default = "10.20.0.0/16"
}
variable "azs" {
description = "AZ name => index used to carve /20 subnets. Given explicitly so plan needs no API call."
type = map(number)
}
variable "nat_gateway" {
description = "One NAT gateway for the private subnets (false = private subnets have no internet egress)."
type = bool
default = true
}output "vpc_id" {
value = aws_vpc.this.id
}
output "public_subnet_ids" {
value = [for s in aws_subnet.public : s.id]
}
output "private_subnet_ids" {
value = [for s in aws_subnet.private : s.id]
}locals {
db_identifier = "${var.name}-pg"
}
resource "aws_security_group" "postgres" {
name_prefix = "${var.name}-pg-"
vpc_id = var.vpc_id
# one ingress rule per client security group
dynamic "ingress" {
for_each = toset(var.client_security_group_ids)
content {
description = "Postgres from ${ingress.value}"
from_port = 5432
to_port = 5432
protocol = "tcp"
security_groups = [ingress.value]
}
}
# name_prefix + create_before_destroy: a changed group is created first,
# so the database is never left without one
lifecycle {
create_before_destroy = true
}
}
resource "aws_db_subnet_group" "this" {
name = var.name
subnet_ids = var.subnet_ids
}
resource "aws_db_instance" "postgres" {
identifier = local.db_identifier
engine = "postgres"
engine_version = var.postgres.engine_version
instance_class = var.postgres.instance_class
allocated_storage = var.postgres.allocated_storage
storage_encrypted = true
multi_az = var.postgres.multi_az
db_name = "shop"
username = "shop_admin"
# RDS creates the password in Secrets Manager: it never enters Terraform state
manage_master_user_password = true
db_subnet_group_name = aws_db_subnet_group.this.name
vpc_security_group_ids = [aws_security_group.postgres.id]
backup_retention_period = var.postgres.backup_days
deletion_protection = var.postgres.deletion_protection
skip_final_snapshot = false
final_snapshot_identifier = "${local.db_identifier}-final"
# minor upgrades are applied by AWS; do not fight them on every plan
auto_minor_version_upgrade = true
lifecycle {
ignore_changes = [engine_version]
}
}
resource "aws_security_group" "redis" {
name_prefix = "${var.name}-redis-"
vpc_id = var.vpc_id
dynamic "ingress" {
for_each = toset(var.client_security_group_ids)
content {
description = "Redis from ${ingress.value}"
from_port = 6379
to_port = 6379
protocol = "tcp"
security_groups = [ingress.value]
}
}
lifecycle {
create_before_destroy = true
}
}
resource "aws_elasticache_subnet_group" "this" {
name = var.name
subnet_ids = var.subnet_ids
}
resource "aws_elasticache_replication_group" "redis" {
replication_group_id = "${var.name}-redis"
description = "Cache, sessions and Laravel locks for ${var.name}"
engine = "redis"
engine_version = var.redis.engine_version
node_type = var.redis.node_type
num_cache_clusters = var.redis.nodes
automatic_failover_enabled = var.redis.nodes > 1
subnet_group_name = aws_elasticache_subnet_group.this.name
security_group_ids = [aws_security_group.redis.id]
at_rest_encryption_enabled = true
transit_encryption_enabled = true
}variable "name" {
type = string
}
variable "vpc_id" {
type = string
}
variable "subnet_ids" {
description = "Private subnets for the DB and cache subnet groups."
type = list(string)
}
variable "client_security_group_ids" {
description = "Security groups (the ECS services) allowed to reach Postgres and Redis."
type = list(string)
}
variable "postgres" {
type = object({
engine_version = optional(string, "17")
instance_class = optional(string, "db.t4g.micro")
allocated_storage = optional(number, 20)
multi_az = optional(bool, false)
deletion_protection = optional(bool, true)
backup_days = optional(number, 7)
})
default = {}
}
variable "redis" {
type = object({
engine_version = optional(string, "7.1")
node_type = optional(string, "cache.t4g.micro")
nodes = optional(number, 1)
})
default = {}
}output "postgres_endpoint" {
value = aws_db_instance.postgres.address
}
output "postgres_secret_arn" {
description = "Secrets Manager secret holding the master password (managed by RDS)."
value = aws_db_instance.postgres.master_user_secret[0].secret_arn
}
output "redis_endpoint" {
value = aws_elasticache_replication_group.redis.primary_endpoint_address
}
output "deletion_protection" {
description = "Known at plan time; the stack test asserts it per environment."
value = aws_db_instance.postgres.deletion_protection
}data "aws_region" "current" {}
data "aws_iam_policy_document" "ecs_assume" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ecs-tasks.amazonaws.com"]
}
}
}
# Execution role: used by the ECS agent to pull the image, write logs, read secrets.
resource "aws_iam_role" "execution" {
name_prefix = "${substr(var.name, 0, 30)}-exec-"
assume_role_policy = data.aws_iam_policy_document.ecs_assume.json
}
resource "aws_iam_role_policy_attachment" "execution" {
role = aws_iam_role.execution.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}
data "aws_iam_policy_document" "read_secrets" {
count = length(var.secrets) > 0 ? 1 : 0
statement {
actions = ["secretsmanager:GetSecretValue", "ssm:GetParameters"]
resources = values(var.secrets)
}
}
resource "aws_iam_role_policy" "read_secrets" {
count = length(var.secrets) > 0 ? 1 : 0
role = aws_iam_role.execution.id
policy = data.aws_iam_policy_document.read_secrets[0].json
}
# Task role: what the application itself may call (S3, SQS, SES for Laravel).
resource "aws_iam_role" "task" {
name_prefix = "${substr(var.name, 0, 30)}-task-"
assume_role_policy = data.aws_iam_policy_document.ecs_assume.json
}
resource "aws_cloudwatch_log_group" "this" {
name = "/ecs/${var.name}"
retention_in_days = var.log_retention_days
}
resource "aws_ecs_task_definition" "this" {
family = var.name
requires_compatibilities = ["FARGATE"]
network_mode = "awsvpc"
cpu = var.cpu
memory = var.memory
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
command = var.command
essential = true
portMappings = var.port == null ? [] : [{ containerPort = var.port, protocol = "tcp" }]
environment = [for k in sort(keys(var.environment)) : { name = k, value = var.environment[k] }]
secrets = [for k in sort(keys(var.secrets)) : { name = k, valueFrom = var.secrets[k] }]
logConfiguration = {
logDriver = "awslogs"
options = {
awslogs-group = aws_cloudwatch_log_group.this.name
awslogs-region = data.aws_region.current.region
awslogs-stream-prefix = "app"
}
}
}])
}
resource "aws_ecs_service" "this" {
name = var.name
cluster = var.cluster_arn
task_definition = aws_ecs_task_definition.this.arn
desired_count = var.desired_count
launch_type = "FARGATE"
network_configuration {
subnets = var.subnet_ids
security_groups = var.security_group_ids
}
dynamic "load_balancer" {
for_each = var.target_group_arn == null ? [] : [var.target_group_arn]
content {
target_group_arn = load_balancer.value
container_name = "app"
container_port = var.port
}
}
deployment_circuit_breaker {
enable = true
rollback = true
}
# an autoscaling policy owns the count after creation
lifecycle {
ignore_changes = [desired_count]
}
}variable "name" {
description = "Service name, e.g. shop-staging-orders-api."
type = string
}
variable "cluster_arn" {
type = string
}
variable "subnet_ids" {
type = list(string)
}
variable "security_group_ids" {
description = "Created by the caller, so data stores can allow them without a dependency cycle."
type = list(string)
}
variable "image" {
description = "Image by digest (registry/repo@sha256:...); the stack validates it."
type = string
}
variable "command" {
description = "Container command; null keeps the image default (the web role)."
type = list(string)
default = null
}
variable "port" {
description = "Container port; null for workers that listen on nothing."
type = number
default = null
}
variable "cpu" {
type = number
default = 256
}
variable "memory" {
type = number
default = 512
}
variable "desired_count" {
type = number
default = 1
}
variable "environment" {
description = "Plain environment variables (non-secret), e.g. outputs of other modules."
type = map(string)
default = {}
}
variable "secrets" {
description = "Env var name => Secrets Manager or SSM ARN. ECS injects the value; Terraform only knows the ARN."
type = map(string)
default = {}
}
variable "target_group_arn" {
description = "Load balancer target group; null for services without one."
type = string
default = null
}
variable "log_retention_days" {
type = number
default = 30
}output "task_role_name" {
value = aws_iam_role.task.name
}
output "task_role_arn" {
value = aws_iam_role.task.arn
}
output "service_name" {
value = aws_ecs_service.this.name
}terraform {
required_version = ">= 1.11"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 6.0"
}
}
}The composition and its test:
variable "environment" {
type = string
validation {
condition = contains(["staging", "prod"], var.environment)
error_message = "environment must be staging or prod."
}
}
variable "azs" {
type = map(number)
}
variable "cidr_block" {
type = string
}
variable "mail_domain" {
type = string
}
variable "images" {
description = "Image digests written by CI: orders_api and laravel."
type = object({
orders_api = string
laravel = string
})
validation {
condition = alltrue([for i in values(var.images) : can(regex("@sha256:[0-9a-f]{64}$", i))])
error_message = "images must be pinned by digest (@sha256:...), never by tag."
}
}
variable "sizes" {
description = "Everything that differs between staging and prod, in one object."
type = object({
nat_gateway = bool
pg_class = string
pg_multi_az = bool
redis_nodes = number
orders_api_cpu = number
web_count = number
})
}output "vpc_id" {
value = module.network.vpc_id
}
output "postgres_endpoint" {
value = module.data.postgres_endpoint
}
output "redis_endpoint" {
value = module.data.redis_endpoint
}
output "laravel" {
description = "What the Laravel .env needs; no secret values, only names and ARNs."
value = {
bucket = module.laravel_cloud.bucket
queue_prefix = module.laravel_cloud.queue_prefix
queue_name = module.laravel_cloud.queue_name
dkim_tokens = module.laravel_cloud.dkim_tokens
}
}# Plans the whole stack against a mocked AWS provider: checks the
# composition (who talks to whom, what differs per environment) without
# credentials. A real plan still needs an account; see the Lab.
mock_provider "aws" {
# A mocked data source returns random strings; IAM validates policy JSON
# at plan time, so give the policy documents a syntactically valid default.
mock_data "aws_iam_policy_document" {
defaults = {
json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"
}
}
}
variables {
environment = "staging"
cidr_block = "10.20.0.0/16"
mail_domain = "staging.shop.example.com"
azs = { "eu-central-1a" = 0, "eu-central-1b" = 1 }
images = {
orders_api = "ghcr.io/acme/orders-api@sha256:1111111111111111111111111111111111111111111111111111111111111111"
laravel = "ghcr.io/acme/shop-laravel@sha256:2222222222222222222222222222222222222222222222222222222222222222"
}
sizes = {
nat_gateway = true
pg_class = "db.t4g.micro"
pg_multi_az = false
redis_nodes = 1
orders_api_cpu = 256
web_count = 1
}
}
run "staging_plan" {
command = plan
assert {
condition = length(module.network.private_subnet_ids) == 2
error_message = "one private subnet per AZ"
}
assert {
condition = toset(keys(module.laravel)) == toset(["web", "worker", "scheduler"])
error_message = "Laravel runs as three ECS services"
}
assert {
condition = module.data.deletion_protection == false
error_message = "staging can be torn down"
}
}
run "prod_protects_the_database" {
command = plan
variables {
environment = "prod"
}
assert {
condition = module.data.deletion_protection
error_message = "prod RDS must have deletion protection"
}
}
run "tag_is_rejected" {
command = plan
variables {
images = {
orders_api = "ghcr.io/acme/orders-api:latest"
laravel = "ghcr.io/acme/shop-laravel@sha256:2222222222222222222222222222222222222222222222222222222222222222"
}
}
expect_failures = [var.images]
}A thin root per environment (envs/prod has the same main.tf, providers.tf and backend.tf with prod in place of staging):
# One state per environment: same bucket, different key.
# use_lockfile = S3-native locking (GA in Terraform 1.11); no DynamoDB table.
terraform {
backend "s3" {
bucket = "acme-shop-tfstate"
key = "shop/staging/terraform.tfstate"
region = "eu-central-1"
encrypt = true
use_lockfile = true
}
}terraform {
required_version = ">= 1.11"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "eu-central-1"
# refuse to run against any other account (123456789012 is the AWS docs placeholder)
allowed_account_ids = [var.account_id]
default_tags {
tags = {
app = "shop"
environment = "staging"
managed_by = "terraform"
repository = "acme/shop-infra"
}
}
}variable "account_id" {
type = string
}
variable "images" {
type = object({
orders_api = string
laravel = string
})
}
module "shop" {
source = "../../stacks/shop"
environment = "staging"
azs = var.azs
cidr_block = var.cidr_block
mail_domain = var.mail_domain
images = var.images
sizes = var.sizes
}
variable "azs" {
type = map(number)
}
variable "cidr_block" {
type = string
}
variable "mail_domain" {
type = string
}
variable "sizes" {
type = object({
nat_gateway = bool
pg_class = string
pg_multi_az = bool
redis_nodes = number
orders_api_cpu = number
web_count = number
})
}
output "shop" {
value = {
postgres_endpoint = module.shop.postgres_endpoint
redis_endpoint = module.shop.redis_endpoint
laravel = module.shop.laravel
}
}account_id = "123456789012"
cidr_block = "10.20.0.0/16"
mail_domain = "staging.shop.example.com"
azs = {
"eu-central-1a" = 0
"eu-central-1b" = 1
}
sizes = {
nat_gateway = true
pg_class = "db.t4g.micro"
pg_multi_az = false
redis_nodes = 1
orders_api_cpu = 256
web_count = 1
}
# images is written by CI into images.auto.tfvars.json on every releaseaccount_id = "123456789012"
cidr_block = "10.30.0.0/16"
mail_domain = "shop.example.com"
azs = {
"eu-central-1a" = 0
"eu-central-1b" = 1
"eu-central-1c" = 2
}
sizes = {
nat_gateway = true
pg_class = "db.m7g.large"
pg_multi_az = true
redis_nodes = 2
orders_api_cpu = 1024
web_count = 3
}{
"images": {
"orders_api": "ghcr.io/acme/orders-api@sha256:1111111111111111111111111111111111111111111111111111111111111111",
"laravel": "ghcr.io/acme/shop-laravel@sha256:2222222222222222222222222222222222222222222222222222222222222222"
}
}The bootstrap root: state bucket and the two GitHub OIDC roles:
# Bootstrap: the state bucket and the CI roles. Applied once by an admin,
# with local state that is then migrated into the bucket it created
# (terraform init -migrate-state after adding the backend block).
terraform {
required_version = ">= 1.11"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "eu-central-1"
}
variable "github_repository" {
description = "owner/name of the infrastructure repository."
type = string
default = "acme/shop-infra"
}
resource "aws_s3_bucket" "state" {
bucket = "acme-shop-tfstate"
lifecycle {
prevent_destroy = true
}
}
resource "aws_s3_bucket_versioning" "state" {
bucket = aws_s3_bucket.state.id
versioning_configuration {
status = "Enabled" # every state write is a recoverable version
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "state" {
bucket = aws_s3_bucket.state.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "aws:kms"
}
}
}
resource "aws_s3_bucket_public_access_block" "state" {
bucket = aws_s3_bucket.state.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
# GitHub's OIDC issuer: workflows get short-lived AWS credentials, no stored keys.
resource "aws_iam_openid_connect_provider" "github" {
url = "https://token.actions.githubusercontent.com"
client_id_list = ["sts.amazonaws.com"]
}
locals {
# plan runs on pull requests and on pushes to main (the plan artifact job);
# apply only in the protected environments
roles = {
plan = [
"repo:${var.github_repository}:pull_request",
"repo:${var.github_repository}:ref:refs/heads/main",
]
apply = [
"repo:${var.github_repository}:environment:staging",
"repo:${var.github_repository}:environment:prod",
]
}
}
data "aws_iam_policy_document" "github_trust" {
for_each = local.roles
statement {
actions = ["sts:AssumeRoleWithWebIdentity"]
principals {
type = "Federated"
identifiers = [aws_iam_openid_connect_provider.github.arn]
}
condition {
test = "StringEquals"
variable = "token.actions.githubusercontent.com:aud"
values = ["sts.amazonaws.com"]
}
condition {
test = "StringEquals"
variable = "token.actions.githubusercontent.com:sub"
values = each.value
}
}
}
resource "aws_iam_role" "github" {
for_each = local.roles
name = "shop-infra-${each.key}"
assume_role_policy = data.aws_iam_policy_document.github_trust[each.key].json
}
# plan: read everything, write only the lock file (state reads need s3:GetObject)
resource "aws_iam_role_policy_attachment" "plan_read" {
role = aws_iam_role.github["plan"].name
policy_arn = "arn:aws:iam::aws:policy/ReadOnlyAccess"
}
data "aws_iam_policy_document" "plan_lock" {
statement {
actions = ["s3:PutObject", "s3:DeleteObject"]
resources = ["${aws_s3_bucket.state.arn}/shop/*/terraform.tfstate.tflock"]
}
}
resource "aws_iam_role_policy" "plan_lock" {
role = aws_iam_role.github["plan"].id
policy = data.aws_iam_policy_document.plan_lock.json
}
# apply: broad rights, but only reachable from the protected environments
resource "aws_iam_role_policy_attachment" "apply_admin" {
role = aws_iam_role.github["apply"].name
policy_arn = "arn:aws:iam::aws:policy/AdministratorAccess"
}
output "role_arns" {
value = { for k, r in aws_iam_role.github : k => r.arn }
}CI and scripts
# .github/workflows/terraform.yml in the infrastructure repository.
# Pull request: fmt, validate, test, plan per environment, comment the plan.
# Merge to main: plan again on main, save the plan file as an artifact,
# apply exactly that file behind the environment's protection rules.
name: terraform
on:
pull_request:
paths: ["aws/**", ".github/workflows/terraform.yml"]
push:
branches: [main]
paths: ["aws/**", ".github/workflows/terraform.yml"]
permissions:
contents: read
env:
TF_IN_AUTOMATION: "1"
TF_INPUT: "0"
AWS_REGION: eu-central-1
jobs:
checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: hashicorp/setup-terraform@v4
with:
terraform_version: "1.17.2"
terraform_wrapper: false
- run: terraform fmt -check -recursive -diff aws
# module tests use mock_provider: no cloud credentials in this job
- name: terraform test (mocked AWS)
run: |
for dir in aws/modules/laravel-app aws/stacks/shop; do
terraform -chdir="$dir" init -backend=false
terraform -chdir="$dir" test
done
plan:
if: github.event_name == 'pull_request'
needs: checks
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
env: [staging, prod]
permissions:
contents: read
id-token: write # OIDC token for AWS
pull-requests: write # plan comment
# one plan per environment and PR at a time; a new push cancels the old plan
concurrency:
group: plan-${{ matrix.env }}-${{ github.event.pull_request.number }}
cancel-in-progress: true
defaults:
run:
working-directory: aws/envs/${{ matrix.env }}
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version: "1.27"
- uses: hashicorp/setup-terraform@v4
with:
terraform_version: "1.17.2"
terraform_wrapper: false
- uses: aws-actions/configure-aws-credentials@v6
with:
role-to-assume: arn:aws:iam::123456789012:role/shop-infra-plan
aws-region: ${{ env.AWS_REGION }}
- run: terraform init
- run: terraform validate
- name: terraform plan
id: plan
run: |
set +e
terraform plan -lock-timeout=5m -detailed-exitcode -out=tfplan -no-color > plan.txt
code=$?
set -e
echo "exitcode=$code" >> "$GITHUB_OUTPUT"
[ "$code" -ne 1 ]
- name: guard destructive changes
run: |
set -o pipefail # keep planguard's exit 2 when piping into tee
terraform show -json tfplan > plan.json
go -C "$GITHUB_WORKSPACE/go" build -o "$RUNNER_TEMP/planguard" ./cmd/planguard
"$RUNNER_TEMP/planguard" plan.json | tee guard.txt # exit 2 = protected delete/replace
- name: comment the plan
if: always() && steps.plan.outcome != 'skipped'
uses: actions/github-script@v9
env:
ENV_NAME: ${{ matrix.env }}
with:
script: |
const fs = require('fs');
const dir = `aws/envs/${process.env.ENV_NAME}`;
const plan = fs.readFileSync(`${dir}/plan.txt`, 'utf8');
const guard = fs.existsSync(`${dir}/guard.txt`) ? fs.readFileSync(`${dir}/guard.txt`, 'utf8') : '';
const body = [
`### terraform plan: ${process.env.ENV_NAME}`,
'```', guard.trim(), '```',
'<details><summary>full plan</summary>', '', '```', plan.slice(-60000), '```', '</details>',
].join('\n');
await github.rest.issues.createComment({
owner: context.repo.owner, repo: context.repo.repo,
issue_number: context.issue.number, body,
});
plan-main:
if: github.event_name == 'push'
needs: checks
runs-on: ubuntu-latest
strategy:
max-parallel: 1 # staging first, then prod
matrix:
env: [staging, prod]
permissions:
contents: read
id-token: write
defaults:
run:
working-directory: aws/envs/${{ matrix.env }}
steps:
- uses: actions/checkout@v7
- uses: hashicorp/setup-terraform@v4
with:
terraform_version: "1.17.2"
terraform_wrapper: false
- uses: aws-actions/configure-aws-credentials@v6
with:
role-to-assume: arn:aws:iam::123456789012:role/shop-infra-plan
aws-region: ${{ env.AWS_REGION }}
- run: terraform init
- run: terraform plan -lock-timeout=5m -out=tfplan
# the plan artifact: apply runs exactly this file, or fails if it is stale
- uses: actions/upload-artifact@v7
with:
name: tfplan-${{ matrix.env }}
path: aws/envs/${{ matrix.env }}/tfplan
retention-days: 5
apply:
needs: plan-main
runs-on: ubuntu-latest
strategy:
max-parallel: 1
matrix:
env: [staging, prod]
# environment protection: prod waits for a required reviewer
environment: ${{ matrix.env }}
permissions:
contents: read
id-token: write
# never two applies on one state; queue instead of cancelling a running apply
concurrency:
group: apply-${{ matrix.env }}
cancel-in-progress: false
defaults:
run:
working-directory: aws/envs/${{ matrix.env }}
steps:
- uses: actions/checkout@v7
- uses: hashicorp/setup-terraform@v4
with:
terraform_version: "1.17.2"
terraform_wrapper: false
- uses: aws-actions/configure-aws-credentials@v6
with:
role-to-assume: arn:aws:iam::123456789012:role/shop-infra-apply
aws-region: ${{ env.AWS_REGION }}
- uses: actions/download-artifact@v8
with:
name: tfplan-${{ matrix.env }}
path: aws/envs/${{ matrix.env }}
- run: terraform init
- run: terraform apply -lock-timeout=10m tfplan#!/usr/bin/env bash
# Runs the cloud-free lab end to end in a scratch copy and saves one
# transcript per step. Nothing here talks to a cloud: the providers are
# hashicorp/random, hashicorp/local and hashicorp/tls.
#
# usage: scripts/lab.sh <terraform-binary> <tofu-binary> <work-dir> <runs-dir>
set -u
TF=$1 TOFU=$2 WORK=$3 RUNS=$4
export PATH="$(dirname "$TF"):$(dirname "$TOFU"):$PATH"
SNIP=$(cd "$(dirname "$0")/.." && pwd)
GO="$SNIP/go"
rm -rf "$WORK" "$RUNS"
mkdir -p "$WORK" "$RUNS"
cp -R "$SNIP/local-lab" "$WORK/lab"
cp -R "$SNIP/local-lab" "$WORK/lab-test"
cp -R "$SNIP/guard" "$WORK/guard"
cp -R "$SNIP/tofu-encryption" "$WORK/tofu-encryption"
cp -R "$SNIP/local-lab" "$WORK/lab-tofu"
# scrub: no home directory, no user@host, no work path in transcripts
scrub() { perl -pe 's/\e\[[0-9;]*m//g' | sed -e "s|$WORK|<work>|g" -e "s|$HOME|~|g" -e "s|$(id -un)@[A-Za-z0-9._-]*|<redacted>|g"; }
# t <file> <binary-name> <args...>: append "$ name args", output and exit code
t() {
local file=$1 name=$2; shift 2
local bin=$TF
[ "$name" = tofu ] && bin=$TOFU
{
echo "\$ $name $*"
"$bin" "$@" 2>&1
echo "[exit $?]"
echo
} | scrub >>"$RUNS/$file.txt"
}
note() { local file=$1; shift; echo "# $*" | scrub >>"$RUNS/$file.txt"; }
sh() { # sh <file> <shell command>
local file=$1; shift
{ echo "\$ $*"; bash -c "$*" 2>&1; echo "[exit $?]"; echo; } | scrub >>"$RUNS/$file.txt"
}
# keep only the fields planguard reads: no prior_state, no values, no secrets
trim_plan() { jq '{format_version, terraform_version, applyable, errored,
resource_changes: [.resource_changes[]? | {address, previous_address, mode, type, action_reason,
change: {actions: .change.actions, importing: .change.importing}} | with_entries(select(.value != null))]}'; }
mkdir -p "$WORK/bin"
(cd "$GO" && go build -o "$WORK/bin/orders-config" ./cmd/orders-config && go build -o "$WORK/bin/planguard" ./cmd/planguard) || exit 1
export PATH="$WORK/bin:$PATH"
cd "$WORK/lab" || exit 1
t 01-init terraform version
t 01-init terraform init -no-color
t 02-validate terraform fmt -check -recursive -diff
t 02-validate terraform validate -no-color
t 03-plan-apply terraform plan -no-color -out=tfplan
"$TF" show -json tfplan | trim_plan >"$GO/planguard/testdata/create.json"
t 03-plan-apply terraform apply -no-color tfplan
t 03-plan-apply terraform plan -no-color -detailed-exitcode
t 04-state terraform state list
t 04-state terraform state show -no-color random_password.db
PW=$("$TF" output -raw db_password)
printf '%s' "$PW" >"$WORK/pw.txt"
sh 04-state "jq -r 'keys | join(\" \")' terraform.tfstate"
sh 04-state "jq -r '.resources[] | \"\(.mode) \(.type).\(.name) instances=\(.instances | length)\"' terraform.tfstate"
sh 04-state "jq -r '.resources[] | select(.type == \"tls_private_key\") | .instances[0].attributes | keys | map(select(test(\"private\"))) | join(\" \")' terraform.tfstate"
note 04-state "how many times does the 24-character password appear in plain text in terraform.tfstate?"
sh 04-state "grep -o -F -f $WORK/pw.txt terraform.tfstate | wc -l | tr -d ' '"
sh 04-state "jq -r --rawfile pw $WORK/pw.txt '[paths(type == \"string\" and . == \$pw) | map(tostring) | join(\".\")] | .[]' terraform.tfstate"
t 05-output terraform output -no-color
"$TF" output -json | sed "s/$PW/REDACTED-BY-LAB-SCRIPT-0/g" >"$GO/appconfig/testdata/outputs.json"
note 05-output "terraform output -json prints db_password in plain text; lab.sh replaces it before saving"
"$TF" output -json | sed "s/$PW/<24-char password redacted by lab.sh>/g" | jq '{db_password, services, environment}' | { echo "\$ terraform output -json | jq '{db_password, services, environment}'"; cat; echo; } >>"$RUNS/05-output.txt"
sh 05-output "terraform output -raw db_password | wc -c | tr -d ' '"
note 05-output "the Go program reads the same document from stdin"
{ echo "\$ terraform output -json | orders-config"; "$TF" output -json | orders-config 2>&1; echo "[exit $?]"; } | scrub >>"$RUNS/05-output.txt"
note 06-drift "someone edits a managed file by hand"
sh 06-drift "echo '{\"port\":9999}' > out/shop-web.json"
t 06-drift terraform plan -no-color -refresh-only
t 06-drift terraform plan -no-color
t 06-drift terraform apply -no-color -auto-approve
t 06-drift terraform plan -no-color -detailed-exitcode
t 07-replace terraform plan -no-color -replace=random_password.db -out=replace.tfplan
"$TF" show -json replace.tfplan | trim_plan >"$GO/planguard/testdata/replace.json"
"$TF" show -json replace.tfplan >plan.json
sh 07-replace "planguard plan.json"
rm -f replace.tfplan plan.json
t 07-replace terraform plan -no-color '-target=local_file.service_config["orders-api"]' -var environment=staging
note 07-replace "a saved plan is tied to the state it was made from"
t 07-replace terraform plan -no-color -out=stale.tfplan -replace=random_password.db
t 07-replace terraform apply -no-color -auto-approve '-replace=local_file.service_config["shop-web"]'
t 07-replace terraform apply -no-color stale.tfplan
rm -f stale.tfplan
note 08-lock "an apply waits at its approval prompt and holds the lock; a second run tries to plan"
( sleep 12 | "$TF" apply -no-color -var environment=staging >"$WORK/held-apply.txt" 2>&1 ) &
HOLDER=$!
sleep 5
sh 08-lock "jq -r '\"ID set: \" + ((.ID|length)>0|tostring) + \", Operation: \" + .Operation + \", Who: <redacted>, Version: \" + .Version' .terraform.tfstate.lock.info"
t 08-lock terraform plan -no-color -lock-timeout=3s
wait $HOLDER
note 08-lock "the holder read EOF at the prompt and gave up; its output:"
tail -6 "$WORK/held-apply.txt" | scrub >>"$RUNS/08-lock.txt"
echo >>"$RUNS/08-lock.txt"
note 09-moved "rename local_file.service_config to local_file.service in main.tf and outputs.tf, add steps/10-moved.tf"
sed -i '' 's/local_file\.service_config/local_file.service/g; s/"local_file" "service_config"/"local_file" "service"/' main.tf outputs.tf
cp steps/10-moved.tf moved.tf
t 09-moved terraform plan -no-color -out=moved.tfplan
"$TF" show -json moved.tfplan | trim_plan >"$GO/planguard/testdata/moved.json"
t 09-moved terraform apply -no-color moved.tfplan
rm -f moved.tfplan
note 09-moved "the same rename with the CLI, no config change: plan now wants to destroy and create"
t 09-moved terraform state mv local_file.service local_file.svc
t 09-moved terraform plan -no-color
t 09-moved terraform state mv local_file.svc local_file.service
rm -f moved.tf
note 10-import "add steps/20-import.tf"
cp steps/20-import.tf import.tf
t 10-import terraform plan -no-color -out=import.tfplan
"$TF" show -json import.tfplan | trim_plan >"$GO/planguard/testdata/import.json"
t 10-import terraform apply -no-color import.tfplan
t 10-import terraform state rm random_integer.debug_port
t 10-import terraform import -no-color random_integer.debug_port 9042,9000,9099
t 10-import terraform state show -no-color random_integer.debug_port
note 11-removed "delete import.tf, add steps/30-removed.tf"
rm -f import.tf import.tfplan
cp steps/30-removed.tf removed.tf
t 11-removed terraform plan -no-color -out=removed.tfplan
"$TF" show -json removed.tfplan | trim_plan >"$GO/planguard/testdata/removed.json"
t 11-removed terraform apply -no-color removed.tfplan
rm -f removed.tfplan
t 11-removed terraform state list
rm -f removed.tf
t 12-workspaces terraform workspace new staging
t 12-workspaces terraform workspace list
t 12-workspaces terraform workspace show
sh 12-workspaces "echo terraform.workspace | terraform console"
t 12-workspaces terraform plan -no-color -var-file=env/staging.tfvars
t 12-workspaces terraform workspace select default
t 12-workspaces terraform workspace delete staging
sh 12-workspaces "find terraform.tfstate.d; ls terraform.tfstate*"
note 13-precedence "TF_VAR_ < terraform.tfvars < *.auto.tfvars < -var-file / -var in command-line order"
printf 'environment = "staging"\n' >terraform.tfvars
printf 'environment = "prod"\n' >z.auto.tfvars
sh 13-precedence "echo var.environment | TF_VAR_environment=dev terraform console"
sh 13-precedence "rm z.auto.tfvars; echo var.environment | TF_VAR_environment=dev terraform console"
sh 13-precedence "echo var.environment | terraform console -var-file=env/staging.tfvars -var environment=prod"
sh 13-precedence "echo var.environment | terraform console -var environment=prod -var-file=env/staging.tfvars"
sh 13-precedence "echo var.environment | terraform console -var environment=qa"
rm -f terraform.tfvars
t 14-destroy terraform plan -no-color -destroy -out=destroy.tfplan
"$TF" show -json destroy.tfplan | trim_plan >"$GO/planguard/testdata/destroy.json"
t 14-destroy terraform apply -no-color destroy.tfplan
sh 14-destroy "jq -r '.resources | length' terraform.tfstate; ls out 2>/dev/null | wc -l | tr -d ' '"
cd "$WORK/lab-test" || exit 1
t 15-test terraform init -no-color
t 15-test terraform test -no-color
cd "$WORK/guard" || exit 1
t 16-lifecycle terraform init -no-color
t 16-lifecycle terraform apply -no-color -auto-approve
t 16-lifecycle terraform apply -no-color -auto-approve -var release=r2
note 16-lifecycle "ignore_changes: a new motd value alone is not a diff"
t 16-lifecycle terraform plan -no-color -var release=r2 -var motd=changed
note 16-lifecycle "but if the object itself disappears (local_file treats a changed file as gone), it is created again from the current value"
sh 16-lifecycle "echo 'edited by hand' > out/motd.txt"
t 16-lifecycle terraform plan -no-color -var release=r2 -var motd=changed
t 16-lifecycle terraform destroy -no-color -auto-approve
note 16-lifecycle "the scratch copy drops prevent_destroy to clean up (the snippet keeps it)"
sed -i '' 's/prevent_destroy = true/prevent_destroy = false/' main.tf
t 16-lifecycle terraform destroy -no-color -auto-approve
cd "$WORK/tofu-encryption" || exit 1
export TF_VAR_state_passphrase="lab-only-passphrase-not-a-secret"
t 17-tofu tofu version
t 17-tofu tofu init -no-color
t 17-tofu tofu apply -no-color -auto-approve
sh 17-tofu "jq -r 'keys | join(\" \")' terraform.tfstate; jq -r '.encrypted_data | length' terraform.tfstate"
sh 17-tofu "grep -c random_password terraform.tfstate"
t 17-tofu tofu state list
note 17-tofu "Terraform does not know the encryption block"
t 17-tofu terraform init -no-color
note 17-tofu "next command runs with TF_VAR_state_passphrase set to a different (wrong) value"
TF_VAR_state_passphrase="wrong-passphrase-0123456789" t 17-tofu tofu plan -no-color
t 17-tofu tofu destroy -no-color -auto-approve
unset TF_VAR_state_passphrase
cd "$WORK/lab-tofu" || exit 1
t 18-tofu-compat tofu init -no-color
t 18-tofu-compat tofu plan -no-color
t 18-tofu-compat tofu test -no-color#!/usr/bin/env bash
# Checks the AWS code without an AWS account: fmt, init -backend=false,
# validate, and terraform test with mock_provider. Nothing is planned
# against a real account and nothing is applied.
#
# usage: scripts/aws-check.sh <terraform-binary> <work-dir> <out-file>
set -u
TF=$1 WORK=$2 OUT=$3
SNIP=$(cd "$(dirname "$0")/.." && pwd)
export PATH="$(dirname "$TF"):$PATH"
rm -rf "$WORK" && mkdir -p "$WORK" && cp -R "$SNIP/aws" "$WORK/aws"
: >"$OUT"
run() { # run <dir> <args...>
local dir=$1; shift
{ echo "\$ (cd aws/$dir && terraform $*)"; (cd "$WORK/aws/$dir" && terraform "$@" 2>&1); echo "[exit $?]"; echo; } \
| perl -pe 's/\e\[[0-9;]*m//g' | sed -e "s|$WORK|<work>|g" -e "s|$HOME|~|g" >>"$OUT"
}
run . version
run . fmt -check -recursive -diff
for d in modules/network modules/data-stores modules/ecs-service modules/laravel-app stacks/shop envs/staging envs/prod bootstrap; do
(cd "$WORK/aws/$d" && terraform init -no-color -backend=false -input=false >/dev/null 2>&1) || echo "init failed: $d" >>"$OUT"
run "$d" validate -no-color
done
run modules/laravel-app test -no-color
run stacks/shop test -no-colorSolving the classic problems
| Problem | Solution | How | Advantage | Cost / limit |
|---|---|---|---|---|
| Environments built by hand drift apart | One module, one root per environment | stacks/shop called by envs/staging and envs/prod with different sizes | The difference is one tfvars file | Wiring outputs to inputs |
| Two people apply at once | Remote state with locking | S3 backend, use_lockfile = true, -lock-timeout=5m in CI | One writer at a time | A bucket to bootstrap |
| What I reviewed is not what ran | Saved plan files | plan -out=tfplan, artefact, apply tfplan | Exactly the reviewed actions, or "Saved plan is stale" | Plan files hold secrets; short retention |
| A rename destroys a database | moved blocks | moved { from = ..., to = ... } shipped with the rename | Zero-change plan | Must be written; planguard flags misses |
| A resource exists but is not managed | import block | import { to, id } + -generate-config-out | Reviewed adoption | Provider-specific IDs |
| Hand over to another state | removed + destroy = false | Removed here, import there | No downtime | Two PRs in the right order |
| Secrets readable in state | Keep them out | Service-managed secrets, write-only args, ephemeral values, OpenTofu encryption | Least exposure | Provider support varies |
| Console edits nobody knows about | Drift detection | Nightly plan -detailed-exitcode / -refresh-only | Drift found within a day | Noise from fields other systems own |
| Long-lived cloud keys in CI | OIDC | id-token: write, role trust on aud + sub | Nothing to leak or rotate | One role per trust boundary |
| Dangerous plan merged by accident | Plan policy | planguard, OPA/conftest, Sentinel; prod environment reviewers | Machine check + human gate | Policy upkeep |
| Module change breaks consumers | Tests and versions | terraform test with mock_provider, SemVer tags, moved in releases | Safe upgrades | Mock limits (computed blocks) |
| Dependency cycle across modules | Dependency inversion | Create the shared object in the caller, pass it in | No cycles, clearer ownership | Slightly more wiring |
Every environment from one source
Staging and prod call the same stacks/shop with an environment name, a CIDR, a map of AZs, a mail domain and one sizes object (NAT gateway, RDS class and Multi-AZ, Redis node count, CPU, web task count). Anything else that differs is a smell. Deletion protection and force_destroy are derived from the environment name, so a staging copy can be torn down and prod cannot.
Locks, stale plans and queued applies
Three layers keep two changes from colliding: GitHub Actions concurrency per environment (cancel-in-progress: false for applies, so a running apply is never killed), the backend lock (use_lockfile), and the saved plan's serial check, which refuses a plan made against an older state. The lab produced the second and third errors on purpose.
Renames, adoptions and hand-overs without downtime
Code, not commands: moved for renames and module moves, import blocks for adoption, removed for hand-over. They appear in the plan, are reviewed in the PR, and run in every environment the same way. terraform state mv / rm and terraform import remain for emergencies, from a fresh state backup (terraform state pull > backup.tfstate).
Secrets that never enter state
Prefer designs where Terraform never sees the secret: RDS manage_master_user_password (Secrets Manager), ECS secrets by ARN, External Secrets in Kubernetes. Where a secret must pass through Terraform, use an ephemeral variable into a write-only argument (password_wo with password_wo_version to trigger rotation). Lock the state bucket down to the CI roles regardless; with OpenTofu, encrypt state with a KMS key provider.
Dangerous plans stopped before apply
terraform show -json tfplan | planguard -protect aws_db_instance,aws_s3_bucket,... exits 2 on any delete or replace of those types and prints BLOCKED: <address> would be replaced (replace_by_request) (real output from the lab, for a random_password). It complements prevent_destroy (gone when the block is deleted) and provider deletion protection (gone when someone turns it off first).
Modules that cannot form cycles
The first version of the stack let each ecs-service create its own security group and passed those groups to data-stores, while the services needed the data tier's endpoints: Terraform reported Error: Cycle. Creating the app-tier security groups in the stack and passing them down to both modules is the composition docs' dependency inversion, and it also makes "who may talk to the database" visible in one place.
Choosing
Which IaC tool
| Situation | Choose | Reason |
|---|---|---|
| Several clouds and SaaS APIs (DNS, CDN, GitHub, Datadog) | Terraform or OpenTofu | Largest provider ecosystem, one workflow |
| Policy requires an OSI open-source license, or client-side state encryption | OpenTofu | MPL 2.0, encryption block |
| Team wants HCP Terraform's runs, policies and private registry | Terraform + HCP Terraform | Managed state, Sentinel/OPA, VCS integration |
| Developers prefer TypeScript/Python/Go, complex logic, unit tests | Pulumi | Real languages, Pulumi Cloud or DIY state |
| AWS only, strong preference for vendor-managed state and rollbacks | AWS CDK (on CloudFormation) | cdk synth to stacks, change sets, automatic rollback |
| AWS only, templates generated or very simple | CloudFormation | No state to run, StackSets for many accounts |
| Azure only | Bicep (or Terraform azurerm) | First-party, compiles to ARM templates, what-if |
| Kubernetes-centred platform offering self-service cloud APIs | Crossplane (+ GitOps) | Continuous reconciliation, Compositions |
| Packages, files and services on existing servers | Ansible (with IaC for the servers) | Configuration management, not provisioning |
Environment layout
| Option | When | Trade-off |
|---|---|---|
| Directory per environment + shared modules | Default for most teams | Small duplication of root wiring |
| CLI workspaces | Short-lived copies (PR environments) | Same backend and credentials as the original |
| Terragrunt | Many units x many environments x accounts | Another tool and its conventions |
| HCP Terraform workspaces + variable sets | On HCP Terraform | Configuration outside Git unless managed as code |
| One repository per environment or account | Regulated prod, separate teams | Promotions become cross-repo PRs |
Backend and execution
| Need | Choose | Why |
|---|---|---|
| AWS, self-managed | S3 backend, use_lockfile, versioning, KMS, per-env keys | No DynamoDB since 1.11; recoverable |
| GCP / Azure | gcs / azurerm | Native locking |
| Managed runs, policy, UI | HCP Terraform (or Spacelift, env0, Scalr for both tools) | Locks, queues, policy checks built in |
| PR-driven apply-before-merge | Atlantis | atlantis plan / apply comments with PR locks |
| GitLab | GitLab-managed state (HTTP backend) + MR integration | State and plans next to the MR |
Where Terraform stops
| Thing | Owner | Why |
|---|---|---|
| VPC, subnets, IAM, RDS, ElastiCache, buckets, queues, DNS | Terraform | Long-lived, slow-changing, reviewed |
| ECS task definition image digest | Terraform (this chapter) or the deploy pipeline | Either works; pick one owner per field (ignore_changes for the other) |
| Kubernetes workloads and add-ons | GitOps (Argo CD / Flux) | Continuous reconcile, rollouts |
| Database schema | Application migrations | Versioned with the code |
| Secrets values | Secrets Manager / Vault / the service | Never in state |
| Container images | Docker / BuildKit in CI (Images & Dockerfiles) | Terraform only references the digest |
| OS packages and files on VMs | Ansible or image builds | Configuration management |
In architecture: from a single process to a distributed system
Infrastructure code mirrors the system's architecture: one state per thing that is deployed and owned together, modules per reusable building block, and outputs as the contracts between them. The questions at each size are how many states, who owns which, and how changes are promoted.
Monolith: one app, one stack
The Laravel shop alone: one root per environment, one state each, one stack module (VPC, RDS, Redis, S3, SES, SQS, one ECS service per role). plan on PR and apply on merge from one workflow are enough. The traps at this size are the ones in this chapter: state on a laptop, secrets in state, renames that replace the database, manual console fixes.
Modular monolith: one state, clear modules
The shop grows a Go orders-api and a PDF renderer that share the database. Keep one state, but split modules by purpose (network, data-stores, ecs-service, laravel-app), let the stack own cross-cutting things (security groups, the cluster), and give each module tests. A change to the renderer's task definition still shares a plan with the database; that is acceptable while one team owns everything.
Microservices: many states, contracts by outputs
Twenty services owned by five teams cannot share one state: every plan would show everyone's changes and one lock would serialise all deployments. The usual split:
1 platform/network (platform team) -> VPC IDs, subnet IDs published to SSM parameters
2 platform/data-<team> (each team) -> RDS / Redis per bounded context, secrets ARNs
3 services/<service> (each team) -> ECS service or Kubernetes namespace, reads SSM, not remote state
4 modules registry (platform team) -> ecs-service vX.Y, data-stores vX.Y, SemVer, moved blocks in releases
5 CI -> one plan/apply workflow per state; concurrency group per stateEach state has an owner, a pipeline and a blast radius; cross-state reads go through published outputs (SSM, a service catalogue) instead of terraform_remote_state, so a team can refactor its state without breaking others. Platform teams often package this as a golden path (Platform Engineering).
Distributed data: regions, accounts and stamps
Multi-region means one state per region per environment (shop/prod/eu-central-1/terraform.tfstate), state buckets replicated or one per region so a regional outage does not block infrastructure changes elsewhere, provider aliases for global resources (Route 53, IAM, CloudFront certificates in us-east-1), and data services configured for their replication model (Aurora global databases, ElastiCache global datastores, S3 replication), which Terraform creates but does not operate. The deployment-stamp pattern (Cloud Design Patterns II) maps to one module instantiated per stamp, with for_each over a stamp map in a root, or one root per stamp generated by Terragrunt. Database failover itself is runtime, not IaC: after a regional failover, drift is expected and plans must not "fix" it back.
Scaling path: 1x, 10x, 100x
| Scale | States | Modules | Pipeline and policy |
|---|---|---|---|
| 1x (one team, one app) | One per environment, S3 + lockfile | Local modules in the repo | Plan on PR, apply on merge, OIDC |
| 10x (several teams) | Per team and per layer (network, data, services) | Versioned modules in a registry, terraform test | Per-state workflows, planguard/OPA, required reviewers for prod |
| 100x (many accounts and regions) | Per account x region x layer, generated (Terragrunt, HCP Terraform projects) | Golden-path modules with deprecation policy | Policy as code (Sentinel/OPA), drift detection fleet-wide, cost estimation, self-service via a platform or Crossplane |
Lab
Label: there are no cloud credentials on the build host and none were created; nothing on this page was planned or applied against a real AWS account. Steps marked ran on the host were executed on macOS (darwin/arm64) with the Terraform v1.17.2 and OpenTofu v1.13.10 release binaries (downloaded into the build's scratch directory, SHA-256 verified against the published SHA256SUMS), Go 1.27.4, and only cloud-free providers (hashicorp/random, hashicorp/local, hashicorp/tls); the AWS code was run through init -backend=false, validate and terraform test with mock_provider. scripts/lab.sh ran every step in a scratch copy and saved one transcript per step under pipeline/sources/infrastructure-as-code-terraform/runs/ (colours stripped, user name, host and paths replaced by <redacted> / <work>). Excerpt convention: each $ line below is a command exactly as it appears in a transcript, with the -no-color flag dropped; # lines are excerpts of its real output, ... marks cut lines, and # (lab.sh: ...) describes what the script did between commands without printing it. Random names (dev-endless-foal) and IDs differ per run. Steps that need an AWS account or a tool that is not installed are expected, not run; their output is a shape with placeholders.
1. Init, validate, plan, apply (ran on the host)
# (lab.sh invoked as: scripts/lab.sh <terraform> <tofu> <work-dir> <runs-dir>; runs/01-init.txt, 02, 03)
$ terraform init
# - Installed hashicorp/local v2.9.1 (signed by HashiCorp)
# - Installed hashicorp/tls v4.4.2 (signed by HashiCorp)
# - Installed hashicorp/random v3.9.1 (signed by HashiCorp)
# Terraform has created a lock file .terraform.lock.hcl to record the provider ...
$ terraform fmt -check -recursive -diff
# [exit 0]
$ terraform validate
# Success! The configuration is valid.
$ terraform plan -out=tfplan
# # local_sensitive_file.db_password will be created
# + content = (sensitive value)
# # random_password.db will be created
# Plan: 8 to add, 0 to change, 0 to destroy.
# Saved the plan to: tfplan
$ terraform apply tfplan
# Apply complete! Resources: 8 added, 0 changed, 0 destroyed.
# db_password = <sensitive>
# name_prefix = "dev-endless-foal"
$ terraform plan -detailed-exitcode
# No changes. Your infrastructure matches the configuration.
# [exit 0]2. What the state and the outputs hold (ran on the host)
# runs/04-state.txt, runs/05-output.txt
$ terraform state show random_password.db
# result = (sensitive value)
$ jq -r 'keys | join(" ")' terraform.tfstate
# check_results lineage outputs resources serial terraform_version version
$ jq -r '.resources[] | select(.type == "tls_private_key") | .instances[0].attributes | keys | map(select(test("private"))) | join(" ")' terraform.tfstate
# private_key_openssh private_key_pem private_key_pem_pkcs8
$ grep -o -F -f <work>/pw.txt terraform.tfstate | wc -l | tr -d ' '
# 3
$ jq -r --rawfile pw <work>/pw.txt '[paths(type == "string" and . == $pw) | map(tostring) | join(".")] | .[]' terraform.tfstate
# outputs.db_password.value
# resources.2.instances.0.attributes.content
# resources.3.instances.0.attributes.result
$ terraform output -json | jq '{db_password, services, environment}'
# "db_password": {
# "sensitive": true,
# "type": "string",
# "value": "<24-char password redacted by lab.sh>" (printed in clear; lab.sh replaced it)
$ terraform output -raw db_password | wc -c | tr -d ' '
# 24
$ terraform output -json | orders-config
# environment dev
# name prefix dev-endless-foal
# service orders-api port=8080 replicas=1 file=./out/orders-api.json
# service shop-web port=8000 replicas=1 file=./out/shop-web.json
# tls on, certificate ./out/tls.crt
# db password [redacted] (24 characters)3. Drift (ran on the host)
# runs/06-drift.txt
$ echo '{"port":9999}' > out/shop-web.json
$ terraform plan -refresh-only
# Note: Objects have changed outside of Terraform
# # local_file.service_config["shop-web"] has been deleted
# This is a refresh-only plan, so Terraform will not take any actions to undo these. ...
$ terraform plan
# # local_file.service_config["shop-web"] will be created
# Plan: 1 to add, 0 to change, 0 to destroy.
$ terraform apply -auto-approve
$ terraform plan -detailed-exitcode
# No changes. Your infrastructure matches the configuration.
# [exit 0]
# first version of outputs.tf (runs-first-06-drift.txt): the refresh-only plan failed with
# Error: Invalid index ... local_file.service_config is object with 1 attribute "orders-api"4. Replace, target, the Go guard and stale plans (ran on the host)
# runs/07-replace.txt
$ terraform plan -replace=random_password.db -out=replace.tfplan
# # local_sensitive_file.db_password must be replaced
# # random_password.db will be replaced, as requested
# Plan: 2 to add, 0 to change, 2 to destroy.
# (lab.sh: terraform show -json replace.tfplan > plan.json)
$ planguard plan.json
# terraform 1.17.2 plan: replace=2 no-op=6 moved=0 imported=0
# BLOCKED: random_password.db would be replaced (replace_by_request)
# [exit 2]
$ terraform plan -target=local_file.service_config["orders-api"] -var environment=staging
# Warning: Resource targeting is in effect
$ terraform plan -out=stale.tfplan -replace=random_password.db
$ terraform apply -auto-approve -replace=local_file.service_config["shop-web"]
# Apply complete! Resources: 1 added, 0 changed, 1 destroyed.
$ terraform apply stale.tfplan
# Error: Saved plan is stale
# The given plan file can no longer be applied because the state was changed by
# another operation after the plan was created.
# [exit 1]5. Locking (ran on the host, local backend)
# runs/08-lock.txt
# (lab.sh, in the background: sleep 12 | terraform apply -var environment=staging, which plans and
# then waits at "Enter a value:" holding the lock)
$ jq -r '"ID set: " + ((.ID|length)>0|tostring) + ", Operation: " + .Operation + ", Who: <redacted>, Version: " + .Version' .terraform.tfstate.lock.info
# ID set: true, Operation: OperationTypeApply, Who: <redacted>, Version: 1.17.2
$ terraform plan -lock-timeout=3s
# Acquiring state lock. This may take a few moments...
# Error: Error acquiring the state lock
# Error message: resource temporarily unavailable
# Lock Info:
# ID: <uuid>
# Path: terraform.tfstate
# Operation: OperationTypeApply
# Who: <redacted>
# Version: 1.17.2
# [exit 1]
# the holder then read EOF: "Error: error asking for approval: EOF", and released the lock6. moved, state mv, import, removed (ran on the host)
# runs/09-moved.txt (lab.sh: rename local_file.service_config -> local_file.service, copy steps/10-moved.tf)
$ terraform plan -out=moved.tfplan
# # local_file.service_config["orders-api"] has moved to local_file.service["orders-api"]
# Plan: 0 to add, 0 to change, 0 to destroy.
$ terraform apply moved.tfplan
$ terraform state mv local_file.service local_file.svc
# Successfully moved 1 object(s).
$ terraform plan
# # local_file.svc["orders-api"] will be destroyed
# # (because local_file.svc is not in configuration)
# Plan: 2 to add, 0 to change, 2 to destroy.
$ terraform state mv local_file.svc local_file.service
# runs/10-import.txt (lab.sh: copy steps/20-import.tf)
$ terraform plan -out=import.tfplan
# random_integer.debug_port: Preparing import... [id=9042,9000,9099]
# Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.
$ terraform apply import.tfplan
# Apply complete! Resources: 1 imported, 0 added, 0 changed, 0 destroyed.
$ terraform state rm random_integer.debug_port
# Successfully removed 1 resource instance(s).
$ terraform import random_integer.debug_port 9042,9000,9099
# random_integer.debug_port: Import prepared! ... Import successful!
# runs/11-removed.txt (lab.sh: delete import.tf, copy steps/30-removed.tf)
$ terraform plan -out=removed.tfplan
# # random_integer.debug_port will no longer be managed by Terraform, but will not be destroyed
# # (destroy = false is set in the configuration)
# Warning: Some objects will no longer be managed by Terraform7. Workspaces and variable precedence (ran on the host)
# runs/12-workspaces.txt
$ terraform workspace new staging
# Created and switched to workspace "staging"!
$ echo terraform.workspace | terraform console
# "staging"
$ terraform plan -var-file=env/staging.tfvars
# Plan: 8 to add, 0 to change, 0 to destroy.
$ terraform workspace select default
$ terraform workspace delete staging
# Deleted workspace "staging"!
# runs/13-precedence.txt (lab.sh: terraform.tfvars says staging, z.auto.tfvars says prod)
$ echo var.environment | TF_VAR_environment=dev terraform console
# "prod"
$ rm z.auto.tfvars; echo var.environment | TF_VAR_environment=dev terraform console
# "staging"
$ echo var.environment | terraform console -var environment=prod -var-file=env/staging.tfvars
# "staging"8. terraform test, locally and with a mocked AWS provider (ran on the host)
# runs/15-test.txt (Terraform) and runs/18-tofu-compat.txt (OpenTofu)
$ terraform test
# run "staging_keeps_replicas"... pass
# run "dev_runs_one_replica"... pass
# run "rejects_unknown_environment"... pass
# run "tls_off_means_no_key"... pass
# run "apply_writes_files"... pass
# Success! 5 passed, 0 failed.
$ tofu test
# Success! 5 passed, 0 failed.
# runs-aws-check.txt, written by scripts/aws-check.sh
$ (cd aws/stacks/shop && terraform validate)
# Success! The configuration is valid. (same for the 7 other AWS roots and modules)
$ (cd aws/modules/laravel-app && terraform test)
# Success! 3 passed, 0 failed.
$ (cd aws/stacks/shop && terraform test)
# Success! 3 passed, 0 failed.9. Lifecycle arguments (ran on the host)
# runs/16-lifecycle.txt (guard/)
$ terraform apply -auto-approve -var release=r2
# +/- create replacement and then destroy
# random_id.release: Creating...
# random_id.release (deposed object <id>): Destroying... [id=<old>]
$ terraform plan -var release=r2 -var motd=changed
# No changes. Your infrastructure matches the configuration.
$ echo 'edited by hand' > out/motd.txt
$ terraform plan -var release=r2 -var motd=changed
# # local_file.motd will be created
# + content = "changed"
$ terraform destroy -auto-approve
# Error: Instance cannot be destroyed
# Resource random_password.master has lifecycle.prevent_destroy set, but the
# plan calls for this resource to be destroyed. ...
# [exit 1]10. OpenTofu state encryption (ran on the host)
# runs/17-tofu.txt (lab.sh exports TF_VAR_state_passphrase with a lab-only value)
$ tofu apply -auto-approve
# password_length = 24
$ jq -r 'keys | join(" ")' terraform.tfstate; jq -r '.encrypted_data | length' terraform.tfstate
# encrypted_data encryption_version lineage meta serial
# 1872
$ grep -c random_password terraform.tfstate
# 0
$ terraform init
# Error: Unsupported block type ... Blocks of type "encryption" are not expected here.
# (lab.sh: the next command runs with a wrong TF_VAR_state_passphrase)
$ tofu plan
# Error: Error acquiring the state lock
# Error message: failed to write backup file: decryption failed for all
# provided methods ... cipher: message authentication failed11. Go tests (ran on the host)
cd go && gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ok academy/infrastructure-as-code-terraform/appconfig <time>
# ok academy/infrastructure-as-code-terraform/planguard <time>
# ok academy/infrastructure-as-code-terraform/tfoutputs <time>
# (12 tests; testdata is the real output and plan JSON from steps 1 to 6)12. The real AWS run (expected, not run: needs an AWS account)
cd aws/bootstrap && terraform init && terraform apply # admin, once: state bucket + OIDC roles
# Apply complete! Resources: <n> added, 0 changed, 0 destroyed.
cd ../envs/staging && terraform init
# Successfully configured the backend "s3"! ...
terraform plan -out=tfplan
# Plan: <n> to add, 0 to change, 0 to destroy. (VPC, subnets, NAT, RDS, ElastiCache, ECS x4, S3, SES, SQS x2, IAM)
terraform show -json tfplan > plan.json
go -C ../../../go run ./cmd/planguard "$PWD/plan.json"
# terraform 1.17.2 plan: create=<n> moved=0 imported=0
terraform apply tfplan # RDS and ElastiCache take several minutes each
terraform output -json shop | jq '.laravel'
# { "bucket": "shop-staging-storage-<suffix>", "queue_name": "shop-staging-default", "dkim_tokens": [ "<t1>", "<t2>", "<t3>" ], ... }13. Linters, scanners, policy (expected, not run: tools not installed on the build host)
tflint --init && tflint --recursive # with the AWS ruleset plugin configured in .tflint.hcl
checkov -d aws --framework terraform # or: checkov -f plan.json (plan scan)
trivy config aws/ # misconfiguration scan
terraform show -json tfplan > tfplan.json && conftest test tfplan.json -p policy/ # OPA / Rego
terragrunt run --all plan # if the layout were Terragrunt unitsCommon misconceptions
| Belief | Reality |
|---|---|
sensitive = true keeps a value out of state | It only hides it in plan/apply output; state, plan files and output -json hold it in clear |
| State is just a cache of the cloud | It is the only mapping from addresses to real object IDs; without it Terraform cannot update or delete what it created |
| S3 state needs a DynamoDB table | use_lockfile = true (GA in 1.11) locks with an S3 object; dynamodb_table is deprecated |
terraform apply runs the plan I just looked at | Only apply tfplan does; a bare apply plans again, and a stale saved plan is refused |
| Renaming a block is harmless | The address is the identity: rename = destroy + create, unless a moved block says otherwise |
prevent_destroy makes a resource undeletable | Delete the block and the resource is destroyed; add provider deletion protection and plan checks |
ignore_changes freezes a field forever | It ignores diffs on an existing object; creation and replacement use the configured value (the lab recreated the file with the new content) |
count and for_each are interchangeable | count addresses by index, so removing an element shifts and rewrites later instances |
| Workspaces are environments | They share backend config and credentials; use directories (and accounts) for staging vs prod |
TF_VAR_x overrides tfvars files | It is the lowest-precedence source; -var / -var-file win, the last one on the command line |
terraform validate checks the cloud | It checks syntax, types and references only; invalid instance types need tflint or a plan |
| You cannot test Terraform without an account | terraform test with mock_provider (1.7+) plans and applies against fake providers |
-target is a way to deploy part of a stack | It is for exceptional recovery; routine use leaves the rest of the configuration unapplied |
| A failed apply rolls back | Terraform has no rollback; the state records what succeeded, the next plan shows the rest (CloudFormation does roll back) |
| Pulumi and CDK have no state | Pulumi keeps state in Pulumi Cloud or a DIY backend; CDK's state is the CloudFormation stack |
| OpenTofu is a drop-in Terraform forever | Same HCL and providers today; features diverge (state encryption, -exclude; HCP Terraform integration) |
| The BSL forbids production use | Production use is allowed; competing hosted/embedded offerings are not |
| Terraform should manage every Kubernetes Deployment | GitOps reconciles continuously; Terraform is better for the cluster and the cloud around it |
Cheat sheet
| Task | Command or code |
|---|---|
| Start a checkout | terraform init (CI: -input=false; modules only: -backend=false) |
| Upgrade providers within constraints | terraform init -upgrade and commit .terraform.lock.hcl |
| Format and validate | terraform fmt -check -recursive -diff && terraform validate |
| Plan and keep it | terraform plan -out=tfplan -detailed-exitcode (0 none, 1 error, 2 changes) |
| Read a plan as JSON | terraform show -json tfplan > plan.json |
| Apply exactly that plan | terraform apply tfplan |
| Force one recreation | terraform plan -replace='aws_instance.web[0]' |
| See drift / accept drift | terraform plan -refresh-only / terraform apply -refresh-only |
| List / show state | terraform state list, terraform state show 'ADDR', terraform state pull > backup.tfstate |
| Rename safely | moved { from = local_file.a to = local_file.b } |
| Adopt an object | import { to = aws_s3_bucket.x id = "bucket-name" } + terraform plan -generate-config-out=gen.tf |
| Forget without destroying | removed { from = ADDR lifecycle { destroy = false } } |
| Remove a stuck lock | terraform force-unlock LOCK_ID (only when the holder is gone) |
| S3 backend | backend "s3" { bucket, key, region, encrypt = true, use_lockfile = true } |
| Optional nested block | dynamic "x" { for_each = var.x == null ? [] : [var.x] content { ... } } |
| On/off resource | count = var.enabled ? 1 : 0, refer to x[0] |
| Swap without downtime | lifecycle { create_before_destroy = true } + name_prefix |
| Replace when something else changes | lifecycle { replace_triggered_by = [terraform_data.release] } |
| Unit test | run "x" { command = plan assert { condition = ... error_message = "..." } }, mock_provider "aws" {} |
| Outputs for programs | terraform output -json (secrets in clear), terraform output -raw name |
| Precedence (low to high) | TF_VAR_ < terraform.tfvars < terraform.tfvars.json < *.auto.tfvars < -var/-var-file (last wins) |
| CI credentials | permissions: id-token: write + aws-actions/configure-aws-credentials with role-to-assume |
| OpenTofu equivalent | tofu init / plan / apply / test; encryption { ... } for encrypted state |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What exactly is in the Terraform state file, and why does a "sensitive" output not keep a password safe? Must-know
Answer
Answer: State is JSON with version, terraform_version, serial, lineage, outputs, resources and check_results; every managed resource instance stores all its attributes, including computed ones, plus dependencies. sensitive = true only hides values in plan and apply output: the lab's state held the generated password three times (resource result, file content, output value) and the TLS key resource held the private key, and terraform output -json printed the password in clear. Keep secrets out (service-managed secrets, write-only arguments, ephemeral values) and protect the state backend as a secret store. See State.
2 — Two engineers run terraform apply on the same S3 state at the same time. What prevents damage, and how do you configure it today? Must-know
Answer
Answer: State locking: the first run takes the lock, the second gets "Error acquiring the state lock" (or waits with -lock-timeout). For the S3 backend, use_lockfile = true (generally available since Terraform 1.11) writes a <key>.tflock object with a conditional request; the older dynamodb_table lock with a LockID partition key is deprecated. Add bucket versioning to recover old states, and in CI a concurrency group per environment so applies queue. See Remote backends.
3 — You rename aws_db_instance.db to aws_db_instance.postgres. What does the next plan do, and what is the right fix? Must-know
Answer
Answer: Terraform sees a resource whose address is no longer in the configuration and a new one that is not in state, so it plans to destroy the database and create a new one. Add moved { from = aws_db_instance.db to = aws_db_instance.postgres }; the plan then reports "has moved to" with no changes (the lab showed Plan: 0 to add, 0 to change, 0 to destroy.). terraform state mv works too but is unreviewed and per environment; deletion protection and a plan guard catch the mistake if both are forgotten. See Refactoring state.
4 — Why should CI apply a saved plan file, and what happens if the state changed after the plan? Must-know
Answer
Answer: A bare terraform apply computes a new plan, which can differ from the one reviewed if code or reality changed in between. plan -out=tfplan followed by apply tfplan executes exactly the reviewed actions; if any other operation wrote the state in between, Terraform refuses with "Error: Saved plan is stale" and you plan again. The plan file contains values from state, so it is stored as a short-lived artefact, never committed. See The core workflow.
5 — Design plan-on-PR / apply-on-merge for two environments in GitHub Actions without long-lived AWS keys. Must-know
Answer
Answer: On pull requests, a job per environment with id-token: write assumes a read-only plan role via OIDC (configure-aws-credentials, trust on token.actions.githubusercontent.com:aud = sts.amazonaws.com and :sub = repo:ORG/REPO:pull_request), runs init, validate, plan -out, a policy check on show -json, and posts the plan as a comment. On merge, plan again on main, upload the plan file as an artefact, and apply it in a job bound to a protected GitHub environment (required reviewers for prod) using an apply role trusted only for environment:prod, with a concurrency group that queues rather than cancels. See CI for infrastructure.
6 — count or for_each for one subnet per availability zone, and why? Important
Answer
Answer: for_each over a map keyed by AZ name. With count, instances are [0], [1], [2]; removing or reordering an AZ shifts indexes and Terraform plans to modify or replace subnets that did not change, which cascades to everything in them. With for_each each subnet is ["eu-central-1a"] and only the added or removed key changes. Keep count for 0/1 toggles; migrate existing count resources with moved blocks per instance. See Repetition.
7 — What is drift, how do you detect it, and when should you not "fix" it? Important
Answer
Answer: Drift is a difference between real objects and the recorded state made outside Terraform: a console edit, another tool, an autoscaler. Every plan refreshes and shows it; terraform plan -refresh-only shows only that, apply -refresh-only accepts it into state, and a normal apply reverts to the code. Schedule plan -detailed-exitcode to find it. Do not revert values another system owns (ECS desired_count under autoscaling, AWS-applied minor engine versions): declare that with ignore_changes. See Drift.
8 — Directory per environment or CLI workspaces? Important
Answer
Answer: For staging and prod, directories (thin root modules calling shared modules), each with its own backend key, variables, provider settings such as allowed_account_ids, and CI credentials. Workspaces share one backend configuration and the same credentials, which the Terraform docs call not appropriate for deployments "requiring separate credentials and access controls", and a wrong workspace select targets prod. Workspaces fit short-lived copies like PR environments; Terragrunt helps when there are many units per environment. See Environments.
9 — How do you test a Terraform module that creates AWS resources without an AWS account, and what are the limits? Important
Answer
Answer: terraform test with mock_provider "aws" {} (Terraform 1.7+): resources get fake computed values, so run blocks with command = plan or apply can assert on outputs, counts and validations, and expect_failures checks that bad inputs are rejected. Limits seen in this chapter: random strings for JSON attributes break plan-time validation (fixed with mock_data defaults), and computed nested blocks stay empty, so code must handle that (one(...[*].tokens)). Mocks test your logic, not AWS: a real plan in CI and policy scans (Checkov, Trivy, OPA) are still needed. See Testing.
10 — When would you choose Pulumi, AWS CDK or CloudFormation instead of Terraform? Important
Answer
Answer: Pulumi when the team wants a general-purpose language (TypeScript, Python, Go) with its tooling and tests, accepting Pulumi Cloud or a DIY backend for state. AWS CDK when the system is AWS-only and the team wants high-level constructs plus CloudFormation's managed state, change sets and automatic rollback (cdk synth produces the templates). Plain CloudFormation for simple or generated templates and StackSets across many accounts. Terraform or OpenTofu when several clouds and SaaS APIs must be managed with one workflow. See The alternatives.
11 — What changed with Terraform's license in 2023, and what does OpenTofu offer that Terraform does not? Good to know
Answer
Answer: On 10 August 2023 HashiCorp moved Terraform from MPL 2.0 to the Business Source License 1.1, effective for Terraform 1.6.0 and later; production use stays allowed, competing hosted or embedded offerings do not. The community forked the MPL code as OpenTofu (Linux Foundation, announced 20 September 2023, 1.6.0 stable in January 2024). OpenTofu reads the same HCL and providers and adds features such as client-side state and plan encryption (1.7) and -exclude (1.10); Terraform has HCP Terraform integration and its own newer additions. See Licensing and OpenTofu.
12 — Should Terraform manage the Kubernetes workloads on an EKS cluster it creates? Good to know
Answer
Answer: Usually only up to the GitOps controller. Terraform is good at the cluster, node groups, IAM roles for service accounts, databases and DNS, and can bootstrap Argo CD or Flux with the helm provider; workloads are better owned by GitOps, which reconciles continuously, corrects drift and understands rollouts. Managing every Deployment with the kubernetes provider means changes only happen at apply, CRDs must exist before plans that use them, and providers configured from a cluster created in the same run hit ordering problems. See Terraform and Kubernetes.
Glossary
| Term | Meaning |
|---|---|
| Infrastructure as Code (IaC) | Describing infrastructure in versioned files that a tool turns into real resources |
| Declarative | Describing the desired end state; the tool computes the steps |
| Imperative | Describing the steps; re-runs and deletes are your code's job |
| Idempotent | Applying the same configuration again changes nothing |
| Drift | Differences between real objects and recorded state made outside the tool |
| Drift detection | Finding drift: refresh on every plan, plan -refresh-only, scheduled plans, CloudFormation drift detection |
| Immutable infrastructure | Replacing objects (new image, new task definition revision) instead of changing them in place |
| HCL | HashiCorp Configuration Language: blocks, arguments, expressions |
| Provider | A plugin that implements resource types for one API (hashicorp/aws) |
| Terraform Registry | registry.terraform.io: public providers and modules (OpenTofu: registry.opentofu.org) |
| Dependency lock file | .terraform.lock.hcl: exact provider versions and hashes, committed to Git |
| Resource | A managed object declared with resource "type" "name" |
| Data source | A read-only lookup declared with data "type" "name" |
| Address | The identity of a resource instance in state, e.g. module.data.aws_db_instance.postgres |
| Variable | A module input (variable block) with type, default, validation |
| Locals | Named intermediate values (locals block, local.x) |
| Output | A value a module returns; root outputs are shown by terraform output |
| tfvars | Files assigning variable values (terraform.tfvars, *.auto.tfvars, -var-file) |
| Variable precedence | TF_VAR_ < terraform.tfvars < .tfvars.json < *.auto.tfvars < -var / -var-file |
| count | Meta-argument creating N instances addressed by index |
| for_each | Meta-argument creating one instance per map key or set element |
| Dynamic block | dynamic "name" { for_each, content }: repeated nested blocks |
| Lifecycle | Meta-argument block: create_before_destroy, prevent_destroy, ignore_changes, replace_triggered_by |
| create_before_destroy | Create the replacement before destroying the old object |
| prevent_destroy | Reject plans that would destroy the object (while the block exists) |
| ignore_changes | Ignore diffs on listed attributes after creation |
| Provisioner | local-exec / remote-exec / file scripts at create or destroy; a last resort |
| terraform init | Install providers and modules, configure the backend |
| terraform validate | Static check of syntax, types and references |
| terraform fmt | Rewrite files in canonical style; -check for CI |
| terraform plan | Refresh and diff; -out saves a plan file |
| terraform apply | Execute a plan (saved or fresh) |
| terraform destroy | Plan and apply the deletion of everything in the state |
| Plan file | Binary saved plan (-out=tfplan), applied with apply tfplan; holds values in clear |
| Plan artifact | The plan file uploaded by CI between the plan job and the apply job |
| -target / -replace | Limit a plan to some addresses (exceptional) / force recreation of one |
| State file | terraform.tfstate: mapping from addresses to real objects with attributes |
| Serial / lineage | Write counter / identity of a state's history |
| Remote backend | Shared state storage: S3, GCS, azurerm, HCP Terraform and others |
| S3 backend | State in an S3 object; locking with use_lockfile (or deprecated DynamoDB lock) |
| use_lockfile | S3 backend argument for S3-native locking (<key>.tflock), GA in 1.11 |
| DynamoDB lock | Legacy S3 locking via a table with partition key LockID; deprecated |
| GCS backend / azurerm backend | State in Google Cloud Storage / Azure Blob Storage with native locking |
| HCP Terraform | HashiCorp's managed service: remote state, runs, policies, private registry |
| State locking | Exclusive lock around operations that could write state |
| terraform state mv / rm | Imperative state edits: move an address / forget an object |
| Import block | import { to, id }: plannable adoption of an existing object (1.5+) |
| Moved block | moved { from, to }: planned address change (1.1+) |
| Removed block | removed { from, lifecycle { destroy = false } }: forget without destroying (1.7+) |
| Refresh-only | Plan/apply mode that only syncs state with reality |
| Module | A directory of .tf files with inputs and outputs |
| Root module | The directory Terraform runs in; owns backend and providers |
| Module source / version | Where a module comes from (path, registry, Git) / SemVer constraint for registry modules |
| Module composition | Building a system by wiring module outputs into other modules' inputs |
| Workspaces | Several states for one configuration and backend |
| Directory per environment | One root module per environment calling shared modules |
| Terragrunt | Wrapper generating backends and providers, with dependencies and run --all |
| terraform test | Test runner for .tftest.hcl files with run blocks and assertions (1.6+) |
| mock_provider | Fake provider for tests without credentials (1.7+) |
| tflint | Pluggable Terraform linter with provider rule sets |
| Checkov / Trivy | Static security scanners for IaC code and plans |
| OPA / Sentinel | Policy as code: Rego (via conftest or HCP Terraform) / HashiCorp's policy language |
| OIDC | Federated short-lived credentials for CI (GitHub token exchanged for an AWS role session) |
| sensitive | Flag that hides a value in output; not an encryption |
| ephemeral | Values and resources never stored in plan or state (1.10+) |
| Write-only argument | Provider argument not persisted in state (password_wo, 1.11+) |
| Vault provider | hashicorp/vault: reads and writes HashiCorp Vault secrets |
| Secrets in state | Any secret Terraform reads or generates ends up in state unless ephemeral or write-only |
| BSL license | Business Source License 1.1: Terraform's license since 1.6.0 |
| OpenTofu | MPL-licensed fork of Terraform under the Linux Foundation (tofu) |
| State encryption | OpenTofu's client-side encryption of state and plan files |
| Pulumi / Pulumi state | IaC in general-purpose languages / stack state in Pulumi Cloud or a DIY backend |
| AWS CDK / synth | Constructs in code / cdk synth producing CloudFormation templates in a cloud assembly |
| CloudFormation stack | AWS-managed unit of resources created from a template |
| Change set | CloudFormation preview of a stack update, executed on demand |
| CloudFormation drift | Drift detection on stacks: IN_SYNC, MODIFIED, DELETED, NOT_CHECKED; stack DRIFTED |
| Bicep / ARM templates | Azure's DSL / the JSON templates it compiles to, deployed by Resource Manager |
| Crossplane | Kubernetes-based control plane managing cloud resources as custom resources |
| kubernetes provider / helm provider | Terraform providers for Kubernetes objects / Helm releases |
| planguard | This chapter's Go tool: summarises plan JSON and blocks protected deletes |
References
- Terraform docs: intro https://developer.hashicorp.com/terraform/intro — syntax https://developer.hashicorp.com/terraform/language/syntax/configuration — providers https://developer.hashicorp.com/terraform/language/providers — resource behavior https://developer.hashicorp.com/terraform/language/resources/behavior — lifecycle https://developer.hashicorp.com/terraform/language/meta-arguments/lifecycle — for_each https://developer.hashicorp.com/terraform/language/meta-arguments/for_each — count https://developer.hashicorp.com/terraform/language/meta-arguments/count — data sources https://developer.hashicorp.com/terraform/language/data-sources — dynamic blocks https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks — functions https://developer.hashicorp.com/terraform/language/functions — provisioners https://developer.hashicorp.com/terraform/language/resources/provisioners/syntax
- Terraform values: variables (and precedence) https://developer.hashicorp.com/terraform/language/values/variables — locals https://developer.hashicorp.com/terraform/language/values/locals — outputs https://developer.hashicorp.com/terraform/language/values/outputs — sensitive data https://developer.hashicorp.com/terraform/language/manage-sensitive-data — ephemeral https://developer.hashicorp.com/terraform/language/manage-sensitive-data/ephemeral — write-only https://developer.hashicorp.com/terraform/language/manage-sensitive-data/write-only — ephemeral resources https://developer.hashicorp.com/terraform/language/resources/ephemeral
- Terraform modules: overview https://developer.hashicorp.com/terraform/language/modules — sources https://developer.hashicorp.com/terraform/language/modules/sources — develop https://developer.hashicorp.com/terraform/language/modules/develop — composition https://developer.hashicorp.com/terraform/language/modules/develop/composition — refactoring https://developer.hashicorp.com/terraform/language/modules/develop/refactoring
- Terraform state: state https://developer.hashicorp.com/terraform/language/state — purpose https://developer.hashicorp.com/terraform/language/state/purpose — locking https://developer.hashicorp.com/terraform/language/state/locking — sensitive data in state https://developer.hashicorp.com/terraform/language/state/sensitive-data — remote state https://developer.hashicorp.com/terraform/language/state/remote — workspaces https://developer.hashicorp.com/terraform/language/state/workspaces — backends https://developer.hashicorp.com/terraform/language/backend — S3 backend https://developer.hashicorp.com/terraform/language/backend/s3 — GCS https://developer.hashicorp.com/terraform/language/backend/gcs — azurerm https://developer.hashicorp.com/terraform/language/backend/azurerm — import https://developer.hashicorp.com/terraform/language/import — moved https://developer.hashicorp.com/terraform/language/moved — removing resources https://developer.hashicorp.com/terraform/language/resources/syntax
- Terraform tests: https://developer.hashicorp.com/terraform/language/tests — mocking https://developer.hashicorp.com/terraform/language/tests/mocking
- Terraform CLI: init https://developer.hashicorp.com/terraform/cli/commands/init — plan https://developer.hashicorp.com/terraform/cli/commands/plan — apply https://developer.hashicorp.com/terraform/cli/commands/apply — destroy https://developer.hashicorp.com/terraform/cli/commands/destroy — state https://developer.hashicorp.com/terraform/cli/commands/state — state mv https://developer.hashicorp.com/terraform/cli/commands/state/mv — state rm https://developer.hashicorp.com/terraform/cli/commands/state/rm — import https://developer.hashicorp.com/terraform/cli/commands/import — taint https://developer.hashicorp.com/terraform/cli/commands/taint — output https://developer.hashicorp.com/terraform/cli/commands/output — fmt https://developer.hashicorp.com/terraform/cli/commands/fmt — validate https://developer.hashicorp.com/terraform/cli/commands/validate — test https://developer.hashicorp.com/terraform/cli/commands/test — workspaces https://developer.hashicorp.com/terraform/cli/workspaces — JSON output format https://developer.hashicorp.com/terraform/internals/json-format — automation https://developer.hashicorp.com/terraform/tutorials/automation/automate-terraform — HCP Terraform https://developer.hashicorp.com/terraform/cloud-docs
- Terraform history: CHANGELOGs v1.0 https://raw.githubusercontent.com/hashicorp/terraform/v1.0/CHANGELOG.md — v1.1 https://raw.githubusercontent.com/hashicorp/terraform/v1.1/CHANGELOG.md — v1.5 https://raw.githubusercontent.com/hashicorp/terraform/v1.5/CHANGELOG.md — v1.6 https://raw.githubusercontent.com/hashicorp/terraform/v1.6/CHANGELOG.md — v1.7 https://raw.githubusercontent.com/hashicorp/terraform/v1.7/CHANGELOG.md — v1.10 https://raw.githubusercontent.com/hashicorp/terraform/v1.10/CHANGELOG.md — v1.11 https://raw.githubusercontent.com/hashicorp/terraform/v1.11/CHANGELOG.md — releases v0.1.0 https://github.com/hashicorp/terraform/releases/tag/v0.1.0 and v1.6.0 https://github.com/hashicorp/terraform/releases/tag/v1.6.0 — LICENSE (BSL) https://raw.githubusercontent.com/hashicorp/terraform/main/LICENSE — LICENSE at v1.5 (MPL) https://raw.githubusercontent.com/hashicorp/terraform/v1.5/LICENSE
- OpenTofu: intro https://opentofu.org/docs/intro/ — migration https://opentofu.org/docs/intro/migration/ — what's new 1.7 https://opentofu.org/docs/v1.7/intro/whats-new/ — what's new 1.10 https://opentofu.org/docs/v1.10/intro/whats-new/ — state encryption https://opentofu.org/docs/language/state/encryption/ — 1.7.0 blog https://opentofu.org/blog/opentofu-1-7-0/ — manifesto https://opentofu.org/manifesto/ — release v1.6.0 https://github.com/opentofu/opentofu/releases/tag/v1.6.0 — Linux Foundation announcement https://www.linuxfoundation.org/press/announcing-opentofu
- Tools: Terragrunt https://terragrunt.gruntwork.io/docs/ — tflint https://raw.githubusercontent.com/terraform-linters/tflint/master/README.md — Checkov https://raw.githubusercontent.com/bridgecrewio/checkov/main/README.md — Trivy Terraform scanning https://trivy.dev/latest/docs/coverage/iac/terraform/ — OPA and Terraform https://www.openpolicyagent.org/docs/terraform — Sentinel and Terraform https://developer.hashicorp.com/sentinel/docs/terraform — Atlantis https://www.runatlantis.io/docs/ — GitLab IaC integration https://docs.gitlab.com/user/infrastructure/iac/ — terraform-exec https://raw.githubusercontent.com/hashicorp/terraform-exec/main/README.md — terraform-json https://raw.githubusercontent.com/hashicorp/terraform-json/main/README.md — Terratest https://raw.githubusercontent.com/gruntwork-io/terratest/main/README.md
- Alternatives: Pulumi concepts https://www.pulumi.com/docs/iac/concepts/ — how Pulumi works https://www.pulumi.com/docs/iac/concepts/how-pulumi-works/ — Pulumi state and backends https://www.pulumi.com/docs/iac/concepts/state-and-backends/ — AWS CDK guide https://docs.aws.amazon.com/cdk/v2/guide/home.html — CDK apps https://docs.aws.amazon.com/cdk/v2/guide/apps.html —
cdk synthhttps://docs.aws.amazon.com/cdk/v2/guide/ref-cli-cmd-synth.html — CloudFormation stacks https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacks.html — change sets https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets.html — drift https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html — CloudFormation launch https://aws.amazon.com/about-aws/whats-new/2011/02/25/introducing-aws-cloudformation/ — Bicep https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/overview — ARM templates https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/overview — Crossplane https://docs.crossplane.io/latest/whats-crossplane/ — Ansible https://docs.ansible.com/ansible/latest/getting_started/introduction.html - Providers (docs sources on GitHub): AWS provider https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/index.html.markdown — aws_vpc https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/vpc.html.markdown — aws_subnet https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/subnet.html.markdown — aws_db_instance https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/db_instance.html.markdown — aws_elasticache_replication_group https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/elasticache_replication_group.html.markdown — aws_s3_bucket https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/s3_bucket.html.markdown — aws_sesv2_email_identity https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/sesv2_email_identity.html.markdown — aws_sqs_queue https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/sqs_queue.html.markdown — aws_ecs_service https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/ecs_service.html.markdown — aws_ecs_task_definition https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/ecs_task_definition.html.markdown — VPC module https://raw.githubusercontent.com/terraform-aws-modules/terraform-aws-vpc/master/README.md — kubernetes provider https://raw.githubusercontent.com/hashicorp/terraform-provider-kubernetes/main/docs/index.md — helm provider https://raw.githubusercontent.com/hashicorp/terraform-provider-helm/main/docs/index.md — Vault provider https://raw.githubusercontent.com/hashicorp/terraform-provider-vault/main/website/docs/index.html.markdown — local_file https://raw.githubusercontent.com/hashicorp/terraform-provider-local/main/docs/resources/file.md — random_password https://raw.githubusercontent.com/hashicorp/terraform-provider-random/main/docs/resources/password.md — random_integer https://raw.githubusercontent.com/hashicorp/terraform-provider-random/main/docs/resources/integer.md — tls_private_key https://raw.githubusercontent.com/hashicorp/terraform-provider-tls/main/docs/resources/private_key.md
- CI: GitHub OIDC in AWS https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws — setup-terraform https://raw.githubusercontent.com/hashicorp/setup-terraform/main/README.md — configure-aws-credentials https://raw.githubusercontent.com/aws-actions/configure-aws-credentials/main/README.md — checkout https://raw.githubusercontent.com/actions/checkout/main/README.md — setup-go https://raw.githubusercontent.com/actions/setup-go/main/README.md — upload-artifact https://raw.githubusercontent.com/actions/upload-artifact/main/README.md — download-artifact https://raw.githubusercontent.com/actions/download-artifact/main/README.md — github-script https://raw.githubusercontent.com/actions/github-script/main/README.md
- Laravel 13.x: filesystem (S3) https://laravel.com/docs/13.x/filesystem — mail (SES) https://laravel.com/docs/13.x/mail — queues (SQS, retry_after) https://laravel.com/docs/13.x/queues — SqsConnector source https://raw.githubusercontent.com/laravel/framework/13.x/src/Illuminate/Queue/Connectors/SqsConnector.php
- Go:
encoding/jsondecode https://go.dev/src/encoding/json/decode.go — stream (RawMessage) https://go.dev/src/encoding/json/stream.go