Skip to main content

Infrastructure as code · Advanced · 25 min

Turn the Relay network into a reusable OpenTofu module

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · OpenTofu 1.13.10 · hashicorp/aws 6.74

You will move Relay's VPC, subnets, routes and web security group into a local modules/network module with its own inputs, outputs and README, and adopt the 18 running objects with moved blocks so the plan destroys nothing.

On this page

At the end of part 2, Relay's network lived in the root module in two files. network.tf holds the availability-zone lookup, the subnet layout, a VPC, four subnets in one for_each resource, an internet gateway, a public and a private route table, the internet route and the four route table associations. security.tf holds the web security group and its four rules. It works, but none of it can be reused. A second environment, a recovery copy in another Region or another small service would mean copying both files and editing names by hand.

In this part you move that code into a local module, modules/network, with typed inputs, a small set of outputs and a README. The hard part is not the code. OpenTofu tracks every object by its address, and moving a resource into a module changes its address from aws_vpc.main to module.network.aws_vpc.main. Without telling OpenTofu about the move, the next plan would destroy the whole network and build a new one, taking the web server down with it. You will see that plan, then fix it with moved blocks so the apply changes only addresses in the state.

Nothing you do here creates or deletes anything in AWS, so this part adds no cost. Part 6 writes tests for the module you build, so keep it at modules/network.

Step 1 · Take stock of what the network owns

Go to the project and hand OpenTofu your state passphrase, as in part 4. Every command in this part reads the encrypted state, so run the export line again in any new terminal:

Bash
cd ~/relay-demo
export TF_VAR_state_passphrase="$(cat ~/.config/relay/state-passphrase)"
tofu state list
tofu output

Among the lines from parts 1, 3 and 4 (the assets bucket and its settings, the IAM role and instance profile, the instance) are these 18 network objects from part 2:

Text
aws_internet_gateway.main
aws_route.public_internet
aws_route_table.private
aws_route_table.public
aws_route_table_association.this["private-a"]
aws_route_table_association.this["private-b"]
aws_route_table_association.this["public-a"]
aws_route_table_association.this["public-b"]
aws_security_group.web
aws_subnet.this["private-a"]
aws_subnet.this["private-b"]
aws_subnet.this["public-a"]
aws_subnet.this["public-b"]
aws_vpc.main
aws_vpc_security_group_egress_rule.all
aws_vpc_security_group_ingress_rule.http
aws_vpc_security_group_ingress_rule.https
aws_vpc_security_group_ingress_rule.ssh

There is also data.aws_availability_zones.available, which is a lookup rather than an object you own. If you gave anything in part 2 a different local name, write your names down now. You will need the exact addresses for the moved blocks later.

Decide what goes into the module before you write any of it. A good test is whether a second caller would want the thing unchanged:

  • In: the zone lookup and subnet layout, the VPC, the subnets, the internet gateway, both route tables, the internet route, the associations, and the web security group with its rules. Together they describe one shape of network, and nothing in them is specific to Relay.
  • Out: the provider block and Region, the backend and state encryption, the assets bucket, the instance and its IAM role. The provider and backend belong to whoever calls the module. The bucket and instance are what runs on the network, not the network.
  • Inputs, not constants: the name prefix, the VPC range and the SSH range. Anything that differs between dev and prod, or between Relay and the next service, is a variable.

Check it worked

You can point to each of the 18 addresses above in your own tofu state list output, and tofu output prints vpc_id, public_subnet_ids, private_subnet_ids and web_security_group_id among part 1's and part 3's outputs. The subnet maps are keyed by zone name, such as eu-west-1a. Keep the subnet IDs visible in your terminal: they must be the same at the end of this part.

Step 2 · Give the module its inputs and provider requirements

Create the folder. By convention a module keeps its requirements, inputs, resources and outputs in separate files:

Bash
mkdir -p modules/network

Write modules/network/versions.tf. A reusable module says which provider it needs and which versions it works with, as a range rather than an exact pin. It has no provider "aws" block. The caller's aws provider, with its Region, credentials and default tags, is passed in automatically:

Bash
cat > modules/network/versions.tf <<'HCL'
terraform {
  required_version = ">= 1.13.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 6.0, < 7.0"
    }
  }
}
HCL

A provider block inside a module looks harmless, but it ties every caller to one Region and stops them from using the module with count or for_each. The root module's lock file still decides the exact provider version: the range here only says what the module accepts. State encryption stays in the root too, because it is a setting of the state, and a module has no state of its own.

Now the inputs. They keep part 2's names, so the root passes var.vpc_cidr to vpc_cidr and var.ssh_allowed_cidr to ssh_allowed_cidr without any translation. The validation rules are part 2's, repeated here so every caller of the module gets them, not only Relay's root:

Bash
cat > modules/network/variables.tf <<'HCL'
variable "name_prefix" {
  type        = string
  description = "Prefix for every Name tag and the security group name, such as relay-dev."

  validation {
    condition     = can(regex("^[a-z][a-z0-9-]{2,31}$", var.name_prefix))
    error_message = "name_prefix must be 3 to 32 lowercase letters, digits or hyphens, starting with a letter."
  }
}

variable "vpc_cidr" {
  type        = string
  description = "Address range for the VPC. Must be a /16; subnets are the /24s numbered 0, 1, 10 and 11 inside it."

  validation {
    condition     = can(cidrhost(var.vpc_cidr, 0)) && endswith(var.vpc_cidr, "/16")
    error_message = "vpc_cidr must be a valid IPv4 range ending in /16, such as 10.20.0.0/16."
  }
}

variable "ssh_allowed_cidr" {
  type        = string
  description = "The one IPv4 range allowed to connect on port 22, usually one address as a /32."

  validation {
    condition     = can(cidrnetmask(var.ssh_allowed_cidr)) && var.ssh_allowed_cidr != "0.0.0.0/0"
    error_message = "ssh_allowed_cidr must be an IPv4 range such as 198.51.100.7/32, and never 0.0.0.0/0."
  }
}
HCL

name_prefix has no default on purpose: a module that silently names everything relay would surprise the next service that calls it.

Check it worked

ls modules/network lists variables.tf and versions.tf, and grep -c 'provider "aws"' modules/network/*.tf prints 0 for both files.

Step 3 · Move the resources into the module

Write modules/network/main.tf. Everything in it is part 2's network.tf, copied with its local names, keys, subnet numbers and tags unchanged. The only edit is local.name_prefix becoming var.name_prefix. Keeping the names identical is what makes the moves simple, and keeping the arguments identical is what keeps the plan empty:

Bash
cat > modules/network/main.tf <<'HCL'
data "aws_availability_zones" "available" {
  state = "available"
}

locals {
  # The first two zones, sorted so the choice is the same on every run.
  zones = slice(sort(data.aws_availability_zones.available.names), 0, 2)

  # One entry per subnet. The key is stable even if AWS adds zones.
  # zone is an index into local.zones; netnum picks the /24 inside the /16.
  subnet_layout = {
    "public-a"  = { tier = "public", zone = 0, netnum = 0 }
    "public-b"  = { tier = "public", zone = 1, netnum = 1 }
    "private-a" = { tier = "private", zone = 0, netnum = 10 }
    "private-b" = { tier = "private", zone = 1, netnum = 11 }
  }
}

resource "aws_vpc" "main" {
  cidr_block           = var.vpc_cidr
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = {
    Name = "${var.name_prefix}-vpc"
  }
}

resource "aws_subnet" "this" {
  for_each = local.subnet_layout

  vpc_id                  = aws_vpc.main.id
  availability_zone       = local.zones[each.value.zone]
  cidr_block              = cidrsubnet(var.vpc_cidr, 8, each.value.netnum)
  map_public_ip_on_launch = each.value.tier == "public"

  tags = {
    Name = "${var.name_prefix}-${each.key}"
    Tier = each.value.tier
  }
}

resource "aws_internet_gateway" "main" {
  vpc_id = aws_vpc.main.id

  tags = {
    Name = "${var.name_prefix}-igw"
  }
}

resource "aws_route_table" "public" {
  vpc_id = aws_vpc.main.id

  tags = {
    Name = "${var.name_prefix}-public"
  }
}

resource "aws_route" "public_internet" {
  route_table_id         = aws_route_table.public.id
  destination_cidr_block = "0.0.0.0/0"
  gateway_id             = aws_internet_gateway.main.id
}

resource "aws_route_table" "private" {
  vpc_id = aws_vpc.main.id

  tags = {
    Name = "${var.name_prefix}-private"
  }
}

resource "aws_route_table_association" "this" {
  for_each = aws_subnet.this

  subnet_id      = each.value.id
  route_table_id = local.subnet_layout[each.key].tier == "public" ? aws_route_table.public.id : aws_route_table.private.id
}
HCL

Then modules/network/security.tf, part 2's security.tf with the same single edit. Copy the descriptions character for character: changing a security group's description forces AWS to replace the group, and replacing the group would also force a new web server.

Bash
cat > modules/network/security.tf <<'HCL'
resource "aws_security_group" "web" {
  name        = "${var.name_prefix}-web"
  description = "Relay web server: HTTP and HTTPS from anywhere, SSH from one range"
  vpc_id      = aws_vpc.main.id

  tags = {
    Name = "${var.name_prefix}-web"
  }
}

resource "aws_vpc_security_group_ingress_rule" "http" {
  security_group_id = aws_security_group.web.id
  description       = "HTTP from anywhere"
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "tcp"
  from_port         = 80
  to_port           = 80
}

resource "aws_vpc_security_group_ingress_rule" "https" {
  security_group_id = aws_security_group.web.id
  description       = "HTTPS from anywhere"
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "tcp"
  from_port         = 443
  to_port           = 443
}

resource "aws_vpc_security_group_ingress_rule" "ssh" {
  security_group_id = aws_security_group.web.id
  description       = "SSH from the operator only"
  cidr_ipv4         = var.ssh_allowed_cidr
  ip_protocol       = "tcp"
  from_port         = 22
  to_port           = 22
}

resource "aws_vpc_security_group_egress_rule" "all" {
  security_group_id = aws_security_group.web.id
  description       = "All outbound traffic"
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "-1"
}
HCL

If your part 2 files differ from these in any argument (another description, an extra tag, other subnet numbers), copy your version instead. Any argument that changes on the way into the module shows up in the plan, and some, such as a security group's description or a subnet's cidr_block or availability_zone, replace the object.

Outputs are the module's public face. Every output is a promise to callers, so expose what they need today and nothing more. Relay's instance needs a public subnet and the security group, and the root already reports the VPC and subnet IDs. These four outputs keep part 2's names and part 2's shape, with subnet maps keyed by zone name, so nothing that reads them has to change. The internet gateway, the route tables and the public-a style keys stay inside:

Bash
cat > modules/network/outputs.tf <<'HCL'
output "vpc_id" {
  description = "ID of the VPC."
  value       = aws_vpc.main.id
}

output "public_subnet_ids" {
  description = "Public subnet ID per availability zone name, such as eu-west-1a."
  value       = { for key, subnet in aws_subnet.this : subnet.availability_zone => subnet.id if local.subnet_layout[key].tier == "public" }
}

output "private_subnet_ids" {
  description = "Private subnet ID per availability zone name, such as eu-west-1a."
  value       = { for key, subnet in aws_subnet.this : subnet.availability_zone => subnet.id if local.subnet_layout[key].tier == "private" }
}

output "web_security_group_id" {
  description = "ID of the security group for web servers in this network."
  value       = aws_security_group.web.id
}
HCL
tofu fmt -check -recursive modules/network

A map keyed by zone name tells a caller exactly where each subnet is, and a caller that wants a particular zone asks for it by name instead of trusting a list position.

Check it worked

tofu fmt -check -recursive modules/network prints nothing and returns to the prompt. If it prints a file name, run tofu fmt -recursive modules/network to fix the layout, then check again. grep -c local.name_prefix modules/network/*.tf prints 0 for every file.

Step 4 · Write the module README

A module with no README gets copied rather than called, because nobody can tell what it promises. Write a short one beside the code:

Bash
cat > modules/network/README.md <<'MD'
# network

One VPC across two availability zones, for a small public web service.

Creates: a VPC, one public and one private /24 subnet per zone, an internet
gateway, a public route table with a route to it, a private route table with
no way out, and a security group that allows HTTP and HTTPS from anywhere and
SSH from one range. No NAT gateway: private subnets cannot reach the internet.

The module has no provider block. It uses the caller's `aws` provider; pass
another one with `providers = { aws = aws.<alias> }` to build in a second
Region.

## Inputs

| Name | Type | Description |
| --- | --- | --- |
| `name_prefix` | string | Prefix for Name tags and the security group name, such as `relay-dev`. Required. |
| `vpc_cidr` | string | VPC range, which must be a `/16`. Subnets use netnums 0 and 1 (public) and 10 and 11 (private). |
| `ssh_allowed_cidr` | string | The one range allowed to reach port 22. `0.0.0.0/0` is rejected. |

## Outputs

| Name | Description |
| --- | --- |
| `vpc_id` | ID of the VPC. |
| `public_subnet_ids` | Map of availability zone name to public subnet ID. |
| `private_subnet_ids` | Map of availability zone name to private subnet ID. |
| `web_security_group_id` | ID of the web security group. |

## Example

    module "network" {
      source = "./modules/network"

      name_prefix      = "relay-dev"
      vpc_cidr         = "10.20.0.0/16"
      ssh_allowed_cidr = "203.0.113.10/32"
    }

## History

Resources moved here from the Relay root module in part 5. The moved blocks
live in the root module's moves.tf; keep them until every copy of the state
has been applied.
MD

Check it worked

grep -c '^## ' modules/network/README.md prints 4, for Inputs, Outputs, Example and History. Each variable in variables.tf and each output in outputs.tf has a row in the README's tables.

Step 5 · Call the module from the root

The resources now live in the module, so the root's network.tf and security.tf must go. Both have to go: if you keep security.tf, the root still declares aws_security_group.web with vpc_id = aws_vpc.main.id, a VPC the root no longer declares, and tofu validate fails. Rename them rather than delete them, so you can compare later (or rely on Git):

Bash
mv network.tf network.tf.before-module
mv security.tf security.tf.before-module

OpenTofu reads only files that end in .tf, so the renamed copies are ignored. Now write a new network.tf that calls the module with the same values part 2 used, so the names, ranges and rules come out identical:

Bash
cat > network.tf <<'HCL'
module "network" {
  source = "./modules/network"

  name_prefix      = local.name_prefix
  vpc_cidr         = var.vpc_cidr
  ssh_allowed_cidr = var.ssh_allowed_cidr
}
HCL

The root keeps variables.tf as it is: vpc_cidr and ssh_allowed_cidr are still set from dev.tfvars and prod.tfvars, and now flow into the module.

Next, the root outputs. Part 2 appended vpc_id, public_subnet_ids, private_subnet_ids and web_security_group_id to outputs.tf. Do not declare them again in network.tf, which would be a duplicate. Instead, open outputs.tf and change only the value line of each of the four. Before:

HCL
  value       = aws_vpc.main.id
  value       = { for key, subnet in aws_subnet.this : subnet.availability_zone => subnet.id if local.subnet_layout[key].tier == "public" }
  value       = { for key, subnet in aws_subnet.this : subnet.availability_zone => subnet.id if local.subnet_layout[key].tier == "private" }
  value       = aws_security_group.web.id

After, in the same four outputs and in the same order:

HCL
  value       = module.network.vpc_id
  value       = module.network.public_subnet_ids
  value       = module.network.private_subnet_ids
  value       = module.network.web_security_group_id

The output names, descriptions and map keys stay the same, so anything that reads tofu output (a script, or part 7's pipeline) sees no difference.

The web server from part 3 refers to the old addresses too. Open compute.tf and change the two network lines of aws_instance.web. Before, as part 3 wrote them:

HCL
  subnet_id                   = aws_subnet.this["public-a"].id
  vpc_security_group_ids      = [aws_security_group.web.id]

After:

HCL
  subnet_id                   = values(module.network.public_subnet_ids)[0]
  vpc_security_group_ids      = [module.network.web_security_group_id]

public-a is now a key inside the module, so the root picks the subnet from the output instead. values() returns a map's values in the order of its keys, and the keys are zone names, so [0] is the public subnet in the alphabetically first zone. That is exactly the subnet public-a named, because part 2 sorted the zones and put public-a in the first one. The ID is the same, so the instance is not touched.

Look for any other reference to the old addresses or to the locals that moved into the module:

Bash
grep -n -E '\baws_(vpc|subnet|internet_gateway|route|route_table|route_table_association|security_group|vpc_security_group_ingress_rule|vpc_security_group_egress_rule)\.|\blocal\.(zones|subnet_layout)\b' *.tf || echo "No old network references left"

Fix every line it prints until you see No old network references left. A new module source is something tofu init has to install, even when it is a local folder, so run it before validating:

Bash
tofu init -input=false
tofu validate

tofu init prints Initializing modules... followed by - network in modules/network, and leaves your S3 backend and providers as they were.

Check it worked

tofu validate prints Success! The configuration is valid. If it reports a reference to an undeclared resource, the grep above missed a line or security.tf is still in place. If it reports a duplicate output, the four outputs are declared in two files; keep the ones in outputs.tf.

Step 6 · Look at the plan without moved blocks

Run a plan now, before telling OpenTofu about the move. Read it, and do not apply it:

Bash
tofu plan -var-file=dev.tfvars

The state still has objects at aws_vpc.main and the others, and the configuration no longer declares them, so OpenTofu plans to destroy them. The configuration declares module.network.aws_vpc.main and the others, and the state has nothing there, so it plans to create them. The summary line counts the same 18 network objects under both to add and to destroy. On AWS the web server is caught up as well: its subnet_id would point to a subnet that does not exist yet, and a changed subnet_id forces a new instance, so the plan also replaces aws_instance.web.

Check it worked

The summary reads Plan: N to add, 0 to change, N to destroy. or similar, with at least 18 on each side, and the list includes aws_vpc.main will be destroyed. This is the plan you must never apply: the VPC would be rebuilt with new IDs and Relay would be offline until the new instance booted.

Step 7 · Record the moves

A moved block tells OpenTofu that an object at one address now belongs at another. Write one per resource in a new root file, moves.tf. When a resource uses for_each, the whole resource moves in one block and every instance (["public-a"], ["private-b"] and the rest) moves with it, so 12 blocks cover all 18 objects. If your addresses differed in the first step, use yours in the from lines:

Bash
cat > moves.tf <<'HCL'
# Part 5: the network moved from the root module into modules/network.
# Keep these until every copy of this state has been applied.

moved {
  from = aws_vpc.main
  to   = module.network.aws_vpc.main
}

moved {
  from = aws_subnet.this
  to   = module.network.aws_subnet.this
}

moved {
  from = aws_internet_gateway.main
  to   = module.network.aws_internet_gateway.main
}

moved {
  from = aws_route_table.public
  to   = module.network.aws_route_table.public
}

moved {
  from = aws_route.public_internet
  to   = module.network.aws_route.public_internet
}

moved {
  from = aws_route_table.private
  to   = module.network.aws_route_table.private
}

moved {
  from = aws_route_table_association.this
  to   = module.network.aws_route_table_association.this
}

moved {
  from = aws_security_group.web
  to   = module.network.aws_security_group.web
}

moved {
  from = aws_vpc_security_group_ingress_rule.http
  to   = module.network.aws_vpc_security_group_ingress_rule.http
}

moved {
  from = aws_vpc_security_group_ingress_rule.https
  to   = module.network.aws_vpc_security_group_ingress_rule.https
}

moved {
  from = aws_vpc_security_group_ingress_rule.ssh
  to   = module.network.aws_vpc_security_group_ingress_rule.ssh
}

moved {
  from = aws_vpc_security_group_egress_rule.all
  to   = module.network.aws_vpc_security_group_egress_rule.all
}
HCL
tofu fmt -check moves.tf network.tf outputs.tf compute.tf

The availability-zone data source needs no block. Data sources are read fresh on every plan, so the module simply reads its own copy.

Plan again, this time saving the plan to a file so the apply does exactly what you reviewed. Part 4's plan block encrypts the file with your passphrase:

Bash
tofu plan -var-file=dev.tfvars -out=relay.tfplan

Each network object now appears with a line like # aws_vpc.main has moved to module.network.aws_vpc.main, followed by its attributes with nothing marked for change.

Check it worked

The summary reads Plan: 0 to add, 0 to change, 0 to destroy. and there are 18 has moved to lines, one per object. If the plan still shows anything to add or destroy, compare its addresses with your moved blocks: a typo in a from address does not raise an error, it is just ignored. If it shows will be updated in-place or must be replaced on a moved object, an argument changed on the way into the module; make the module code match part 2 and plan again.

Step 8 · Apply the moves and confirm nothing changed in AWS

Apply the saved plan. It rewrites addresses in the state and makes no AWS API calls that change anything:

Bash
tofu apply relay.tfplan
rm relay.tfplan

The apply ends with Apply complete! Resources: 0 added, 0 changed, 0 destroyed. Look at the new addresses and the outputs:

Bash
tofu state list | grep '^module.network'
tofu output public_subnet_ids
tofu output private_subnet_ids

Finally, a plan with -detailed-exitcode exits with 0 when there is nothing to do, 2 when there are changes and 1 on an error, which makes it easy to script. Once it passes, remove the renamed copies of the old files:

Bash
tofu plan -var-file=dev.tfvars -detailed-exitcode
rm network.tf.before-module security.tf.before-module

Leave moves.tf in place. Your dev state has applied the moves, but any other copy has not: a teammate's workspace pointed at an old state, a prod environment that runs the same code with prod.tfvars and its own state key, or a restore from a state backup. For each of those, the moved blocks are the difference between a quiet apply and a rebuilt network. Remove them only when you are sure every state that used the old addresses has been applied with this code.

Because the module has no provider block, a second copy in another Region is a provider alias and a few lines away. For example, a recovery copy in Cape Town (af-south-1), closer to visitors in southern Africa, would look like this. Do not apply it unless you want it: it creates resources in a second Region, and af-south-1 is an opt-in Region that must first be enabled for your AWS account.

HCL
provider "aws" {
  alias  = "cape_town"
  region = "af-south-1"

  default_tags {
    tags = local.common_tags
  }
}

module "network_cape_town" {
  source = "./modules/network"

  providers = {
    aws = aws.cape_town
  }

  name_prefix      = "relay-dr"
  vpc_cidr         = "10.30.0.0/16"
  ssh_allowed_cidr = var.ssh_allowed_cidr
}

Check it worked

  • tofu state list shows 18 addresses starting with module.network.aws_ and none of the old root addresses.
  • The subnet IDs from tofu output are exactly the ones you noted in the first step, under the same zone-name keys.
  • tofu plan -var-file=dev.tfvars -detailed-exitcode prints No changes. Your infrastructure matches the configuration. and echo $? straight after it prints 0.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.