The Terraform practices that matter most are about state and change control. Keep state in a remote backend with locking and versioning, split it so that one plan can't touch everything, pin Terraform and provider versions and commit the lock file, keep secrets out of state, and apply only plans a person has reviewed, from CI rather than from someone's laptop. Naming, module layout and tests matter too, but they are far easier to fix later than one state file that holds everything you run.
The examples use AWS, Terraform 1.16 (1.16.6 is the current release; 1.17 is at release candidate) and version 6 of the AWS provider. The rules carry over to Google Cloud, Azure or any other provider.
Keep state remote, locked and versioned
Terraform's state file maps every resource in your code to a real object: the bucket's name, the role's ARN, and every attribute the provider returned. Terraform reads it on every plan to work out what has changed. Two things follow. If two people apply against the same state at the same moment they can corrupt it, so you need locking. And because state stores attributes in plain text, it often holds database passwords, private keys and connection strings, so it deserves the same care as a secrets store.
The S3 backend now handles locking on its own. Since Terraform 1.11 it writes a lock file next to the state object, and the DynamoDB table that older tutorials tell you to create is deprecated; the S3 backend documentation says DynamoDB locking will be removed in a future minor version. A current backend block:
terraform {
backend "s3" {
bucket = "acme-terraform-state"
key = "production/app/terraform.tfstate"
region = "eu-central-1"
encrypt = true
use_lockfile = true
}
}Turn on versioning for the bucket, so that a bad apply or an accidental delete can be rolled back to the previous state object, and block public access. The identity that runs Terraform needs s3:ListBucket on the bucket, s3:GetObject and s3:PutObject on the state key, and those two plus s3:DeleteObject on the .tflock object next to it. If you are moving off DynamoDB, set use_lockfile = true next to the existing dynamodb_table for a while: Terraform takes both locks, and you delete the table once every pipeline and laptop runs 1.11 or later.
The Google Cloud Storage and Azure Blob Storage backends lock natively, so there is nothing extra to configure there. If you'd rather not run a bucket at all, HCP Terraform stores and locks state for you and has a free tier.
Keep these out of Git: *.tfstate files and their backups, the .terraform/ directory, saved plan files and any .tfvars file with secrets in it. Do commit .terraform.lock.hcl; the section on versions explains why.
Split state by environment and by blast radius
Most teams start with one state for everything, and it gets slow and risky at about the same rate. Every plan refreshes every resource in the state, so plans slow down as it grows, and a typo in a DNS record lands in the same plan as your production database. Google's Terraform guidance gives a number: no more than 100 resources in a single state, and ideally only a few dozen.
Split first by environment, then by how often things change and how much a mistake would cost. A layout that holds up:
infra/
modules/
network/
service/
envs/
staging/
network/
app/
production/
network/
app/Each directory under envs/ is a root module with its own backend key and variables, and it mostly contains module blocks that call into modules/. Networking changes rarely and takes everything down when it goes wrong, so it gets a state of its own. Application services change every week and get theirs.
Should you use workspaces for environments instead? With the plain CLI, our answer is no: use directories. CLI workspaces share one backend and one set of credentials, which is exactly what you don't want between staging and production, and HashiCorp's own workspace documentation recommends other approaches for deployments that need separate credentials and access controls. HCP Terraform workspaces are a different thing (each has its own state, variables and permissions), and one per environment works well there.
When one state needs a value from another, such as the app needing the VPC ID, look it up with a data source (find the VPC by its tags) instead of reading the other state with terraform_remote_state. Reading remote state requires access to the whole snapshot, which often includes secrets, and it couples the two configurations tightly.
Two provider settings make the classic wrong-account mistake much harder:
provider "aws" {
region = "eu-central-1"
allowed_account_ids = ["111111111111"] # production account only
default_tags {
tags = {
environment = "production"
managed_by = "terraform"
repository = "acme/infra"
}
}
}allowed_account_ids stops Terraform at the start of a plan if the credentials belong to any other AWS account, so staging code run with production credentials fails straight away. default_tags labels everything Terraform creates, which pays off during an audit: a resource without managed_by = "terraform" was made by hand. Since version 6 of the AWS provider, most resources also accept their own region argument, so a second region no longer needs a second provider block.
Pin versions and commit the lock file
Three things can change under you: the Terraform CLI, the providers and the modules. Pin each one on purpose.
terraform {
required_version = ">= 1.11, < 2.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
random = {
source = "hashicorp/random"
version = "~> 3.7"
}
}
}~> 6.0 accepts any 6.x release of the AWS provider and refuses 7.0, which is where breaking changes will arrive. The exact version that gets installed is recorded with its checksums in .terraform.lock.hcl the first time you run terraform init, and that file is what makes your laptop and CI use the same provider build. If the team works on Macs and CI runs on Linux, record checksums for both platforms up front, so the lock file doesn't change depending on who ran init last:
terraform providers lock -platform=darwin_arm64 -platform=linux_amd64Upgrades then become ordinary pull requests: run terraform init -upgrade, read the provider's changelog, look at the plan, merge. Dependabot and Renovate can open those pull requests for you. In CI, install one exact CLI version (the workflow below uses 1.16.6) and change it deliberately, because a plan saved by one version can't be applied by another.
Registry modules take a version argument, and the HashiCorp style guide recommends pinning them to a major and minor version. Modules from Git take a tag in the source address, such as ?ref=v1.4.0. A module without a version can be different code every time someone runs init.
Write modules that earn their place
A module is worth writing when it stands for something you deploy more than once: a service with its load balancer target group, log group and alarms, or a network laid out the way your company does it. A module that wraps a single resource and passes every argument straight through only adds a layer to read. Write the resource directly.
Inside modules, a few habits prevent most of the damage:
- Give every variable a
typeand adescription, and add avalidationblock wherever a wrong value would be expensive, such as an environment name or a region. - Use
for_eachover a map or a set for anything that has a name. Withcount, removing the second item of a list shifts the index of everything after it, and Terraform plans to destroy and recreate those resources. - Refactor with
movedblocks (example below). Without one, renaming a resource or moving it into a module looks to Terraform like a delete followed by a create. - Put
prevent_destroy = truein thelifecycleblock of anything you can't recreate, such as databases, the state bucket and KMS keys. Terraform then rejects any plan that would delete them. To stop managing a resource without deleting it, for example when it moves to another state, use aremovedblock withlifecycle { destroy = false }.
moved {
from = aws_s3_bucket.uploads
to = module.storage.aws_s3_bucket.uploads
}Follow the style guide for file names (terraform.tf, providers.tf, main.tf, variables.tf, outputs.tf) and run terraform fmt -check in CI, so formatting never comes up in code review.
Keep secrets out of state
sensitive = true on a variable or output hides the value from CLI output, and that is all it does. The value is still written to state in plain text, as the style guide itself points out. There are two better options.
Where the service supports it, let the service own the secret. For RDS, manage_master_user_password = true makes AWS generate the master password and keep it in Secrets Manager, and Terraform never sees it.
When Terraform has to set the secret itself, combine an ephemeral value with a write-only argument, which needs Terraform 1.11 or later. Ephemeral values exist only while Terraform runs, and write-only arguments (their names end in _wo) are passed to the provider and never saved to the plan or the state. This follows the pattern in HashiCorp's documentation and needs version 3.7 or later of the random provider:
ephemeral "random_password" "db" {
length = 32
special = false
}
resource "aws_secretsmanager_secret" "db" {
name = "production/app/db-password"
}
resource "aws_secretsmanager_secret_version" "db" {
secret_id = aws_secretsmanager_secret.db.id
secret_string_wo = ephemeral.random_password.db.result
secret_string_wo_version = 1
}
ephemeral "aws_secretsmanager_secret_version" "db" {
secret_id = aws_secretsmanager_secret_version.db.secret_id
}
resource "aws_db_instance" "app" {
identifier = "app-production"
engine = "postgres"
instance_class = "db.t4g.medium"
allocated_storage = 50
username = "app"
password_wo = ephemeral.aws_secretsmanager_secret_version.db.secret_string
password_wo_version = aws_secretsmanager_secret_version.db.secret_string_wo_version
lifecycle {
prevent_destroy = true
}
}The password is generated, stored in Secrets Manager and handed to RDS, and it appears in neither the plan nor the state. Only the version numbers are stored, and they are how Terraform knows when to rotate: increase secret_string_wo_version by one and apply. The detour through Secrets Manager has a reason. If you passed the ephemeral password straight to the database, the database would work and nobody would know its password.
Apply only the plan someone reviewed
A person reads the plan, and exactly that plan gets applied. Running terraform apply without a plan file breaks this, because it computes a fresh plan, so anything that changed since the review gets applied without anyone reading it. Saving the plan with -out and applying that file closes the gap. If the state changes in between, Terraform rejects the saved plan as stale and you plan again, which is the behaviour you want.
Running Terraform from CI rather than laptops gives you one CLI version, one set of credentials and a record of who approved what. The workflow below handles one root module on GitHub Actions. A pull request gets a plan. A merge to main produces a plan, waits for approval on the production environment, then applies the saved file. AWS credentials come through OIDC, so no access keys are stored in GitHub.
name: terraform-production-app
on:
pull_request:
paths: ["infra/envs/production/app/**", "infra/modules/**"]
push:
branches: [main]
paths: ["infra/envs/production/app/**", "infra/modules/**"]
permissions:
contents: read
id-token: write # lets jobs request an OIDC token for AWS
concurrency:
# One queue per branch. Never cancel a run on main; do cancel stale PR plans.
group: terraform-production-app-${{ github.head_ref || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
defaults:
run:
working-directory: infra/envs/production/app
env:
TF_IN_AUTOMATION: "true"
TF_INPUT: "false"
jobs:
plan:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
with:
terraform_version: 1.16.6
terraform_wrapper: false
- uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
with:
role-to-assume: ${{ vars.TF_PLAN_ROLE_ARN }}
aws-region: eu-central-1
- run: terraform init
- run: terraform validate
- run: terraform plan -lock-timeout=5m -out=tfplan
- if: github.event_name == 'push'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: tfplan
path: infra/envs/production/app/tfplan
retention-days: 1
apply:
needs: plan
if: github.event_name == 'push'
runs-on: ubuntu-24.04
environment: production # required reviewers approve here
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
with:
terraform_version: 1.16.6
terraform_wrapper: false
- uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
with:
role-to-assume: ${{ vars.TF_APPLY_ROLE_ARN }}
aws-region: eu-central-1
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: tfplan
path: infra/envs/production/app
- run: terraform init
- run: terraform apply -lock-timeout=5m tfplanThe plan and apply jobs assume different IAM roles. The plan role can read the account and the state and write the lock file. The apply role can change things, and its trust policy should accept only tokens whose subject is repo:<org>/<repo>:environment:production, so only a job that has passed the approval gate can assume it. Check that string against the age of your repository: repositories created after 15 July 2026 get subjects that carry the owner and repository IDs (repo:<org>@<org-id>/<repo>@<repo-id>:environment:production), and a trust policy written for the old format refuses their tokens. Our GitHub Actions post covers OIDC trust policies in more depth.
Reviewers read the plan in the plan job's log before they approve. The plan file contains state and variable values, so the artifact is kept for one day; if nobody approves within that day, the download step fails and you re-run the workflow, which gets you a fresh plan anyway. The concurrency settings stop two runs on main from applying at once and never cancel one halfway, while a new commit on a pull request cancels that branch's older plan. Plan and apply both wait up to five minutes for the state lock, so a drift check that happens to be running (see below) doesn't fail a deploy.
One limitation to know before you rely on this: on GitHub's Free, Pro and Team plans, required reviewers on environments only work in public repositories. A private repository on those plans needs a different approval step, for example running applies through HCP Terraform, which asks for confirmation before it applies unless you turn on auto-apply.
Check the code before anyone reads the plan
Cheap checks catch most mistakes before a person spends time on the plan. terraform fmt -check -recursive and terraform validate take seconds. TFLint, with the ruleset for your provider, finds things like invalid instance types and unused variables. Trivy (trivy config, which absorbed the older tfsec) and Checkov flag misconfigurations such as public buckets, security groups open to the world and unencrypted volumes. Pick one of the two scanners, and set aside an afternoon to decide which findings to suppress.
Run the scanners in a separate job without cloud credentials: give it permissions: contents: read and no id-token: write. In March 2026 attackers force-pushed malicious code to almost every version tag of Trivy's own GitHub Action, and the payload collected secrets from the runner before running a normal scan. Aqua's advisory treats every workflow that referenced the action by a version tag as potentially compromised and calls pinning to a full commit SHA the only reliable protection. That is why every action in the workflow above is pinned to a SHA: those jobs hold credentials that can change your whole account. A scan job without cloud credentials has little to hand over beyond a read-only GitHub token. Our DevSecOps post goes into wiring scanners into a pipeline.
For modules, the built-in terraform test command (available since 1.6) is enough for most teams. With command = plan and a mocked provider (since 1.7), tests finish in seconds and need no cloud account. For a module that names its ECS service <name>-<environment>, a test file at modules/service/tests/service.tftest.hcl could look like this:
mock_provider "aws" {}
variables {
name = "billing"
environment = "staging"
}
run "service_name_includes_environment" {
command = plan
assert {
condition = aws_ecs_service.this.name == "billing-staging"
error_message = "Service names must follow <name>-<environment>."
}
}
run "rejects_unknown_environment" {
command = plan
variables {
environment = "prod2"
}
expect_failures = [var.environment]
}Tests that use the default command = apply create real infrastructure and destroy it afterwards. For a module that many teams depend on they are worth running against a sandbox account, but they are slow and cost money, so keep them out of the pull request path.
Catch drift, and stop clicking in the console
Drift is the gap between your code and what is really running, and it usually starts with someone fixing something by hand during an incident. A scheduled job that runs a plan every morning and fails when there are changes will find it:
terraform plan -detailed-exitcode -lock-timeout=5mWith -detailed-exitcode the command exits with 0 when nothing changed, 1 on an error and 2 when the real infrastructure differs from the code, so the job goes red on drift. When it does, decide which side is right. If the manual change was a mistake, apply the code and the change is reverted. If it was right, update the code until the plan is empty again. terraform apply -refresh-only only updates the state to match reality and leaves your code untouched, so on its own it just postpones the decision. HCP Terraform can run these checks for you on its paid Standard and Premium editions.
For resources that were created by hand and never managed, use an import block (Terraform 1.5 and later) and let Terraform write a first draft of the configuration with terraform plan -generate-config-out=generated.tf. Treat that file as a draft: it lists every attribute, including defaults you don't want to pin.
Terraform or OpenTofu?
In August 2023 HashiCorp moved Terraform from the open-source MPL 2.0 licence to the Business Source License (BSL). OpenTofu, the community fork started in response, kept MPL 2.0 and became a CNCF sandbox project in April 2025, and IBM completed its acquisition of HashiCorp in February 2025. For a company running its own infrastructure, the BSL changes nothing in practice; its restriction applies to products that compete with HashiCorp's.
The two tools are still close, and both now support ephemeral values and write-only arguments, but they are moving apart. OpenTofu has client-side state encryption (since 1.7), for_each on provider blocks (since 1.9) and an enabled lifecycle argument (since 1.11). Terraform has Stacks, action blocks, terraform query for finding existing resources (since 1.14) and its integration with HCP Terraform. Our view: pick one per codebase and stay with it. If an open-source licence or encrypted state is a hard requirement, choose OpenTofu. If you use HCP Terraform or want HashiCorp's newest features, stay with Terraform. Switching later gets harder the more of either tool's own features you use.
When Terraform is more than you need
Terraform pays for itself when many pieces have to stay the same across environments. A typical AWS backend (a VPC, an ECS service with its task definition and IAM roles, a few Lambda functions, CloudWatch alarms) has dozens of resources that must match between staging and production, and the moment you keep them in step by hand in the console, drift starts.
It pays off much less for a small product on a couple of managed platforms, say a web app on Cloudflare Workers or Vercel with a hosted Postgres database. Each of those services already keeps its settings in its own config file or dashboard, and Terraform adds a state file to protect and a pipeline to maintain before it saves anyone time. A rough rule: once you have more than one environment, more than a dozen or so cloud resources, or more than one person changing them, write the infrastructure in Terraform. If you are about to move workloads to the cloud, write the landing zone this way from the first day; our cloud migration post covers what goes into it.
Frequently asked questions
Is Terraform still free?
Yes, for managing your own infrastructure: the BSL only restricts products that compete with HashiCorp's. HCP Terraform, the hosted service, is free for up to 500 managed resources with unlimited users, and paid editions start above that. HashiCorp retired its older free plan on 31 March 2026. If you need an open-source licence, OpenTofu is under MPL 2.0.
Do I need Terragrunt?
Not for a handful of root modules. The directory layout above repeats a backend block and a provider block in every root module, and Terragrunt, an open-source wrapper from Gruntwork, exists mostly to generate those blocks and to run several root modules in dependency order. It starts to pay off with dozens of root modules spread over several accounts. Below that, a few repeated lines cost less than another tool everyone has to learn.
Terraform or CloudFormation?
If everything runs on AWS and will stay there, CloudFormation (or the AWS CDK, which generates CloudFormation templates) is a sound choice, and AWS keeps the state for you, so there is no state file to protect. Terraform fits better when the same code also has to manage DNS at Cloudflare, GitHub settings, a monitoring service or a second cloud.
Does Terraform replace Ansible?
They mostly do different jobs. Terraform creates and changes resources through provider APIs: networks, load balancers, databases, DNS records. Ansible configures what runs inside servers. If everything you run is containers or managed services, you may not need Ansible at all.
Setting up the cloud side of a backend is part of our backend and API work, if you'd rather not do it alone.
Related Articles
AWS Cloud Architecture: A Practical Blueprint and What It Costs
The AWS setup we would suggest for most web apps and SaaS products, layer by layer: accounts, network, compute, data and operations, with October 2026 prices for Frankfurt.
Read More: AWS Cloud Architecture: A Practical Blueprint and What It CostsCloud Migration Strategy: How to Pick the Right R for Each App
Choose one of the 7 Rs per application, map what each system talks to, move in waves, rehearse the rollback and budget for the costs most migration plans leave out.
Read More: Cloud Migration Strategy: How to Pick the Right R for Each AppAWS Cost Optimization: What to Fix First, and What It Saves
The order matters more than any single trick: clean up, rightsize and move to Graviton before you buy Savings Plans. Worked examples use AWS list prices from October 2026.
Read More: AWS Cost Optimization: What to Fix First, and What It Saves
