Advanced Terraform: Modules and State Management
· Pavan Y N · terraform, devops, aws, cicd
Advanced Terraform is mostly about boundaries: what belongs in a module, what belongs in a separate state, who may read that state, and how changes are tested before they reach production. EduGeek explains a reusable VPC (Virtual Private Cloud) module, state management on AWS with S3-native locking, two layers of testing, and the patterns that keep Terraform manageable across many teams and accounts. It assumes the basics from Terraform Infrastructure as Code: Complete Guide. The module and test code was validated with Terraform 1.15 and the AWS provider 6.x.
# Reusable modules
## Module structure
A module repository should make three things obvious: the interface (variables and outputs), the supported versions, and how to try it.
terraform-modules/
├── vpc/
│ ├── main.tf
│ ├── flow_logs.tf
│ ├── variables.tf
│ ├── outputs.tf
│ ├── versions.tf
│ ├── README.md
│ ├── examples/
│ │ └── complete/
│ │ └── main.tf
│ ├── tests/
│ │ └── vpc.tftest.hcl
│ └── test/
│ └── vpc_test.go
├── eks/
└── rds/
versions.tf declares what the module needs. Modules should declare provider requirements but never configure providers; the calling configuration does that.
terraform {
required_version = ">= 1.11.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 6.0, < 7.0"
}
}
}
## A VPC module with per-AZ subnets, NAT, and flow logs
The module below creates public, private, and optional database subnets across a configurable number of Availability Zones (AZs). Compared with the count-based version commonly copied from older tutorials, it keys every per-AZ resource by AZ name with for_each, so changing az_count adds or removes whole zones without renumbering the rest. It also includes the IAM role and policy that VPC Flow Logs need to write to CloudWatch Logs; omitting them is a common reason a copied module fails validation.
modules/vpc/main.tf:
data "aws_availability_zones" "available" {
state = "available"
}
locals {
azs = slice(data.aws_availability_zones.available.names, 0, var.az_count)
az_indexes = { for index, az in local.azs : az => index }
# With a single NAT gateway, only the first AZ hosts one
nat_azs = var.enable_nat_gateway ? (var.single_nat_gateway ? slice(local.azs, 0, 1) : local.azs) : []
}
resource "aws_vpc" "this" {
cidr_block = var.vpc_cidr
enable_dns_hostnames = var.enable_dns_hostnames
enable_dns_support = var.enable_dns_support
tags = merge(var.tags, { Name = var.name })
}
resource "aws_internet_gateway" "this" {
vpc_id = aws_vpc.this.id
tags = merge(var.tags, { Name = "${var.name}-igw" })
}
resource "aws_subnet" "public" {
for_each = local.az_indexes
vpc_id = aws_vpc.this.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, each.value)
availability_zone = each.key
map_public_ip_on_launch = true
tags = merge(var.tags, {
Name = "${var.name}-public-${each.key}"
Type = "public"
"kubernetes.io/role/elb" = "1"
})
}
resource "aws_subnet" "private" {
for_each = local.az_indexes
vpc_id = aws_vpc.this.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, each.value + 10)
availability_zone = each.key
tags = merge(var.tags, {
Name = "${var.name}-private-${each.key}"
Type = "private"
"kubernetes.io/role/internal-elb" = "1"
})
}
resource "aws_subnet" "database" {
for_each = var.create_database_subnets ? local.az_indexes : {}
vpc_id = aws_vpc.this.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, each.value + 20)
availability_zone = each.key
tags = merge(var.tags, {
Name = "${var.name}-database-${each.key}"
Type = "database"
})
}
resource "aws_eip" "nat" {
for_each = toset(local.nat_azs)
domain = "vpc"
tags = merge(var.tags, { Name = "${var.name}-nat-eip-${each.key}" })
depends_on = [aws_internet_gateway.this]
}
resource "aws_nat_gateway" "this" {
for_each = toset(local.nat_azs)
allocation_id = aws_eip.nat[each.key].id
subnet_id = aws_subnet.public[each.key].id
tags = merge(var.tags, { Name = "${var.name}-nat-${each.key}" })
depends_on = [aws_internet_gateway.this]
}
resource "aws_route_table" "public" {
vpc_id = aws_vpc.this.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.this.id
}
tags = merge(var.tags, { Name = "${var.name}-public-rt" })
}
resource "aws_route_table" "private" {
for_each = local.az_indexes
vpc_id = aws_vpc.this.id
tags = merge(var.tags, { Name = "${var.name}-private-rt-${each.key}" })
}
resource "aws_route" "private_nat" {
for_each = var.enable_nat_gateway ? local.az_indexes : {}
route_table_id = aws_route_table.private[each.key].id
destination_cidr_block = "0.0.0.0/0"
nat_gateway_id = aws_nat_gateway.this[var.single_nat_gateway ? local.azs[0] : each.key].id
}
resource "aws_route_table_association" "public" {
for_each = aws_subnet.public
subnet_id = each.value.id
route_table_id = aws_route_table.public.id
}
resource "aws_route_table_association" "private" {
for_each = aws_subnet.private
subnet_id = each.value.id
route_table_id = aws_route_table.private[each.key].id
}
modules/vpc/flow_logs.tf:
resource "aws_cloudwatch_log_group" "flow_logs" {
count = var.enable_flow_logs ? 1 : 0
name = "/aws/vpc/${var.name}"
retention_in_days = var.flow_logs_retention_days
tags = var.tags
}
data "aws_iam_policy_document" "flow_logs_assume" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["vpc-flow-logs.amazonaws.com"]
}
}
}
data "aws_iam_policy_document" "flow_logs_write" {
count = var.enable_flow_logs ? 1 : 0
statement {
actions = [
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:DescribeLogStreams",
]
resources = ["${aws_cloudwatch_log_group.flow_logs[0].arn}:*"]
}
}
resource "aws_iam_role" "flow_logs" {
count = var.enable_flow_logs ? 1 : 0
name = "${var.name}-flow-logs"
assume_role_policy = data.aws_iam_policy_document.flow_logs_assume.json
tags = var.tags
}
resource "aws_iam_role_policy" "flow_logs" {
count = var.enable_flow_logs ? 1 : 0
name = "write-flow-logs"
role = aws_iam_role.flow_logs[0].id
policy = data.aws_iam_policy_document.flow_logs_write[0].json
}
resource "aws_flow_log" "this" {
count = var.enable_flow_logs ? 1 : 0
vpc_id = aws_vpc.this.id
traffic_type = "ALL"
log_destination = aws_cloudwatch_log_group.flow_logs[0].arn
iam_role_arn = aws_iam_role.flow_logs[0].arn
max_aggregation_interval = 60
tags = merge(var.tags, { Name = "${var.name}-flow-logs" })
}
modules/vpc/variables.tf:
variable "name" {
description = "Name used on all resources"
type = string
}
variable "vpc_cidr" {
description = "CIDR block for the VPC"
type = string
validation {
condition = can(cidrhost(var.vpc_cidr, 0))
error_message = "Must be a valid IPv4 CIDR block."
}
}
variable "az_count" {
description = "Number of Availability Zones to span"
type = number
default = 3
validation {
condition = var.az_count >= 2 && var.az_count <= 6
error_message = "AZ count must be between 2 and 6."
}
}
variable "enable_nat_gateway" {
description = "Create NAT gateways for the private subnets"
type = bool
default = true
}
variable "single_nat_gateway" {
description = "Share one NAT gateway across all AZs (cheaper, but not zone-resilient)"
type = bool
default = false
}
variable "create_database_subnets" {
description = "Create database subnets"
type = bool
default = false
}
variable "enable_dns_hostnames" {
description = "Enable DNS hostnames in the VPC"
type = bool
default = true
}
variable "enable_dns_support" {
description = "Enable DNS support in the VPC"
type = bool
default = true
}
variable "enable_flow_logs" {
description = "Send VPC Flow Logs to CloudWatch Logs"
type = bool
default = false
}
variable "flow_logs_retention_days" {
description = "Flow log retention in days"
type = number
default = 7
}
variable "tags" {
description = "Tags to apply to all resources"
type = map(string)
default = {}
}
modules/vpc/outputs.tf:
output "vpc_id" {
description = "ID of the VPC"
value = aws_vpc.this.id
}
output "vpc_cidr" {
description = "CIDR block of the VPC"
value = aws_vpc.this.cidr_block
}
output "public_subnet_ids" {
description = "IDs of the public subnets, keyed by Availability Zone"
value = { for az, subnet in aws_subnet.public : az => subnet.id }
}
output "private_subnet_ids" {
description = "IDs of the private subnets, keyed by Availability Zone"
value = { for az, subnet in aws_subnet.private : az => subnet.id }
}
output "database_subnet_ids" {
description = "IDs of the database subnets, keyed by Availability Zone"
value = { for az, subnet in aws_subnet.database : az => subnet.id }
}
output "nat_gateway_ids" {
description = "IDs of the NAT gateways, keyed by Availability Zone"
value = { for az, nat in aws_nat_gateway.this : az => nat.id }
}
output "internet_gateway_id" {
description = "ID of the internet gateway"
value = aws_internet_gateway.this.id
}
Two design notes:
- →NAT gateway placement. One NAT gateway per AZ keeps outbound traffic working if a zone fails;
single_nat_gateway = trueis cheaper but ties every private subnet to one zone. AWS has also introduced regional NAT gateways that expand across AZs automatically, and the AWS provider supports them throughavailability_mode = "regional"onaws_nat_gateway. Evaluate that option before writing new per-AZ NAT logic. AWS Multi-AZ High Availability Architecture covers the failure-domain reasoning, and Cloud Cost Optimization and FinOps Basics covers why NAT traffic is worth watching. - →Kubernetes subnet tags. The
kubernetes.io/role/elbandkubernetes.io/role/internal-elbtags are the convention Kubernetes load balancer integrations on AWS use to discover public and private subnets. Drop them if the VPC will not host Kubernetes.
## Using the module
module "vpc" {
source = "./modules/vpc"
name = "production-vpc"
vpc_cidr = "10.0.0.0/16"
az_count = 3
enable_nat_gateway = true
single_nat_gateway = false
create_database_subnets = true
enable_flow_logs = true
tags = {
Environment = "production"
ManagedBy = "Terraform"
Project = "MyApp"
}
}
resource "aws_security_group" "app" {
name = "app"
vpc_id = module.vpc.vpc_id
}
When modules live in their own repository, reference a tag so every change is a deliberate upgrade, and use semantic versioning for the tags:
module "vpc" {
source = "git::https://github.com/example/terraform-modules.git//vpc?ref=v1.4.0"
# ...
}
# Advanced state management
## Remote state with S3 and native locking
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/network/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true
kms_key_id = "arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012"
# Only used by non-default workspaces:
# state is stored at <workspace_key_prefix>/<workspace>/<key>
workspace_key_prefix = "workspaces"
}
}
Three facts from the S3 backend reference are worth keeping in mind:
- →S3-native locking (
use_lockfile) became generally available in Terraform 1.11, and DynamoDB locking (dynamodb_table) is deprecated. Both can be configured together during a migration. - →The lock is a separate object at the state key with
.tflockappended, so the identity running Terraform needss3:GetObject,s3:PutObject, ands3:DeleteObjecton that object as well as read and write access to the state itself. - →With
kms_key_id, Terraform needskms:Encrypt,kms:Decrypt, andkms:GenerateDataKeyon the key.
## The backend bucket and a least-privilege policy
Create the bucket once, from a separate bootstrap configuration with local state, and then point other configurations at it.
resource "aws_s3_bucket" "terraform_state" {
bucket = "my-terraform-state"
lifecycle {
prevent_destroy = true
}
}
resource "aws_s3_bucket_versioning" "terraform_state" {
bucket = aws_s3_bucket.terraform_state.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "terraform_state" {
bucket = aws_s3_bucket.terraform_state.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "aws:kms"
kms_master_key_id = aws_kms_key.terraform_state.arn
}
bucket_key_enabled = true
}
}
resource "aws_s3_bucket_public_access_block" "terraform_state" {
bucket = aws_s3_bucket.terraform_state.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_kms_key" "terraform_state" {
description = "KMS key for Terraform state encryption"
deletion_window_in_days = 10
enable_key_rotation = true
}
resource "aws_s3_bucket_lifecycle_configuration" "terraform_state" {
bucket = aws_s3_bucket.terraform_state.id
rule {
id = "expire-old-state-versions"
status = "Enabled"
filter {}
noncurrent_version_expiration {
noncurrent_days = 90
}
}
}
data "aws_iam_policy_document" "terraform_state_access" {
statement {
sid = "ListStateBucket"
actions = ["s3:ListBucket"]
resources = [aws_s3_bucket.terraform_state.arn]
}
statement {
sid = "ReadWriteStateAndLockFiles"
actions = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"]
resources = [
"${aws_s3_bucket.terraform_state.arn}/prod/*",
]
}
statement {
sid = "UseStateKey"
actions = ["kms:Encrypt", "kms:Decrypt", "kms:GenerateDataKey"]
resources = [aws_kms_key.terraform_state.arn]
}
}
The bucket is versioned, encrypted with a customer managed KMS key, and expires old noncurrent versions after 90 days, so a bad write can be rolled back for a while without keeping every version forever. The policy document grants the access a pipeline needs for the prod/ state prefix: list the bucket, read and write state and lock objects, and use the key. New S3 buckets already apply SSE-S3 encryption and block public access by default; the explicit settings here make the intent reviewable. The DynamoDB lock table that earlier versions of this guide created is no longer needed.
A check block in the same configuration can assert that versioning stays enabled. A failing check produces a warning in the plan without blocking it, which suits conditions that should stay visible but should not stop an unrelated change.
check "state_bucket_versioning" {
assert {
condition = aws_s3_bucket_versioning.terraform_state.versioning_configuration[0].status == "Enabled"
error_message = "State bucket versioning must stay enabled."
}
}
## Sharing data between configurations
A common structure is one configuration per layer (network, shared services, applications), each with its own state. The question is how the application layer learns the VPC ID.
terraform_remote_state is the familiar answer, but HashiCorp's documentation points out its drawback: although it exposes only output values, the reader needs access to the entire state snapshot, which often includes sensitive information. The documentation recommends explicitly publishing shared data to a separate location instead, using a managed resource and a matching data source. On AWS, Systems Manager Parameter Store is a simple fit:
# In the network configuration: publish what other stacks need
module "vpc" {
source = "./modules/vpc"
name = "production-vpc"
vpc_cidr = "10.0.0.0/16"
}
resource "aws_ssm_parameter" "vpc_id" {
name = "/platform/production/network/vpc_id"
type = "String"
value = module.vpc.vpc_id
}
# In an application configuration: read it back
data "aws_ssm_parameter" "vpc_id" {
name = "/platform/production/network/vpc_id"
}
resource "aws_security_group" "app" {
name = "app"
vpc_id = data.aws_ssm_parameter.vpc_id.value
}
# Testing Terraform code
Test at two levels: fast tests that need no cloud account, and a smaller set of integration tests that create real infrastructure.
## Native tests with a mocked provider
terraform test is generally available since Terraform 1.6, and mocked providers (Terraform 1.7 and later) let a test run without AWS credentials. This file lives at modules/vpc/tests/vpc.tftest.hcl and checks the module's logic at plan time:
mock_provider "aws" {
mock_data "aws_availability_zones" {
defaults = {
names = ["us-east-1a", "us-east-1b", "us-east-1c"]
}
}
}
variables {
name = "test-vpc"
vpc_cidr = "10.0.0.0/16"
az_count = 2
}
run "creates_one_subnet_pair_per_az" {
command = plan
assert {
condition = length(aws_subnet.public) == 2 && length(aws_subnet.private) == 2
error_message = "Expected one public and one private subnet per AZ."
}
assert {
condition = length(aws_nat_gateway.this) == 2
error_message = "Expected one NAT gateway per AZ by default."
}
}
run "single_nat_gateway_creates_exactly_one" {
command = plan
variables {
single_nat_gateway = true
}
assert {
condition = length(aws_nat_gateway.this) == 1
error_message = "single_nat_gateway should create exactly one NAT gateway."
}
}
run "rejects_invalid_az_count" {
command = plan
variables {
az_count = 1
}
expect_failures = [var.az_count]
}
cd modules/vpc
terraform init
terraform test
The expect_failures run confirms that the az_count validation rejects a bad value, which is how a module's input contract stays tested.
## Integration tests with Terratest
Mocks cannot tell you whether AWS accepts the configuration. For that, Terratest is a Go library that applies a real example, asserts on the outputs, and destroys it. Terratest 2.0 moved every module to a /v2 import path, and the repository's own examples now use the ...Context helper variants such as InitAndApplyContext and DestroyContext. Older snippets that import github.com/gruntwork-io/terratest/modules/terraform without /v2 target the v1 line, which receives security fixes only for 12 months after the v2 release. The test below targets v2 and needs Go 1.26 or later.
examples/complete/main.tf:
variable "name" {
type = string
}
variable "vpc_cidr" {
type = string
}
variable "az_count" {
type = number
}
provider "aws" {
region = "us-east-1"
}
module "vpc" {
source = "../.."
name = var.name
vpc_cidr = var.vpc_cidr
az_count = var.az_count
}
output "vpc_id" {
value = module.vpc.vpc_id
}
output "public_subnet_ids" {
value = module.vpc.public_subnet_ids
}
output "private_subnet_ids" {
value = module.vpc.private_subnet_ids
}
test/vpc_test.go:
package test
import (
"testing"
"github.com/gruntwork-io/terratest/modules/terraform/v2"
"github.com/stretchr/testify/assert"
)
func TestVPCModule(t *testing.T) {
t.Parallel()
terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
TerraformDir: "../examples/complete",
Vars: map[string]interface{}{
"name": "test-vpc",
"vpc_cidr": "10.0.0.0/16",
"az_count": 2,
},
})
// Destroy runs even if an assertion fails
defer terraform.DestroyContext(t, t.Context(), terraformOptions)
terraform.InitAndApplyContext(t, t.Context(), terraformOptions)
vpcID := terraform.OutputContext(t, t.Context(), terraformOptions, "vpc_id")
assert.NotEmpty(t, vpcID)
publicSubnetIDs := terraform.OutputMapContext(t, t.Context(), terraformOptions, "public_subnet_ids")
assert.Len(t, publicSubnetIDs, 2)
privateSubnetIDs := terraform.OutputMapContext(t, t.Context(), terraformOptions, "private_subnet_ids")
assert.Len(t, privateSubnetIDs, 2)
}
Terratest uses the terraform binary when it is on the PATH and falls back to tofu otherwise; set TerraformBinary in the options to pin one. Run these tests in a dedicated sandbox account, since they create billable resources.
# Patterns for many teams and accounts
## Separate states by boundary
HashiCorp's guidance is to create separate configurations that correspond to architectural boundaries, each with its own backend, instead of one large configuration or a pile of workspaces. A practical layout splits by account, environment, and layer (for example prod/network, prod/data, prod/apps/checkout), so a mistake in one layer has a bounded blast radius and access can be granted per state.
## A versioned module library
Publish modules from a Git repository or a private registry, tag releases with semantic versions, keep an examples/ directory and a tests/ directory in each module, and let consumers upgrade on their own schedule by changing a version constraint.
## Pipelines with short-lived credentials
Run terraform plan on pull requests and terraform apply of the saved, reviewed plan after merge. AWS's IAM guidance is to use temporary credentials for workloads, including CI/CD systems outside AWS, for example by exchanging the CI provider's OpenID Connect token through AssumeRoleWithWebIdentity instead of storing access keys. Scope each pipeline role to the accounts and state paths it manages, such as the prod/* prefix used in the backend policy above.
## Policy as code and drift detection
- →Policy. Pull-request scanners such as Checkov or Trivy catch misconfigurations before review. In HCP Terraform, policies can be enforced with Sentinel, Open Policy Agent (OPA), or the newer native Terraform policy framework, which is in beta.
- →Drift.
terraform plan -refresh-onlyshows differences between state and reality. HCP Terraform health assessments add scheduled drift detection and continuous validation for eligible workspaces. - →Governance. Apply common tags with the provider's
default_tags, enforce guardrails across accounts with AWS Organizations policies, and review who can read state, since it can contain secrets.
# Best practices
- →Modules: keep them focused, use
for_eachwith stable keys, version them semantically, document every variable and output, and ship anexamples/directory that doubles as the integration-test target. - →State: use a remote backend with locking, versioning, and encryption; migrate DynamoDB locking to
use_lockfile; restrict state access per environment and publish shared values explicitly. - →Testing: run
terraform fmt -check,terraform validate, andterraform teston every pull request, keep a small set of integration tests in a sandbox account, and fail the build on policy and security scan findings. - →Documentation: give each module a README with usage, inputs, outputs, and the supported provider range, and record architectural decisions such as state boundaries and account layout next to the code.
# Key takeaways
- →Key per-AZ resources by AZ name with
for_eachso changing the zone count does not renumber existing resources. - →A copied module is only as good as its validation: the flow log role and policy must exist in the module, and
terraform validateplusterraform testcatch the gaps. - →S3-native locking with
use_lockfilereplaces the DynamoDB lock table, and the lock object needs delete permission as well as read and write. - →
terraform_remote_stategives readers the entire state snapshot, so HashiCorp recommends publishing shared values to a separate location such as Parameter Store. - →Use mocked-provider
terraform testfor fast logic checks and Terratest v2 for real integration checks. - →Split state by account, environment, and layer, and give pipelines short-lived credentials scoped to their own state paths.
- →Treat the NAT gateway layout as a cost and resilience decision, and check regional NAT gateways before building new per-AZ logic.
# Further reading
Test yourself: Advanced Terraform assessment