Infrastructure as code · Advanced · 18 min
Test the Relay network module with tofu test and mock providers
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · OpenTofu 1.13.10 · hashicorp/aws 6.74
You will have a tofu test suite for Relay's network module that checks subnet ranges, input validation and outputs against a mocked AWS provider, and passes in seconds with no credentials.
On this page
Relay's network now lives in modules/network, and the root module calls it. Every change to that module can move a subnet, open a port or break a caller, and so far the only way to find out is to run a plan against AWS and read it. That needs credentials, a network connection and your attention each time.
tofu test gives you a faster loop. You write test files next to the module. Each file holds run blocks that plan or apply the module with inputs you choose, then assert on the result. With a mock provider, OpenTofu never calls AWS: it invents values for anything AWS would normally return, so the tests run with no account and no credentials, and the whole suite finishes in a few seconds.
In this part you write two test files. The first checks the plan: how many subnets there are, which ranges they get, which ones are public, and that bad inputs are refused. The second applies the module against the mock and checks the outputs that the root module and part 3's web server depend on. Part 7 runs this suite on every pull request, so keep the files when you finish.
Step 1 · Get the module ready to test
You test the module on its own, not the root module. That way the tests describe the module's contract (what it accepts and what it returns) and do not depend on Relay's backend, state or .tfvars files. Go to the module folder and confirm OpenTofu is the version this series uses:
cd ~/relay-demo/modules/network
tofu version
lsThe tests in this part check the module exactly as you wrote it in part 5. You do not change the module here; if a test fails, the test or the module has found a real difference, and you decide which one is wrong. The parts the tests rely on:
variables.tfdeclaresname_prefix(3 to 32 lowercase letters, digits or hyphens, starting with a letter),vpc_cidr(no default, and a validation block that accepts only an IPv4 range ending in/16) andssh_allowed_cidr(a validation block that accepts one IPv4 range and refuses0.0.0.0/0).main.tfreadsdata.aws_availability_zones.available, sorts the names it returns and takes the first two aslocal.zones.- It creates all four subnets in one resource,
aws_subnet.this, withfor_eachoverlocal.subnet_layout, keyedpublic-a,public-b,private-aandprivate-b. Each range iscidrsubnet(var.vpc_cidr, 8, netnum)with netnums 0, 1, 10 and 11, so with10.20.0.0/16theprivate-bsubnet is10.20.11.0/24. outputs.tfreturnsvpc_id,web_security_group_id, andpublic_subnet_idsandprivate_subnet_idsas maps keyed by availability zone name.
This is the locals block in main.tf that everything else hangs from:
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 }
}
}A mock provider still needs the real provider's schema, so the module folder needs its own tofu init. It has no backend, so this only installs the provider and writes a lock file:
tofu init
tofu validateThe hashicorp/aws 6.74 provider takes about 700 MB under .terraform. If you are on metered or prepaid mobile data, set a plugin cache once so the root module and the module folder share one copy instead of downloading it twice. Add plugin_cache_dir = "$HOME/.terraform.d/plugin-cache" to ~/.tofurc and create that folder, or export TF_PLUGIN_CACHE_DIR with the same path. After that first download, nothing in this tutorial uses the network.
Add the new folder to your .gitignore in ~/relay-demo if it is not already covered (.terraform/ matches it at any depth), and commit the module's .terraform.lock.hcl so the tests in part 7 use the same provider version you use.
Check it worked
tofu version prints OpenTofu v1.13.10 (any 1.13.x is fine), ls shows at least README.md, main.tf, outputs.tf, security.tf, variables.tf and versions.tf, and tofu validate prints Success! The configuration is valid.
Step 2 · Write a first test with a mocked provider
tofu test looks for files ending in .tftest.hcl in the current folder and in a tests folder. Use the tests folder so test code stays out of the module's own file list. Create it with a first test file:
mkdir -p tests
cat > tests/network.tftest.hcl <<'HCL'
mock_provider "aws" {}
variables {
name_prefix = "relay-test"
vpc_cidr = "10.20.0.0/16"
ssh_allowed_cidr = "203.0.113.7/32"
}
run "plans_four_subnets" {
command = plan
assert {
condition = length(aws_subnet.this) == 4
error_message = "Expected one public and one private subnet in each of two zones."
}
}
HCLThree blocks do the work:
mock_provider "aws" {}replaces everyawsprovider configuration for this file. Resources and data sources are never created or read from AWS; OpenTofu fills in their computed attributes with generated values.variablessets inputs for every run in the file. The module has no default forvpc_cidr, so the test gives it one.203.0.113.7/32is from a range reserved for documentation, so it can never be someone's real address.run "plans_four_subnets"is one test case.command = planmeans OpenTofu only plans, which is the cheapest kind of test. Theassertblocks are checked against that plan.
Run the suite:
tofu testCheck it worked
The run fails, and that is the useful part. The error is Invalid function argument on the slice(...) line in main.tf, saying the end index is greater than the length of the list, and the summary reads Failure! 0 passed, 1 failed. The mock answered the availability-zone lookup with an empty list, so there were no two zones to take. A mock invents values, but it cannot know what a list of zones should contain. You tell it in the next step.
Step 3 · Feed the zone lookup with override_data
override_data replaces the result of one data source with values you choose. Add it to the same file:
cat >> tests/network.tftest.hcl <<'HCL'
override_data {
target = data.aws_availability_zones.available
values = {
names = ["af-south-1a", "af-south-1b", "af-south-1c"]
}
}
HCL
tofu testThe names are the three zones of the Cape Town region. The module sorts them and takes the first two, so the -a subnets go in af-south-1a and the -b subnets in af-south-1b, and the third zone is ignored. Use your own region's zone names if you prefer; the module does not care which region it is in.
You put override_data at the top level of the file, so it applies to every run. You can also put it inside a single run block when one test needs a different answer, for example a region with only one zone.
Check it worked
The output lists tests/network.tftest.hcl... pass and run "plans_four_subnets"... pass, and ends Success! 1 passed, 0 failed. It takes a few seconds and needs no AWS credentials.
Step 4 · Assert the ranges, zones and the public flag
A count of four does not catch a subnet in the wrong range or zone, or a private subnet that hands out public IP addresses. Add a run that checks the values the module computes from its inputs, and a second run that changes an input to prove the ranges follow it:
cat >> tests/network.tftest.hcl <<'HCL'
run "plans_the_expected_ranges" {
command = plan
assert {
condition = aws_subnet.this["public-a"].cidr_block == "10.20.0.0/24"
error_message = "The public-a subnet should be 10.20.0.0/24."
}
assert {
condition = aws_subnet.this["private-b"].cidr_block == "10.20.11.0/24"
error_message = "The private-b subnet should be 10.20.11.0/24."
}
assert {
condition = aws_subnet.this["private-b"].availability_zone == "af-south-1b"
error_message = "The -b subnets should be in the second zone after sorting."
}
assert {
condition = alltrue([for key in ["public-a", "public-b"] : aws_subnet.this[key].map_public_ip_on_launch == true])
error_message = "Public subnets should give instances a public IP address."
}
assert {
condition = !anytrue([for key in ["private-a", "private-b"] : aws_subnet.this[key].map_public_ip_on_launch == true])
error_message = "Private subnets must not give instances a public IP address."
}
assert {
condition = aws_vpc_security_group_ingress_rule.ssh.cidr_ipv4 == "203.0.113.7/32"
error_message = "SSH must be open only to ssh_allowed_cidr."
}
}
run "uses_a_different_vpc_range" {
command = plan
variables {
vpc_cidr = "10.30.0.0/16"
}
assert {
condition = aws_subnet.this["public-b"].cidr_block == "10.30.1.0/24"
error_message = "Subnets should follow vpc_cidr."
}
}
HCL
tofu testThe variables block inside a run overrides the file-level one for that run only, so name_prefix and ssh_allowed_cidr still come from the top of the file.
Write expected values as literals, as here, not as the same cidrsubnet() call the module makes. A test that repeats the module's formula passes even when the formula is wrong.
Check it worked
Three runs pass and the summary reads Success! 3 passed, 0 failed. To see a failure report, change 10.20.11.0/24 in the test to 10.20.1.0/24 and run tofu test again: the failing assertion shows the line, the planned value "10.20.11.0/24", a diff, and your error message. Change it back before you continue.
Step 5 · Prove bad inputs are refused with expect_failures
The validation blocks on vpc_cidr and ssh_allowed_cidr protect every caller of the module. A test should prove they fire, so a later edit cannot quietly remove them. expect_failures turns an expected error into a pass:
cat >> tests/network.tftest.hcl <<'HCL'
run "rejects_a_vpc_that_is_not_a_16" {
command = plan
variables {
vpc_cidr = "10.20.0.0/24"
}
expect_failures = [var.vpc_cidr]
}
run "rejects_ssh_from_anywhere" {
command = plan
variables {
ssh_allowed_cidr = "0.0.0.0/0"
}
expect_failures = [var.ssh_allowed_cidr]
}
run "rejects_an_ssh_range_that_is_not_a_cidr" {
command = plan
variables {
ssh_allowed_cidr = "my-laptop"
}
expect_failures = [var.ssh_allowed_cidr]
}
HCL
tofu testThe SSH rule has two halves, a valid IPv4 range and not 0.0.0.0/0, so it gets one run for each. Dropping either half from the module now fails a test.
expect_failures only covers conditions you wrote yourself: variable validation, preconditions, postconditions and check blocks. It does not catch an error the provider raises. That is one more reason to validate inputs in the module, where a test can reach them.
Check it worked
Six runs pass: Success! 6 passed, 0 failed. To see the test protect you, change 10.20.0.0/24 in the test to the valid 10.20.0.0/16 and run again. That run fails with Missing expected failure and says var.vpc_cidr was expected to report an error but did not. Put the value back.
Step 6 · Check the outputs with an apply-mode run
Plan-mode tests check what the module intends to build. The root module and part 3's web server depend on something else: the outputs, and the IDs inside them. A run without command = plan applies the module, here against the mock, so nothing is created anywhere, and OpenTofu destroys the mocked resources when the file finishes.
Generated IDs are random strings, which are hard to assert on. mock_resource sets fixed values for one resource type. Put this in a second file, so each file says clearly what it mocks:
cat > tests/outputs.tftest.hcl <<'HCL'
mock_provider "aws" {
mock_resource "aws_vpc" {
defaults = {
id = "vpc-0relay000000test"
}
}
mock_resource "aws_subnet" {
defaults = {
id = "subnet-0relay00000test"
}
}
mock_resource "aws_security_group" {
defaults = {
id = "sg-0relay0000000test"
}
}
}
override_data {
target = data.aws_availability_zones.available
values = {
names = ["af-south-1a", "af-south-1b", "af-south-1c"]
}
}
variables {
name_prefix = "relay-test"
vpc_cidr = "10.20.0.0/16"
ssh_allowed_cidr = "203.0.113.7/32"
}
run "outputs_carry_mocked_ids" {
assert {
condition = output.vpc_id == "vpc-0relay000000test"
error_message = "vpc_id should come from the VPC."
}
assert {
condition = keys(output.public_subnet_ids) == ["af-south-1a", "af-south-1b"]
error_message = "public_subnet_ids should be keyed by zone name."
}
assert {
condition = output.private_subnet_ids["af-south-1b"] == "subnet-0relay00000test"
error_message = "private_subnet_ids should hold subnet IDs."
}
assert {
condition = aws_subnet.this["public-a"].vpc_id == output.vpc_id
error_message = "Every subnet should sit in the module's VPC."
}
assert {
condition = output.web_security_group_id == "sg-0relay0000000test"
error_message = "web_security_group_id should come from the web security group."
}
}
HCL
tofu test
tofu test -filter=tests/outputs.tftest.hcl
tofu fmt -check -recursivedefaults fill in computed attributes only. Anything the module sets itself, such as cidr_block, still comes from your configuration. Every subnet gets the same mocked ID, which is fine here: the assertions check that the outputs are wired to the right resources and keyed by zone name, not that IDs are unique. Since part 5, the web server reads values(module.network.public_subnet_ids)[0] and module.network.web_security_group_id, so these are exactly the names and keys a rename would break.
-filter runs a single file, which is handy while you work on one of them. tofu fmt -check -recursive checks the formatting of the test files as well as the module, so make it part of the same habit.
Check it worked
The full run lists both files and ends Success! 7 passed, 0 failed., the filtered run passes 1 passed, 0 failed, and tofu fmt -check -recursive prints nothing. The whole suite takes a few seconds.
Step 7 · Run the same files with terraform test
If your team also uses Terraform, these two files are written to work under terraform test in Terraform 1.17 as well. In a copy of the module with Terraform installed:
terraform init
terraform testThe differences worth knowing:
- Computed values during plan. OpenTofu fills mocked computed attributes, such as
id, during plan as well as apply. Terraform returns them as known after apply during plan unless you addoverride_during = planto themock_providerblock. OpenTofu 1.13 rejects that argument as unsupported. This is why every assertion on an ID in this tutorial sits in the apply-mode run, and the plan-mode runs only check values the module computes from its inputs. Keep to that split and one file serves both tools. - File names. OpenTofu also reads
.tofutest.hclfiles, and whennetwork.tofutest.hclandnetwork.tftest.hclsit side by side it uses only the.tofutest.hclone. Terraform ignores.tofutest.hcl. Use that pair when the two tools genuinely need different tests. - Registries and lock files.
terraform initinstalls the provider from the HashiCorp registry rather than the OpenTofu one. Run Terraform in its own copy of the folder so its init does not rewrite the lock file OpenTofu commits.
Check it worked
Under OpenTofu, tofu test passes seven runs with both files unchanged. If you try Terraform, terraform test should list the same seven run names. If it fails on an ID inside a plan-mode run, move that assertion into an apply-mode run.
Next steps
You now have a module whose layout, input checks and outputs are tested in seconds, with no account. What these tests cannot tell you is whether AWS accepts the plan: an instance type that is not offered in a zone, a quota, or an IAM permission only shows up against real AWS. An apply-mode test with a real provider against a sandbox account catches those. It is worth its cost before a release or after a provider major upgrade, not on every commit. It creates real resources, so it can bill while it runs, and you must make sure it cleans up even when a run fails.
- Run this suite on every pull request in Plan Relay changes in pull requests with GitHub Actions.
- Go further with conditions the tests can target: Check inputs with validation, preconditions and check blocks.
- Revisit how the module was extracted in Turn the Relay network into a reusable OpenTofu module.
- New to the plan and apply loop? Start with Manage infrastructure as code with OpenTofu.
Related tutorials
- Turn the Relay network into a reusable OpenTofu moduleYou 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.
- Store the Relay state in S3 with locking and OpenTofu state encryptionYou will create a state bucket from a separate bootstrap configuration, move the Relay state into it with S3 locking, and encrypt that state and every saved plan with OpenTofu's own encryption, ready to switch to AWS KMS.
- Repeat resources in Terraform with count, for_each and dynamic blocksYou will build a small Terraform 1.17 project that makes one file per page with count, watch count recreate the wrong things when a list shrinks, rebuild it with for_each and stable keys, shape the outputs with for expressions and splat, generate nested blocks with dynamic, and leave with a rule for when to use each.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials