Terraform modules, variables & remote state
Reuse modules and keep state safely in S3 with locking.
By Invicly Tech, , in Full DevOps with Python. About 12 minutes to read.
In short
Terraform modules package infrastructure you can reuse, and variables make them configurable per environment. Remote state in S3 with locking lets a team share one source of truth without overwriting each other.
Explained simply
As your Terraform code grows, you will copy the same network setup into dev, staging and prod. A module stops that copying. A module is simply a folder of .tf files that you call from somewhere else, passing in values, like calling a function.
Variables are the inputs of a module, and outputs are its return values. A tfvars file holds the input values for one environment: dev might use small servers and one zone, prod bigger servers and three zones, all with the same module code.
State is Terraform's memory of what it built. On a laptop, it gets lost or overwritten. In a team, you store it remotely in an S3 bucket, with locking so two people cannot apply at the same moment.
Finally, keep each environment separate: its own folder, its own variable values and its own state file. Then a mistake while testing in dev cannot delete anything in prod.
Press Play on a diagram to walk through it one step at a time.
- modules/vpc
- main.tf
- variables.tf
- outputs.tf
- envs/dev
- main.tf calls modules
- dev.tfvars
- backend: dev state key
- envs/prod
- main.tf calls modules
- prod.tfvars
- backend: prod state key
- Terraform to Lock: Acquire lock1Acquire lock
- Terraform to S3 state: Read current state2Read current state
- Terraform to AWS API: Refresh and compare3Refresh and compare
- Terraform to AWS API: Create or update resources4Create or update resources
- Terraform to S3 state: Write new state5Write new state
- Terraform to Lock: Release lock6Release lock
- 1prod.tfvars
vpc_cidr = 10.20.0.0/16
- 2Root variables
var.vpc_cidr in envs/prod
- 3module vpc call
cidr = var.vpc_cidr
- 4Module resources
aws_vpc.this uses var.cidr
- 5Module outputs
module.vpc.vpc_id back to the root
In depth
Variables, types and where values come from
A variable block can set a type (string, number, bool, list(string), map(string), object({...})), a default, a description, and validation rules with a condition and error message. A variable without a default is required. sensitive = true hides the value in plan output.
Values can come from several places, and later sources win. From lowest to highest priority: TF_VAR_name environment variables, terraform.tfvars, terraform.tfvars.json, any *.auto.tfvars files (in alphabetical order), and finally -var and -var-file options on the command line, in the order given. terraform.tfvars and *.auto.tfvars load automatically; other files need -var-file=prod.tfvars.
locals are internal named values, good for building names or common tags once (local.name_prefix). They are not inputs, so callers cannot override them. Keep secrets out of tfvars files in Git; pass them with TF_VAR_ variables from your CI secret store or read them from a secrets manager with a data source.
- No default means the variable is required
- -var and -var-file override everything else
- Use validation blocks to reject bad values early
- 1-var and -var-file
Command line, in the order given
- 2*.auto.tfvars
Loaded automatically, alphabetical order
- 3terraform.tfvars.json
Loaded automatically
- 4terraform.tfvars
Loaded automatically
- 5TF_VAR_name
Environment variables
- 6default in the variable block
Used only if nothing else is set
Writing your own VPC module
A good module has a small, clear interface. variables.tf declares the inputs (name, cidr, az_count), main.tf holds the resources, and outputs.tf exposes what callers need (vpc_id, public_subnet_ids, private_subnet_ids). Callers can only see outputs; they cannot reach into the module's resources directly.
Inside the module, use variables instead of fixed values and count or for_each to create one subnet per zone. Do not put a provider block with credentials inside a reusable module; the root configuration configures providers and passes them down.
When you move existing resources into a module, their addresses change, for example from aws_vpc.main to module.vpc.aws_vpc.this. Without help, Terraform would plan to destroy the old one and create a new one. A moved block (from and to addresses) tells Terraform it is the same object, so the plan shows a move with no real changes. Run plan and confirm 0 to destroy before applying.
- Inputs in variables.tf, outputs in outputs.tf
- Root config owns provider settings
- moved blocks refactor without recreating resources
Using registry modules safely
The public Terraform Registry hosts community modules. The popular terraform-aws-modules/vpc/aws module builds a VPC with public and private subnets, route tables and optional NAT gateways from a dozen inputs. Its source is written as namespace/name/provider, and you set a version constraint next to it.
Always pin the version. Without it, terraform init picks the newest release, and a major version can rename inputs or change resources. Use an exact version or a pessimistic constraint like ~> 6.0, and upgrade on purpose with terraform init -upgrade followed by a careful plan. Git sources can be pinned with ?ref=v1.2.0 at the end of the URL.
Before adopting a module, read its inputs, outputs and examples on the registry page, check that it is maintained, and look at what it creates in the plan. A registry module saves time, but you still own every resource it makes, including its costs (one NAT gateway per zone adds up).
Remote state in S3 with locking
The state file maps every resource in your code to a real ID, and it can contain secrets such as database passwords in plain text. So it must be shared, protected and never lost.
The s3 backend stores it in a bucket. Turn on bucket versioning so you can recover an older state, block all public access, enable encryption (encrypt = true), and limit IAM access to the people and pipelines that run Terraform. Use a key per environment and stack, like prod/network.tfstate.
Locking stops two applies at once. Since Terraform 1.10, use_lockfile = true locks by writing a .tflock object next to the state in S3. Older setups used a DynamoDB table (dynamodb_table), which is now deprecated. If a run crashes and leaves a lock, terraform force-unlock LOCK_ID releases it, but only after you are sure nobody is still running.
The backend block cannot use variables. For different settings per environment, use partial configuration: terraform init -backend-config=dev.s3.tfbackend.
- Versioning on, public access blocked, encryption on
- use_lockfile = true needs Terraform 1.10 or newer
- terraform init -migrate-state moves local state into S3
Separating dev and prod
There are two common patterns. Directory per environment: envs/dev and envs/prod each have their own main.tf that calls the shared modules, their own tfvars and their own backend key. It is explicit and easy to understand, and a plan in envs/dev can only touch dev state. Its downside is a little repeated wiring.
CLI workspaces: one folder, and terraform workspace new prod creates a second state in the same backend (in S3 under the env:/ prefix). It is quick, but it is easy to forget which workspace is selected, and both environments share the same backend credentials. HashiCorp recommends workspaces for short-lived copies, not for strong isolation between dev and prod.
For real isolation, many teams go further and use separate AWS accounts for dev and prod, each with its own state bucket and IAM role. Promote changes the same way as code: apply in dev, then the same commit in prod.
- envs/dev and envs/prod folders
- Own backend key and tfvars each
- Clear and hard to mix up
- Some repeated wiring
- One folder, many states
- terraform workspace select prod
- Fast for temporary copies
- Easy to apply in the wrong one
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Use input variables and tfvars files~1h
- 2Extract a reusable VPC module~1h
- 3Consume a registry module~1h
- 4Store state in S3 with locking~1h
- 5Separate dev and prod environments~1h
Key points
- Variables are inputs, outputs are return values, and a module is a folder of .tf files.
- Pin module versions so a registry update cannot change your infrastructure silently.
- Store state in S3 with versioning and locking so two applies cannot collide.
- Give dev and prod separate state files so a dev mistake cannot touch prod.
Key terms
Tap a card to flip it. 0/5 known
Examples
terraform {
backend "s3" {
bucket = "acme-tf-state"
key = "prod/network.tfstate"
region = "us-east-1"
use_lockfile = true
}
}
module "vpc" {
source = "../../modules/vpc"
cidr = var.vpc_cidr
az_count = 2
}Prod uses the shared VPC module with S3 state and locking.
Use the registry VPC module for dev
Step 1: call the module with a pinned version. Step 2: give it a name, CIDR, two zones and subnet ranges. Step 3: use a single NAT gateway in dev to save money (prod can set one per zone). Step 4: run terraform init to download it, then plan; you will see around 20 resources to add. Step 5: other code reads module.vpc.private_subnets for databases and servers.
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 6.0"
name = "dev"
cidr = "10.10.0.0/16"
azs = ["us-east-1a", "us-east-1b"]
public_subnets = ["10.10.1.0/24", "10.10.2.0/24"]
private_subnets = ["10.10.11.0/24", "10.10.12.0/24"]
enable_nat_gateway = true
single_nat_gateway = true
}
output "private_subnet_ids" { value = module.vpc.private_subnets }Move local state to S3 without recreating anything
Your team has been running Terraform from one laptop. Step 1: create the state bucket once (by hand or a tiny bootstrap config) with versioning and public access blocked. Step 2: add the backend block with use_lockfile. Step 3: run terraform init -migrate-state; Terraform asks to copy the existing state into S3, answer yes. Step 4: run terraform plan; it must show no changes. Step 5: delete the local terraform.tfstate files so nobody uses them by mistake.
aws s3api create-bucket --bucket acme-tf-state --region us-east-1
aws s3api put-bucket-versioning --bucket acme-tf-state \
--versioning-configuration Status=Enabled
aws s3api put-public-access-block --bucket acme-tf-state \
--public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
# add backend "s3" { bucket, key, region, encrypt = true, use_lockfile = true }
terraform init -migrate-state
terraform plan # expect: No changes.
rm terraform.tfstate terraform.tfstate.backupQuick reference
- Variable precedence, low to high: TF_VAR_, terraform.tfvars, *.auto.tfvars, -var and -var-file
- terraform plan -var-file=prod.tfvars loads a non-default tfvars file
- Pin modules: version = "~> 6.0" for registry, ?ref=v1.2.0 for Git sources
- terraform init -upgrade fetches newer module and provider versions within constraints
- S3 backend: use_lockfile = true (Terraform 1.10+); dynamodb_table is deprecated
- Backend blocks cannot use variables; use -backend-config for per-environment settings
- moved { from = aws_vpc.main to = module.vpc.aws_vpc.this } refactors without recreating
- terraform force-unlock LOCK_ID only when you are sure no run is active
Common mistakes
- Keeping terraform.tfstate on a laptop or in Git, where it leaks secrets and drifts.
- Using variables inside the backend block; backend settings cannot use them.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Declare a required variable environment that only accepts dev or prod, and an instance_type variable with default t3.micro.
- Exercise 2medium
Turn your VPC code into modules/vpc with inputs name and cidr and outputs vpc_id and public_subnet_id, then call it from envs/dev.
- Exercise 3hard
Configure envs/dev and envs/prod to share one backend block but use different state keys, without using variables in the backend.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use Terraform workspaces for dev and prod?
- HashiCorp's own guidance is that CLI workspaces are not a good fit for strong separation such as dev and prod. Separate directories (or separate AWS accounts) with their own state are safer and clearer.
- Do I still need a DynamoDB table for Terraform locking?
- Not with Terraform 1.10 or newer: set use_lockfile = true and the S3 backend locks with an object in the bucket. The dynamodb_table option still works but is deprecated.
- Can I put secrets in tfvars files?
- Avoid it. Pass secrets as TF_VAR_ environment variables from your CI secret store or read them from Secrets Manager. Remember that values still end up in state, so protect the state bucket.
- What is the difference between a module and a provider?
- A provider is a plugin that knows how to talk to an API such as AWS. A module is your own (or a shared) folder of Terraform code that uses providers to build a group of resources.