Short answer
Keep Terraform state in an encrypted, versioned S3 bucket with locking; split state by environment and component; build small, versioned modules; pin Terraform, provider, and module versions; keep secrets in AWS Secrets Manager rather than in code; run plans in CI and apply only through a reviewed pipeline; tag every resource with default_tags; and check for drift on a schedule.
Terraform makes AWS infrastructure reviewable and repeatable, but only if the codebase and its state are organised with care. The practices below come from running Terraform-managed production workloads on AWS, including log processing pipelines built on S3, SQS, Lambda, OpenSearch, and ECS. They are ordered roughly by how much trouble they prevent.
1. Store state remotely, encrypted, and locked
Terraform state maps your code to real resources and often contains sensitive values. Never keep it on a laptop or in Git. Store it in a dedicated S3 bucket with versioning enabled, public access blocked, server-side encryption on, and IAM access limited to the people and pipelines that run Terraform. Terraform 1.11 and later can lock state using the S3 bucket itself, so two runs cannot change the same state at once; older setups use a DynamoDB table for locking.
terraform {
required_version = ">= 1.11"
backend "s3" {
bucket = "acme-terraform-state"
key = "prod/network/terraform.tfstate"
region = "ap-south-1"
encrypt = true
use_lockfile = true
}
}2. Split state by environment and component
One state file for everything means every plan touches everything, and one mistake can affect every environment. Give each environment its own state, and split large environments by component, for example network, data, and services, so a change to an application cannot accidentally modify the VPC. For production, separate AWS accounts per environment, managed through AWS Organizations, add a much stronger boundary than separate state files alone.
Terraform workspaces are useful for short-lived copies of the same stack, but they share one backend configuration and usually one set of credentials. For dev, staging, and production, separate directories with separate backends and roles are easier to reason about and to secure.
infrastructure/
├── modules/
│ ├── network/
│ ├── database/
│ └── service/
└── envs/
├── dev/
│ ├── network/
│ └── service/
└── prod/
├── network/
└── service/3. Write small, focused modules
A good module does one job, such as a network, a database, or a containerised service, and exposes a small set of typed, documented inputs and outputs. Avoid one large module with dozens of feature flags; it becomes hard to change safely. Version shared modules with Git tags or a private registry, and reference a specific version from each environment so upgrades are deliberate.
Validate inputs so mistakes fail during plan instead of during apply:
variable "environment" {
type = string
description = "Deployment environment name."
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be dev, staging, or prod."
}
}4. Pin Terraform, provider, and module versions
Unpinned versions turn an ordinary plan into a surprise upgrade. Set required_version for Terraform, constrain each provider to a major version, and commit the .terraform.lock.hcl file so every machine and pipeline uses the same provider builds. Upgrade on purpose, in a branch, and read the provider's upgrade guide before moving to a new major version.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}5. Tag every resource with default_tags
Consistent tags make cost reports, ownership, and clean-up possible. The AWS provider's default_tags block applies tags to every taggable resource it creates, so nobody has to remember them. Activate the same keys as cost allocation tags in the AWS Billing console to break down spending by project and environment.
provider "aws" {
region = "ap-south-1"
default_tags {
tags = {
Project = "orders-platform"
Environment = var.environment
ManagedBy = "terraform"
}
}
}6. Keep secrets out of code and, where possible, out of state
Never commit passwords, API keys, or private keys to Terraform files or .tfvars. Store them in AWS Secrets Manager or SSM Parameter Store and grant your workloads permission to read them at runtime. Marking a variable as sensitive hides it from plan output but not from state, so prefer designs where Terraform never handles the secret value. For Amazon RDS, setting manage_master_user_password = true lets AWS generate the master password and keep it in Secrets Manager. Newer Terraform versions also add ephemeral values and write-only arguments that keep some secrets out of state entirely; check whether the resources you use support them.
7. Plan in CI and apply only through a pipeline
Running apply from a laptop makes changes invisible and hard to audit. A simple pipeline removes that risk:
- On every pull request, run terraform fmt -check, terraform validate, a linter such as TFLint, and a security scanner such as Checkov.
- Run terraform plan, save the plan file, and post the summary on the pull request for review.
- After approval and merge, apply exactly the reviewed plan file from the pipeline.
- Authenticate the pipeline to AWS with OpenID Connect and short-lived IAM roles instead of long-lived access keys, and use a read-only role for plans and a separate role for applies.
8. Detect drift and stop console changes
Manual changes in the AWS console drift away from the code and get reverted, or worse, preserved by accident. Restrict write access in production to the pipeline role, and run terraform plan -detailed-exitcode on a schedule: exit code 2 means the real infrastructure no longer matches the code, which should raise an alert for someone to investigate.
9. Refactor with moved and import blocks
Renaming a resource or moving it into a module used to mean careful terraform state mv commands. Moved blocks record the change in code, so it is reviewed and applied like any other change, and import blocks bring existing resources under Terraform management the same way.
moved {
from = aws_s3_bucket.logs
to = module.logging.aws_s3_bucket.this
}10. Protect what must never be destroyed
Add lifecycle { prevent_destroy = true } to resources such as production databases and the state bucket itself, enable deletion protection where AWS supports it, and keep backups independent of Terraform. Policy checks in CI can also block risky changes, such as public S3 buckets or security groups open to the internet, before they reach review.
Quick checklist
- Remote S3 state with versioning, encryption, and locking
- Separate state per environment and component, ideally separate AWS accounts
- Small modules with typed, validated inputs
- Pinned Terraform and provider versions with a committed lock file
- default_tags on every provider
- Secrets in Secrets Manager or Parameter Store, never in code
- Plan on pull request, apply from the pipeline with OIDC roles
- Scheduled drift detection and prevent_destroy on critical resources
If you want help setting up or cleaning up Terraform on AWS, our AWS cloud and DevOps service covers infrastructure as code, CI/CD pipelines, monitoring, and cost optimisation, led by an AWS Certified Solutions Architect.
Frequently asked questions
Should I use Terraform workspaces for dev and production?
Workspaces are convenient for short-lived or identical copies of a stack, but they share one backend configuration and usually one set of credentials. For dev, staging, and production, separate state files, ideally in separate AWS accounts, give clearer isolation and safer access control.
Is DynamoDB still needed for Terraform state locking on AWS?
Not on Terraform 1.11 or later, which can lock state directly in the S3 bucket with use_lockfile = true. Existing DynamoDB-based locking continues to work, so you can migrate when you upgrade Terraform.
Should I choose Terraform or AWS CloudFormation and the CDK?
Both work well on AWS. Terraform suits teams that manage several providers, such as AWS plus DNS, monitoring, or source control, with one tool and language. CloudFormation and the AWS CDK are AWS-native and integrate closely with AWS services. Using one approach consistently matters more than which one you pick.