Catalog My learning Blog
CI/CD and DevOps Tutorial: Build a Delivery Pipeline · Phase 3 · Lesson 17 · 4 min read

Terraform State and Modules Explained

On this page
  1. What Terraform state is
  2. Remote state in S3 with locking
  3. Splitting state by blast radius
  4. Terraform modules
  5. Check yourself

What Terraform state is

Terraform records every resource it manages in a state file: "aws_security_group.web is sg-97d9...". Plans compare code against state and reality. Lose the state and Terraform no longer knows it owns those resources; corrupt it and plans go wrong; let two people apply at once and they overwrite each other's changes.

State can also contain secrets (database passwords, keys) in plain text, so treat it as sensitive.

Remote state in S3 with locking

For a team, state goes in shared, versioned storage with a lock so only one operation runs at a time. With S3, Terraform 1.10+ and OpenTofu 1.10+ lock using a lock file in the bucket itself, so the DynamoDB table older guides describe is no longer needed:

Shell
terraform {
  backend "s3" {
    bucket       = "acme-terraform-state"
    key          = "checkout-svc/staging/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true # S3-native locking; no DynamoDB table needed
  }
}

The state bucket should have versioning (to recover earlier states), encryption, Block Public Access, and access limited to CI and a few administrators.

Here's what a teammate sees when they run a plan while someone else's apply holds the lock, tested against a local S3:

Code
Acquiring state lock. This may take a few moments...
Error: Error acquiring the state lock
Error message: ... api error PreconditionFailed: At least one of the pre-conditions you specified did not hold
Lock Info:
  ID:        5c1d2f3e-teammate
  Path:      acme-terraform-state/checkout-svc/staging/terraform.tfstate
  Operation: OperationTypeApply
  Who:       priya@laptop
  Version:   1.13.1
  Created:   2026-10-11 09:14:02 +0000 UTC

The lock is a conditional write that fails if the lock file exists. Wait for the other run to finish. Only use force-unlock <ID> when you're sure the lock holder has died, never to get around a colleague's apply.

Teams share state in a versioned, locked backend; modules package resources that many configurations reuse.
Teams share state in a versioned, locked backend; modules package resources that many configurations reuse.

Splitting state by blast radius

One giant state for everything makes every plan slow and every mistake large. Split it: per environment (staging, production) and per component (network, database, each service). A plan for one service then can't touch the production network.

Terraform modules

A module is a directory of Terraform files with inputs and outputs, reused like a function:

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

variable "environment" {
  type = string
  validation {
    condition     = contains(["staging", "production"], var.environment)
    error_message = "environment must be staging or production."
  }
}

variable "vpc_id" {
  type = string
}

variable "allowed_cidrs" {
  type    = list(string)
  default = ["0.0.0.0/0"]
}
Terraform
# modules/web-service/main.tf
resource "aws_security_group" "this" {
  name        = "${var.name}-${var.environment}"
  description = "Ingress for ${var.name}"
  vpc_id      = var.vpc_id
  tags        = { Service = var.name, Environment = var.environment }
}

resource "aws_vpc_security_group_ingress_rule" "https" {
  for_each          = toset(var.allowed_cidrs)
  security_group_id = aws_security_group.this.id
  cidr_ipv4         = each.value
  from_port         = 443
  to_port           = 443
  ip_protocol       = "tcp"
}

Two services use it:

Terraform
module "checkout" {
  source        = "./modules/web-service"
  name          = "checkout"
  environment   = var.environment
  vpc_id        = aws_vpc.main.id
  allowed_cidrs = ["10.20.0.0/16"]
}

module "search" {
  source      = "./modules/web-service"
  name        = "search"
  environment = var.environment
  vpc_id      = aws_vpc.main.id
}
Code
  # module.checkout.aws_security_group.this will be created
  # module.checkout.aws_vpc_security_group_ingress_rule.https["10.20.0.0/16"] will be created
  # module.search.aws_security_group.this will be created
  # module.search.aws_vpc_security_group_ingress_rule.https["0.0.0.0/0"] will be created
Plan: 4 to add, 0 to change, 0 to destroy.

And the validation rule rejects a typo before anything is planned: -var environment=prod fails with Error: Invalid value for variable.

Share modules across repositories with version pins (a Git tag or a registry version), so updating a module is a deliberate change for each consumer.

Check yourself

Two simultaneous applies would read the same state and each write their own version, overwriting the other's changes, corrupting the state or leaving infrastructure Terraform no longer tracks. A lock lets only one run change state at a time.

Smaller states plan faster, and a mistake can only affect what's in that state, so a change to one service can't accidentally touch the production network. It also lets teams own and apply their parts independently.

Each CIDR becomes a separately addressed resource keyed by its value, so adding or removing one doesn't shift or recreate the others.

State can contain passwords, keys and other sensitive attribute values in plain text. Store it encrypted, with tight access control.

A focused purpose, a small set of clear inputs and outputs, sensible defaults and a pinned version when other configurations use it.