Modules, environments and remote state

Advanced · 36 min

Make Terraform work for a team: shared locked state in a remote backend, modules for reuse, and one layout that keeps dev, staging and prod alike but apart.

Before thisTerraform and OpenTofu: plan, apply and stateBuild once, promote through environments

DevOps Directive · 158 min · from 1:20:02

Modules, environments and remote state

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DevOps DirectiveReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A remote backend stores state in one shared place with locking, so two people cannot apply at the same time and overwrite each other's changes.
  • On S3, Terraform now locks with a lock file in the bucket (use_lockfile = true). The older DynamoDB lock table is deprecated.
  • A module is a directory of Terraform code with input variables and outputs. Environments call the same module with different inputs instead of copying code.
  • Give each environment its own state, either through workspaces or, more commonly, a directory per environment with its own backend key.
  • Split state by environment and by component, so one plan touches a small blast radius and a mistake in dev cannot reach production.

When the second person joins

The last lesson ended with one person, one laptop and a terraform.tfstate file. Three things break as soon as that grows.

  • State on a laptop is invisible to everyone else, and gone if the laptop is.
  • Two people applying at once read the same old state, each make changes, and the second write wins. Terraform then believes resources exist that do not, or forgets ones that do.
  • Dev, staging and production get built by copying the folder three times, and the copies drift, which is exactly the problem IaC was meant to solve.

The fixes are a remote backend, modules and a deliberate layout for environments.

Remote state with locking

A backend is where Terraform keeps state. A remote one puts it in shared storage with access control and, most importantly, a lock: whoever is applying holds it, and anyone else fails fast instead of corrupting the file. A common setup on AWS, from the Terraform S3 backend docs. I did not run it, since there is no Terraform or AWS account here:

terraform {
  backend "s3" {
    bucket       = "acme-terraform-state"
    key          = "prod/network/terraform.tfstate"
    region       = "eu-west-1"
    encrypt      = true
    use_lockfile = true
  }
}

use_lockfile = true makes Terraform create a lock object next to the state in the bucket. When I read the S3 backend docs on 27 November 2026, they marked the older approach, a DynamoDB table named in dynamodb_table, as deprecated and due for removal in a future minor version. Most tutorials before 2025 still show the DynamoDB table, so expect to see both. Turn on versioning for the state bucket, so a bad apply can be rolled back to the previous state, and restrict who can read it, because state can contain secrets. Google Cloud Storage, Azure Blob Storage and HCP Terraform offer the same thing for their platforms.

Modules: write it once

A module is a directory of .tf files with input variables and outputs. Every Terraform configuration is a module, and calling one from another is how you reuse code:

# modules/web-service/variables.tf
variable "name"          { type = string }
variable "instance_type" { type = string }
variable "min_size"      { type = number }

# modules/web-service/outputs.tf
output "lb_dns_name" { value = aws_lb.this.dns_name }
# envs/prod/main.tf
module "notes_api" {
  source        = "git::https://github.com/acme/infra-modules.git//web-service?ref=v1.6.0"
  name          = "notes-api-prod"
  instance_type = "m7g.large"
  min_size      = 3
}

The ?ref=v1.6.0 pins the module version. When you change the module, dev moves to v1.7.0 first, and production follows only after it has proven itself. That is build once, promote applied to infrastructure.

The public registry has thousands of modules. I looked up the most popular AWS network module:

$ curl -s https://registry.terraform.io/v1/modules/terraform-aws-modules/vpc/aws | jq '{id, version, published_at, downloads, inputs: (.root.inputs|length), outputs: (.root.outputs|length), required_inputs: [.root.inputs[]|select(.required==true)|.name]}'
{
  "id": "terraform-aws-modules/vpc/aws/6.9.0",
  "version": "6.9.0",
  "published_at": "2026-11-25T14:53:24.924151Z",
  "downloads": 236553981,
  "inputs": 239,
  "outputs": 119,
  "required_inputs": []
}

239 inputs and none required. A general-purpose module has to cover every case, so it is powerful and hard to review. A small in-house module with five inputs encodes your decisions, such as “our services always get encrypted volumes”, and leaves less to get wrong. Many teams wrap a big public module in a small opinionated one.

One layout for many environments

There are three common ways to run the same code for several environments:

  1. Workspaces. One directory, one backend, and terraform workspace select prod switches between separate state files. It is quick, but the environments share a backend and its permissions, and the only thing between you and applying to production is which workspace happens to be selected.
  2. A directory per environment. envs/dev, envs/staging and envs/prod each call the same modules with their own inputs and their own backend key. The differences are plain files that show up in review, and CI can give the production directory stricter permissions.
  3. A branch per environment. Merging promotes a change. It sounds tidy, but branches drift apart quickly, and it is the option most guides warn against.

Most teams land on the second. A typical tree:

infra/
  modules/web-service/        # reusable, versioned
  envs/dev/network/           # its own state: dev/network
  envs/dev/notes-api/         # its own state: dev/notes-api
  envs/prod/network/
  envs/prod/notes-api/

Notice that state is also split by component. One giant state for everything means every plan reads every resource, takes minutes, and a typo can touch the network and the database at once. Smaller states mean smaller plans and a smaller blast radius. Tools like Terragrunt exist mostly to cut the repetition this layout creates.

About the video

The embed is Parts 6 and 7 of DevOps Directive’s “Complete Terraform Course - From BEGINNER to PRO!” by Sid Palas, published February 2022: “Project Organization + Modules” and “Managing Multiple Environments”, each with a demo, from 1:20:02 to 1:56:05. The full course is 2 hours 38 minutes. The written companion’s Part 7 has a workspaces example and a subdirectory example, the first two layouts above. Remote backends are covered in the course’s Part 3, the clip used in the previous lesson. The course predates S3 native locking, so any S3 backend it shows will use DynamoDB. English was judged from the title, description, channel and its English auto-caption track. Ned in the Cloud’s video in deeper compares branch, folder and repository layouts in detail.

Where this fits

Terraform creates servers. Something still has to configure what runs on them: configuration management with Ansible.

Check yourself

  1. 01Two engineers run terraform apply against the same state at the same moment. What prevents damage?

    State locking in the backend. The first apply takes the lock, and the second fails to acquire it and stops instead of writing over the first one's state.

  2. 02What is the difference between a module's variables and its outputs?

    Variables are the inputs a caller sets, such as instance size or CIDR range. Outputs are values the module exposes after apply, such as a subnet ID, for the caller or other code to use.

  3. 03Why do many teams prefer a directory per environment over Terraform workspaces?

    Each directory has its own backend configuration, inputs and permissions, and the difference between environments is visible in files. Workspaces share one codebase and backend, and the active workspace is easy to get wrong.

  4. 04Why pin a module to a version when calling it?

    So a change to the module reaches environments one at a time. Dev can move to the new version and prove it before staging and production follow.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark