06-05 ended with a sentence that was also a promise: «conditions protect the deployment; tests protect the conditions. And module 7 takes care of the second half». This is that second half.
The problem it solves is concrete and counter-intuitive. You have written preconditions, postconditions, validations and check blocks. They are good controls. But they have three blind spots no control can cover about itself:
- They are only evaluated when somebody deploys. If nobody uses the
networkmodule with a single availability zone, nobody discovers that the precondition has a typo and never fires. - Nobody checks that they fail when they should. A
>=where a>belonged, a condition that is always true, anerror_messagethat refers to a variable that no longer exists. All of that passes review and passes theplan. - A refactor breaks them silently. Somebody reorganises the
locals, the precondition stops referring to what its author thought it did, and nobody notices until a consumer gets the cryptic error the precondition existed to avoid.
terraform test, native since 1.6, solves all three. And along the way it solves the other fear this platform has been carrying since module 4: refactoring a module that already has consumers. terraform-aws-ecomarket-network is used by ecomarket-infra and ecomarket-wholesale; changing something inside it today means crossing your fingers and staring at plans. With a test suite, it means running a thirty-second command.
This lesson walks the whole verification pyramid — from terraform fmt to Terratest — explains what is worth testing in infrastructure and what is not, and develops terraform test in depth, including mock_provider, which lets you test with no cloud, no credentials and without spending a penny.
- The infrastructure verification pyramid
The steps, from cheapest to most expensive. The rule is the usual one: the lower down, the more often it runs.
flowchart TD
E6["6. Runtime validation<br/><b>check</b> · continuous, non-blocking"]
E5["5. End-to-end · Terratest<br/>really deploys · minutes and money"]
E4["4. terraform test with apply<br/>integration · minutes"]
E3["3. terraform test with plan and mocks<br/>unit · SECONDS"]
E2["2. Conditions in the code<br/>validation · precondition · postcondition"]
E1b["1b. Static security analysis<br/>tfsec · checkov (07-04)"]
E1["1a. fmt · validate · tflint<br/>syntax and style · MILLISECONDS"]
E1 --> E1b --> E2 --> E3 --> E4 --> E5 --> E6
style E1 fill:#dcfce7,stroke:#15803d
style E1b fill:#dcfce7,stroke:#15803d
style E3 fill:#e0f2fe,stroke:#0369a1
style E5 fill:#fee2e2,stroke:#b91c1c
style E6 fill:#f3e8fd,stroke:#7c3aed
| Step | What it detects | Duration | Needs credentials | When it runs |
|---|---|---|---|---|
fmt |
Inconsistent formatting | < 1 s | No | On save, on every commit, in CI |
validate |
Syntax, types, references that do not exist | 1–3 s | No (after init) |
On every commit and in CI |
tflint |
Invalid provider attributes, non-existent instance types, conventions | 2–10 s | No | On every commit and in CI |
| Security analysis | Missing encryption, open ports, broad permissions | 5–30 s | No | On every PR (07-04) |
| Conditions | Assumptions broken in this deployment | Part of the plan | Yes | On every plan and apply |
test with plan + mocks |
Your logic: names, CIDRs, conditionals, contracts | 2–20 s | No | On every PR |
test with apply |
That the resources really do get created and fit together | 3–20 min | Yes | Nightly and before tagging |
| Terratest | That the deployed system works (HTTP, SSH, queries) | 10–40 min | Yes | Nightly, before a MAJOR |
check |
That the system works right now | Part of the plan | Yes | Always, and in a scheduled plan |
The highlighted row is the one that changes day-to-day life: unit tests in seconds, with no credentials and no cost. It is what lets them run on every pull request without anybody complaining.
And one observation about the shape of the pyramid in infrastructure, which sets it apart from the software one: step 6 does not exist in applications. A program that passes its tests goes on doing the same thing tomorrow; an infrastructure that passed its tests may be broken tomorrow because somebody touched something in the console, a certificate expired or a managed service changed. That is why the check blocks from 06-05 are not the top of the pyramid: they are a different, continuous layer that lives alongside all the others.
- What makes sense to test and what does not
The most expensive mistake when you start testing infrastructure is testing the provider. It goes like this:
# A USELESS test. It does not test your code: it tests that AWS works.
run "the_bucket_gets_created" {
command = apply
assert {
condition = aws_s3_bucket.images.id != ""
error_message = "The bucket has not been created."
}
}If the bucket is not created, the apply has already failed and the assertion is never evaluated. That test costs minutes of runtime and cannot detect any failure the apply did not detect already.
The rule: test YOUR logic, not the provider's. Your logic is everything sitting between the input variables and the arguments that reach the resource.
| Worth testing | Why | Example in EcoMarket |
|---|---|---|
| Name computation | A badly composed prefix collides between environments or exceeds the length limit | local.prefix + suffix ≤ 63 characters for a bucket |
| CIDR computation | cidrsubnet with the wrong bits gives overlapping subnets or subnets outside the VPC |
EcoMarket's 6 subnets do not overlap |
| Per-environment conditionals | A badly written count creates in dev something that should only exist in prod |
NAT only in staging and prod |
| Sizing logic | A badly resolved local.current deploys prod at dev size |
var.environments["prod"].multi_az == true |
| Module contracts | An output that changes shape breaks the consumers | private_subnets is a map with the expected keys |
| That the validations reject | A validation with a typo protects nothing | expect_failures (section 8) |
| Tag composition | A badly ordered merge loses mandatory tags |
Project, Environment, ManagedBy always present |
| Default values | A dangerous default (encryption off) goes unnoticed | storage_encrypted defaults to true |
| Not worth testing | Why |
|---|---|
| That the provider creates the resource | If it fails, the apply fails; the test adds nothing |
| That an assigned attribute has the assigned value | assert { condition = aws_instance.web.instance_type == "t3.micro" } with instance_type = "t3.micro" right above is a tautology |
| The cloud's behaviour | Whether S3 is durable or RDS takes backups is their job, not yours |
Things a validation already guarantees |
If the variable has a validation, test the validation with expect_failures, not every valid value |
| Things that change on every run | A generated identifier, a timestamp(): the test would be flaky |
The tautology rule, which is the one that avoids the most useless tests: if you can read the expected value directly in the resource's code three lines above, the test adds nothing. What adds value is testing what lies between the input and the resource: the function, the ternary, the for, the merge, the lookup.
- The floor:
fmt and validate
fmt and validateThey are the cheapest steps and the most underrated.
# fmt: canonical formatting. -check fails if something is not formatted,
# -recursive descends into subdirectories, -diff shows what would change.
terraform fmt -check -recursive -diff
# validate: syntax, types, references to things that do not exist,
# arguments the provider does not know. It requires a prior `init`
# (it needs the schemas), but it does NOT need credentials.
terraform init -backend=false # no backend: it does not touch the state
terraform validateThe -backend=false is the detail that makes this viable in CI: it downloads the providers and the modules, but it does not connect to the backend and does not need cloud credentials. It is what lets you validate a pull request from an outsider without giving them access to anything.
What validate does detect:
| Error | Example |
|---|---|
| A reference to something that does not exist | aws_vpc.main.id when the resource is called aws_vpc.this |
| An argument the provider does not know | storage_encripted = true (a typo) |
| An incompatible type | Passing a list where a string is expected |
| A missing required block | A provider with no region when there is no other source |
| A cycle in the dependency graph | A depends on B and B on A |
| A duplicate name | Two resource "aws_s3_bucket" "images" |
What it does not detect, and hence the need for the following steps:
- That
t3.mikrois not a valid instance type (the type is a string and the string is valid) → caught bytflint. - That the computed CIDR falls outside the VPC → caught by a
preconditionor byterraform test. - That the bucket has no encryption → caught by security analysis (07-04).
- That the module returns an empty map with certain inputs → caught by
terraform test.
- Linters:
tflint and the rules that really do catch errors
tflint and the rules that really do catch errorstflint fills the gap between validate and the tests: it knows the providers' catalogue and detects things that would only fail at apply time, once you have already waited three minutes.
# .tflint.hcl — ecomarket-infra's configuration
plugin "terraform" {
enabled = true
preset = "recommended" # language rules: names, types, versions
}
plugin "aws" {
enabled = true
version = "0.32.0"
source = "github.com/terraform-linters/tflint-ruleset-aws"
# deep_check queries the AWS API to verify that the referenced
# identifiers really exist. It is powerful and it NEEDS
# credentials: we only enable it in the nightly job,
# not in an outsider's PR.
deep_check = false
}
# --- Language rules, tuned ---
rule "terraform_naming_convention" {
enabled = true
format = "snake_case" # the convention from 07-01 §5
}
rule "terraform_required_version" { enabled = true }
rule "terraform_required_providers" { enabled = true }
rule "terraform_unused_declarations" { enabled = true } # dead variables and locals
rule "terraform_documented_variables" { enabled = true } # description mandatory
rule "terraform_documented_outputs" { enabled = true }
# Modules must pin a version: no branches and no `latest`.
rule "terraform_module_pinned_source" {
enabled = true
style = "flexible" # accepts ~> as well as exact versions
}
# --- AWS provider rules ---
rule "aws_instance_invalid_type" { enabled = true } # catches "t3.mikro"
rule "aws_db_instance_invalid_engine" { enabled = true }
rule "aws_iam_policy_document_gov_friendly_arns" { enabled = false } # not applicableWhat tflint catches and nobody else catches in under three minutes:
# 1. A non-existent instance type. validate accepts it (it is a string);
# AWS rejects it 90 seconds into the apply.
resource "aws_instance" "web" {
instance_type = "t3.mikro" # tflint: "t3.mikro" is an invalid value
}
# 2. A module with no pinned version. In a published module this means
# a third party's change can land in your plan without warning.
module "network" {
source = "ecomarket/ecomarket-network/aws" # tflint: module source is not pinned
}
# 3. A variable declared and never used: leftovers from a half-finished refactor.
variable "cache_class" {} # tflint: variable "cache_class" is declared but not usedCustom rules with tflint-ruleset-custom
You can write your own rules for internal conventions. It is more work than it looks — you have to compile a plugin in Go — so in practice most internal conventions are better enforced from the policy-over-the-plan step, with OPA and Conftest (07-04).
The difference between the two places matters and is worth pinning down:
| Control | Where | What it sees | Example |
|---|---|---|---|
| Linter | Over the source code | The text of the .tf file, unresolved |
«This module does not pin a version» |
| Policy over the plan | Over the resolved plan | The final values, with variables and functions already evaluated | «This SG ends up open to 0.0.0.0/0» |
A linter cannot know that cidr_blocks = var.allowed_ranges ends up being ["0.0.0.0/0"], because the value comes from a .tfvars file. A policy over the plan can, because the plan is already resolved. Each control sees a different thing and that is why you need both.
terraform test: anatomy of a test file
terraform test: anatomy of a test fileHere the central part begins. terraform test has been built into the CLI since 1.6 and it is written in HCL, not in Go or Python. There is no new language to learn.
Where the tests live
modules/network/
├── main.tf
├── variables.tf
├── outputs.tf
├── versions.tf
├── examples/
│ ├── complete/main.tf # the module 4 examples...
│ └── minimal/main.tf # ...which will now be test scenarios
└── tests/ # ← Terraform looks here by convention
├── unit.tftest.hcl # plan + mocks: seconds
├── validations.tftest.hcl # expect_failures: seconds
└── integration.tftest.hcl # a real apply: minutes and moneyTerraform looks for *.tftest.hcl files (and *.tftest.json) in the current directory and in the tests/ subdirectory. The directory can be changed with -test-directory=.
A crucial detail: the directory where you run terraform test is the module under test. From modules/network/, the tests see var.cidr, aws_subnet.private and output.private_subnets directly, with no module. prefix. That is what makes the assertions so readable.
The minimal file, commented
# modules/network/tests/unit.tftest.hcl
# --- 1. Default variables for EVERY `run` in this file.
# Each `run` can override the ones it needs.
variables {
base_name = "ecomarket-tests"
cidr = "10.20.0.0/16"
zones = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
subnet_bits = 8
create_nat = false
}
# --- 2. A mock provider: no credentials, no calls, no cost.
# Detailed in section 9.
mock_provider "aws" {}
# --- 3. Each `run` is a test case. They run IN ORDER
# and share state within the file.
run "three_zones_produce_three_private_subnets" {
command = plan # plan only: it creates nothing
assert {
condition = length(aws_subnet.private) == 3
error_message = format(
"With 3 zones there must be 3 private subnets, %d have been planned.",
length(aws_subnet.private),
)
}
assert {
# Check that they are in DIFFERENT zones: three subnets in the
# same zone are not high availability, and it is a fault that
# is only noticed on the day a zone goes down.
condition = length(distinct([
for s in aws_subnet.private : s.availability_zone
])) == 3
error_message = "The private subnets have ended up in fewer than 3 zones."
}
}
run "the_cidrs_do_not_overlap_and_fit_inside_the_vpc" {
command = plan
assert {
# cidrsubnet with 8 bits over a /16 produces a /24. The real
# check is that every CIDR is distinct: a botched computation
# (repeated indices) would give identical subnets and the apply
# would fail two minutes in with a provider error.
condition = length(distinct([
for s in aws_subnet.private : s.cidr_block
])) == length(aws_subnet.private)
error_message = "There are duplicate subnet CIDRs: check the index computation."
}
assert {
condition = alltrue([
for s in aws_subnet.private : startswith(s.cidr_block, "10.20.")
])
error_message = "One of the subnets has ended up outside the VPC range."
}
}The run block from the inside
| Argument | What it does | Default |
|---|---|---|
command |
plan or apply |
apply |
plan_options |
refresh, replace, target |
— |
variables |
Variables for this run, overriding the file's |
The file's |
providers |
Reassign providers (useful with aliases) | The module's |
module |
Run another module instead of the one under test | The module under test |
assert |
One or more checks | — |
expect_failures |
Addresses that must fail | — |
And two properties of the execution model that have to be clear from the start:
- The
runblocks in a file execute in order and share the state. Arunwithapplycreates resources the nextrunsees. This allows progressive scenarios: create, then modify, then verify. - Each
.tftest.hclfile is independent and starts with a clean state. That is why one file per kind of test is better than one giant file.
command = plan versus command = apply
command = plan versus command = applyThis is the decision with the biggest impact on the cost and the speed of your test suite.
| Aspect | command = plan |
command = apply |
|---|---|---|
| Creates resources | No | Yes, for real |
| Duration | Seconds | Minutes |
| Cost | €0 | Whatever the created resources cost |
| Credentials | No, with mock_provider |
Yes |
| Sees computed attributes | No: they are (known after apply) |
Yes, with their real values |
| Evaluates preconditions | The ones that do not depend on computed attributes | All of them |
| Evaluates postconditions | No (they depend on the created resource) | Yes |
| Risk of leaving rubbish behind | None | Yes, if it fails halfway |
The key limitation of plan is the computed-attributes row, and it produces an error that is baffling the first time:
run "this_fails_with_plan" {
command = plan
assert {
# The ARN is assigned by AWS on creation: in a plan it is unknown.
condition = startswith(aws_s3_bucket.images.arn, "arn:aws:s3:::")
error_message = "The ARN does not have the expected format."
}
}The practical rule: with plan you test what you compute; with apply, what the cloud returns. And since almost everything worth testing is what you compute (section 2), most tests should use plan.
There is a very useful exception: with mock_provider, computed attributes do have values, because the mock invents them. That lets you test with plan things that would normally require apply, and it is why section 9 matters so much.
assert: checking what the module produces
assert: checking what the module producesAn assert has the same shape as the conditions in 06-05: a boolean condition and an error_message. The difference is where it lives and when it is evaluated.
# modules/data/tests/unit.tftest.hcl
variables {
base_name = "ecomarket-dev"
suffix = "brown-cat"
vpc_id = "vpc-0123456789abcdef0"
subnets = { "eu-west-1a" = "subnet-aaa", "eu-west-1b" = "subnet-bbb" }
db_class = "db.t3.micro"
db_password = "very-long-test-password-1234"
}
mock_provider "aws" {}
mock_provider "random" {}
run "the_name_respects_the_s3_limit" {
command = plan
assert {
# S3 limits a bucket name to 63 characters. With a long project
# and a long environment, the prefix + the random suffix overflow,
# and the apply fails three minutes in with an opaque error.
condition = length(aws_s3_bucket.images.bucket) <= 63
error_message = format(
"The bucket name is %d characters long and S3 allows 63: '%s'.",
length(aws_s3_bucket.images.bucket),
aws_s3_bucket.images.bucket,
)
}
assert {
# Lower case and no underscores: S3's naming rules.
condition = can(regex("^[a-z0-9][a-z0-9.-]*[a-z0-9]$", aws_s3_bucket.images.bucket))
error_message = "The bucket name does not comply with S3's rules."
}
}
run "production_enables_multi_az_and_retention" {
command = plan
variables {
# Only what changes relative to the file's `variables` block.
base_name = "ecomarket-prod"
db_class = "db.t3.medium"
high_availability = true
retention_days = 30
protect_deletion = true
}
assert {
condition = aws_db_instance.this.multi_az == true
error_message = "Production must be deployed across several zones."
}
assert {
condition = aws_db_instance.this.backup_retention_period >= 7
error_message = "Production requires at least 7 days of backup retention."
}
assert {
condition = aws_db_instance.this.storage_encrypted == true
error_message = "Encryption at rest is mandatory in every environment."
}
assert {
condition = aws_db_instance.this.deletion_protection == true
error_message = "Production must have deletion protection."
}
}
run "the_mandatory_tags_are_present" {
command = plan
assert {
condition = alltrue([
for key in ["Project", "Environment", "ManagedBy"] :
contains(keys(aws_db_instance.this.tags), key)
])
error_message = format(
"Mandatory tags are missing. Present: %s",
join(", ", keys(aws_db_instance.this.tags)),
)
}
}Look at the third assertion in the second run: storage_encrypted == true. It might look like one of section 2's tautologies — it is written that way in the resource — but it is not, and the difference is subtle and important: the test stops anybody changing it. It is a regression control over a security decision. Exercise 2 in 07-02 showed somebody removing exactly that line in a PR; with this test, the pipeline rejects it before any human looks at it.
That is the criterion for testing something that looks obvious: do I mind if somebody changes it without noticing? If the answer is yes, the test is worth it however trivial it appears.
Testing the outputs: the module's contract
run "the_output_contract_is_maintained" {
command = plan
assert {
# The shape of the output is the module's public API. Changing it
# breaks ALL the consumers, and the error shows up on their side,
# far from where the change was made.
condition = alltrue([
for z, s in output.private_subnets :
alltrue([
contains(keys(s), "id"),
contains(keys(s), "cidr"),
contains(keys(s), "zone"),
])
])
error_message = "The private_subnets output has changed shape: each entry must have id, cidr and zone."
}
assert {
condition = length(keys(output.private_subnets)) == length(var.zones)
error_message = "The output must have one entry per requested zone."
}
}This test is what lets you keep the promise made at the start: refactoring a published module without fear. You can reorganise the locals, swap count for for_each, extract a submodule or rewrite the CIDR computation. As long as this test passes, the consumers notice nothing. And if you break it, you know in twenty seconds on your own machine, not when the ecomarket-wholesale team raises a ticket three weeks later.
expect_failures: checking that it fails when it should
expect_failures: checking that it fails when it shouldThis is where the literal debt from 06-05 gets paid.
An assert checks that the module produces the right thing with correct inputs. expect_failures checks the opposite and is just as important: that the module rejects incorrect inputs.
# modules/network/tests/validations.tftest.hcl
mock_provider "aws" {}
variables {
base_name = "test"
cidr = "10.20.0.0/16"
zones = ["eu-west-1a", "eu-west-1b"]
subnet_bits = 8
}
# --- Case 1: a single zone must be rejected (variable validation) ---
run "a_single_zone_must_fail" {
command = plan
variables {
zones = ["eu-west-1a"]
}
# The exact address of what must fail. If it does NOT fail,
# the test fails: that is exactly what we want to detect.
expect_failures = [var.zones]
}
# --- Case 2: a CIDR that is too small (variable validation) ---
run "a_cidr_that_is_too_small_must_fail" {
command = plan
variables {
cidr = "10.20.0.0/26" # /26 + 8 bits = /34, which does not exist
}
expect_failures = [var.cidr]
}
# --- Case 3: NAT with no public subnets (a resource precondition) ---
run "nat_without_public_subnets_must_fail" {
command = plan
variables {
create_nat = true
create_public = false
}
# Here the address is that of the RESOURCE whose precondition must fire.
expect_failures = [aws_nat_gateway.main]
}
# --- Case 4: the output contract (a precondition on an output) ---
run "one_zone_breaches_the_output_contract" {
command = plan
variables {
zones = ["eu-west-1a"]
skip_zones_validation = true # a back door only for this test
}
expect_failures = [output.private_subnets]
}Which addresses expect_failures accepts
| Address | What it checks | Example |
|---|---|---|
var.<name> |
A validation block on that variable |
var.zones |
<type>.<name> |
A precondition or postcondition on that resource |
aws_nat_gateway.main |
data.<type>.<name> |
Conditions on a data source | data.aws_ami.web |
output.<name> |
A precondition on that output |
output.private_subnets |
check.<name> |
An assert inside a check block |
check.correct_account |
The four rules that avoid the expect_failures traps
1. The test fails if there is NO failure. That is the whole point of the mechanism. If somebody relaxes the zones validation from >= 2 to >= 1, the case-1 run stops failing, and terraform test reports it as an error:
2. A run with expect_failures must not have assert blocks. If the run ends in failure, the assertions are never evaluated. Mixing them produces tests that appear to check more than they do.
3. The address must be exact. expect_failures = [var.zones] checks that that specific variable's validation fails. If the run fails for another reason — a typo in the test file, a different validation — the test is reported as a failure, not as a success. That is precisely the desired behaviour: it protects against tests that «pass» by accident.
4. One bad input per run. If a run sets two invalid variables at once, Terraform aborts at the first and never checks the second. The second validation would go untested and nobody would notice.
# BAD: if var.cidr fails first, var.zones is never checked.
run "bad_inputs" {
variables {
cidr = "10.20.0.0/26"
zones = ["eu-west-1a"]
}
expect_failures = [var.cidr, var.zones]
}
# GOOD: one run per validation, with all the other inputs correct.
run "a_bad_cidr_fails" {
variables { cidr = "10.20.0.0/26" }
expect_failures = [var.cidr]
}
run "insufficient_zones_fails" {
variables { zones = ["eu-west-1a"] }
expect_failures = [var.zones]
}This is the section that closes the circle opened in module 6. The conditions you wrote there are no longer good-faith statements: they are behaviour verified on every pull request.
mock_provider: testing with no cloud and no credentials
mock_provider: testing with no cloud and no credentialsmock_provider is the feature that makes unit testing viable in infrastructure. It replaces the real provider: there are no API calls, no credentials, no cost and no latency.
# The minimal form: every computed attribute is filled in
# with automatically generated values.
mock_provider "aws" {}With that, a terraform test that used to take three minutes and spend money now takes five seconds and spends nothing. And, most importantly: it works on the laptop of somebody who has no AWS account, which is what makes the tests actually get run rather than being something only the pipeline does.
Controlling what the mock returns
The automatically generated values are random strings, and sometimes you need them to have a shape:
mock_provider "aws" {
# Default values for ALL resources of a type.
mock_resource "aws_s3_bucket" {
defaults = {
arn = "arn:aws:s3:::mock-bucket"
bucket_regional_domain_name = "mock-bucket.s3.eu-west-1.amazonaws.com"
hosted_zone_id = "Z1BKCTXD74EZPE"
}
}
mock_resource "aws_db_instance" {
defaults = {
address = "mock-db.abc123.eu-west-1.rds.amazonaws.com"
port = 5432
endpoint = "mock-db.abc123.eu-west-1.rds.amazonaws.com:5432"
status = "available"
}
}
# And for data sources too.
mock_data "aws_caller_identity" {
defaults = {
account_id = "123456789012" # EcoMarket's dev account
arn = "arn:aws:iam::123456789012:role/ecomarket-terraform-dev"
user_id = "AROAEXAMPLEID:tests"
}
}
mock_data "aws_region" {
defaults = { name = "eu-west-1" }
}
}With mock_data "aws_caller_identity" you can test the account guard from 06-05 with no credentials, which is exactly the kind of thing that previously could only be checked by deploying:
# infra/app/tests/guards.tftest.hcl
variables {
environment = "prod"
# ... the rest of the minimal variables
}
# Scenario: the pipeline says "prod" but the active credentials
# are the dev ones. The guard MUST block the apply.
mock_provider "aws" {
mock_data "aws_caller_identity" {
defaults = { account_id = "123456789012" } # ← the DEV account
}
}
run "the_guard_blocks_when_the_account_does_not_match" {
command = plan
# terraform_data.guard_account carries the precondition that blocks
# in production (06-05 §7). If somebody deletes it or relaxes it,
# this test fails.
expect_failures = [terraform_data.guard_account]
}This test is remarkable: it verifies a security control, with no cloud, in two seconds, on every PR. It is the concrete answer to «and who checks that the guard works?».
Overriding a specific resource inside a run
override_resource, override_data and override_module fine-tune the mock for one case:
run "the_connection_url_is_composed_correctly" {
command = plan
# For this run only: pin exactly what the DB returns.
override_resource {
target = aws_db_instance.this
values = {
address = "db.test.local"
port = 5432
endpoint = "db.test.local:5432"
}
}
assert {
# What is being tested is OUR composition of the URL, with the
# DB's value already pinned. This is testing your logic, not the cloud.
condition = output.connection_url == "postgresql://[email protected]:5432/ecomarket"
error_message = format("Incorrect connection URL: %s", output.connection_url)
}
}
run "without_planning_the_whole_network_module" {
command = plan
# override_module avoids planning a complete module and returns
# its outputs directly. Useful when the child module is slow
# or when what is being tested sits above it.
override_module {
target = module.network
outputs = {
vpc_id = "vpc-mock"
private_subnets = {
"eu-west-1a" = { id = "subnet-aaa", cidr = "10.20.1.0/24", zone = "eu-west-1a" }
"eu-west-1b" = { id = "subnet-bbb", cidr = "10.20.2.0/24", zone = "eu-west-1b" }
}
}
}
assert {
condition = length(aws_db_subnet_group.this.subnet_ids) == 2
error_message = "The subnet group must use both private subnets."
}
}What mocks do NOT test
It is important to be honest about this, because a mock-based test suite can give a false sense of security:
| Not tested | Consequence |
|---|---|
| That the provider accepts your arguments | An argument with an invalid value passes the test and fails at apply |
| Account quotas and limits | «5 elastic IP addresses per region» does not exist in the mock |
| IAM permissions | The mock never returns AccessDenied |
| Real service behaviours | That a bucket with that name already exists, that a zone has no capacity |
| Timings and implicit dependencies | A resource that takes 20 minutes or that needs another to be ready |
That is why mocks are step 3 and not the last one. Integration tests with a real apply are still necessary, they are just run once a day rather than on every commit.
module inside run and the use of examples/
module inside run and the use of examples/In 04-02 you wrote examples/ with one justification: «documentation that cannot lie». Now they earn their second value: they are test scenarios that are already written.
The module block inside a run runs a module other than the one being tested. It serves two purposes: setting up auxiliary infrastructure and running a complete example.
# modules/network/tests/examples.tftest.hcl
#
# Each `run` runs one of the module's examples. If somebody
# changes the module's interface and forgets to update the example,
# these tests fail: the examples lose the ability to lie.
mock_provider "aws" {}
run "the_minimal_example_plans" {
command = plan
module {
source = "./examples/minimal"
}
assert {
condition = length(module.network.private_subnets) >= 2
error_message = "The minimal example must produce at least 2 private subnets."
}
}
run "the_complete_example_plans_with_nat" {
command = plan
module {
source = "./examples/complete"
}
assert {
condition = module.network.nat_id != null
error_message = "The complete example must create the NAT gateway."
}
}Note the detail: inside a run with module, the addresses carry the module.network. prefix because the module under test is now the example, not network. It is the most common source of confusion when writing these tests.
Auxiliary infrastructure with a setup run
The other use of module is to stand up what the module under test needs and does not create:
# modules/data/tests/integration.tftest.hcl
# WARNING: this file does a REAL APPLY. It creates resources that cost
# money. It runs in the nightly job, not on every PR.
variables {
base_name = "ecomarket-test"
suffix = "swift-cat"
db_class = "db.t3.micro" # free tier
db_password = "test-only-password-1234"
}
# --- Step 1: create the network the `data` module needs. ---
run "prepare_network" {
command = apply
module {
source = "../network" # the sibling module, not the one under test
}
variables {
base_name = "ecomarket-test"
cidr = "10.99.0.0/16"
zones = ["eu-west-1a", "eu-west-1b"]
subnet_bits = 8
create_nat = false # $33/month we are not going to spend on tests
}
}
# --- Step 2: test the `data` module against that network. ---
run "the_database_is_created_and_reachable" {
command = apply
variables {
# The previous run's outputs are referenced by its name.
vpc_id = run.prepare_network.vpc_id
subnets = run.prepare_network.private_subnets
}
assert {
condition = aws_db_instance.this.status == "available"
error_message = "The database has not come up as available."
}
assert {
# This DOES require a real apply: the endpoint is assigned by AWS.
condition = can(regex("\\.rds\\.amazonaws\\.com$", aws_db_instance.this.address))
error_message = format("Unexpected endpoint: %s", aws_db_instance.this.address)
}
}run.prepare_network.vpc_id is the mechanism that chains steps: a run's outputs are available to the following ones. And the cleanup is automatic: when the file finishes, Terraform destroys everything it created, in reverse order. That guarantee is what makes integration tests bearable; the cases where it fails are dealt with in section 15.
Cost warning. A test file with
command = applycreates real resources and bills for as long as they exist. An RDSdb.t3.microcosts little if it lives for eight minutes, but a test that fails and leaves the instance orphaned bills until somebody finds it. Before adding integration tests: always use a separate test account, set a budget alert, and make sure the sweeper from 06-01 also sweeps up what the tests leave behind.
- Running the tests and reading the output
# Run every test in the current module.
cd modules/network
terraform init -backend=false # required: it downloads the providers
terraform testtests/unit.tftest.hcl... in progress
run "three_zones_produce_three_private_subnets"... pass
run "the_cidrs_do_not_overlap_and_fit_inside_the_vpc"... pass
tests/unit.tftest.hcl... tearing down
tests/unit.tftest.hcl... pass
tests/validations.tftest.hcl... in progress
run "a_single_zone_must_fail"... pass
run "a_cidr_that_is_too_small_must_fail"... pass
run "nat_without_public_subnets_must_fail"... fail
Error: Expected failure for aws_nat_gateway.main, but no failure occurred.
on tests/validations.tftest.hcl line 34, in run "nat_without_public_subnets_must_fail":
34: expect_failures = [aws_nat_gateway.main]
tests/validations.tftest.hcl... tearing down
tests/validations.tftest.hcl... fail
Failure! 1 passed, 1 failed.That failure says something very specific: the NAT's precondition is not firing. Either it was deleted in a refactor, or the condition has been relaxed, or the resource is no longer called that. Without this test, the failure would show up on the day somebody set create_nat = true with no public subnets and got an opaque provider error halfway through an apply.
The useful arguments
# A single file: the normal thing while you are writing a test.
terraform test -filter=tests/validations.tftest.hcl
# Several files.
terraform test -filter=tests/unit.tftest.hcl -filter=tests/validations.tftest.hcl
# Variables from outside (from the pipeline, for instance).
terraform test -var="region=eu-west-1" -var-file=tests/values.tfvars
# Verbose output: it prints the plan or the state of each `run`.
# Essential for debugging an assertion you do not understand.
terraform test -verbose
# JSON format, for the pipeline to process.
terraform test -json | jq -r 'select(.type=="test_run") | "\(.test_run.status) \(.test_run.name)"'
# From outside the module's directory.
terraform -chdir=modules/network test-filter is the one used most day to day: while you are writing a new test, running only its file brings the cycle down from twenty seconds to three. And -verbose is the first resort when an assertion fails and you do not know why, because it prints the resolved plan with the real values.
- Cost and duration: EcoMarket's strategy
Infrastructure tests have a property software tests do not: some of them cost money every time they run. Ignoring that leads to one of two things: either a suite nobody runs because it takes forty minutes, or an unexpected invoice.
| Kind of test | Duration | Cost per run | Credentials | Sustainable frequency |
|---|---|---|---|---|
fmt + validate |
2–4 s | €0 | No | Every commit |
tflint |
2–10 s | €0 | No | Every commit |
test with plan + mocks |
5–20 s | €0 | No | Every PR, several times |
test with a real plan (no mocks) |
20–60 s | €0 (reads only) | Yes, read-only | Every PR |
test with apply (network + DB) |
8–15 min | €0.10–0.50 | Yes, write | Nightly |
test with apply (the whole platform) |
20–35 min | €1–3 | Yes | Nightly or before tagging |
| End-to-end Terratest | 25–45 min | €2–5 | Yes | Nightly, before a MAJOR |
The strategy that follows from that table:
flowchart TD
PR["Pull request opened"] --> R1["fmt · validate · tflint<br/>security analysis<br/><b>< 30 s</b>"]
R1 --> R2["terraform test<br/>plan + mock_provider<br/><b>< 30 s</b>"]
R2 --> R3["plan against dev<br/>posted on the PR<br/><b>1-2 min</b>"]
R3 --> REV["Human review<br/>(the 07-02 checklist)"]
REV --> MERGE["Merge to main<br/>→ apply in dev"]
NIGHT["Nightly job<br/>02:00"] --> N1["terraform test with apply<br/>in the test account<br/><b>15-30 min</b>"]
N1 --> N2["End-to-end Terratest<br/><b>30-45 min</b>"]
N2 --> N3["Drift plan across the<br/>3 environments (07-01 §11)"]
N3 --> N4["destroy and verification<br/>that nothing is left"]
TAG["Before tagging<br/>a module"] --> T1["The COMPLETE suite<br/>unit + integration<br/>+ examples"]
style R2 fill:#e0f2fe,stroke:#0369a1
style N1 fill:#fef9c3,stroke:#a16207
style T1 fill:#f3e8fd,stroke:#7c3aed
The three rules that hold the scheme together:
- In the PR, nothing that costs money or takes more than two minutes. If the feedback cycle goes beyond that, people stop running the tests locally and start pushing commits «to see if it passes».
- The expensive things run at night, in a separate account, with a budget alert and a sweeper that destroys anything left orphaned.
- The complete suite before tagging a module version. It is the only moment when waiting forty minutes is acceptable, because what gets published is going to be consumed by others.
- Terratest: when it pays off, and a commented example
Terratest is a Go library that wraps the Terraform CLI and lets you write tests in Go. It existed years before terraform test and it still has a niche of its own.
The honest comparison
| Criterion | terraform test (native) |
Terratest |
|---|---|---|
| Language | HCL, the one you already know | Go: you have to know it or learn it |
| Installation | None: it comes with the CLI | Go, modules, dependencies |
| Without the cloud (mocks) | Yes, mock_provider |
Not natively |
| Assertions over the plan | Yes, native and straightforward | You have to parse the JSON |
| Verifying the system WORKS | No: it does no HTTP or SSH | Yes: that is its whole reason for being |
| Waits and retries | No | Yes, with configurable timeouts |
| Testing non-Terraform code | No | Yes: Docker, Kubernetes, Packer, Helm |
| Parallel execution | Per file | Yes, with t.Parallel() |
| Cleanup after a failure | Automatic | Manual (defer), and rubbish can be left behind |
| Learning curve | Low | Medium-high |
| Maintenance | Low | High: it is Go code that also ages |
The decision criterion, in one sentence: terraform test checks that Terraform produces the right configuration; Terratest checks that the deployed system does what it should. If your question is «is the CIDR computed correctly?», it is the native test. If it is «does the website return 200 on /health and does the database accept connections from the web tier?», it is Terratest.
A commented example
// test/ecomarket_platform_test.go
//
// End-to-end test: deploys the complete platform in the test
// account, verifies that it really responds, and destroys it.
// Duration: ~30 min. Cost: ~€2. It runs at night.
package test
import (
"fmt"
"testing"
"time"
"github.com/gruntwork-io/terratest/modules/http-helper"
"github.com/gruntwork-io/terratest/modules/random"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
)
func TestEcoMarketPlatform(t *testing.T) {
// t.Parallel lets several tests run at once. It requires
// each of them to use unique names: hence the random suffix.
t.Parallel()
// A unique suffix: without it, two simultaneous runs collide on
// global names (S3 buckets) and both fail.
suffix := random.UniqueId()
baseName := fmt.Sprintf("ecomarket-e2e-%s", suffix)
options := &terraform.Options{
TerraformDir: "../examples/complete",
Vars: map[string]interface{}{
"base_name": baseName,
"environment": "test",
"web_class": "t3.micro", // free tier
"db_class": "db.t3.micro", // free tier
"create_nat": false, // $33/month we do not spend
},
EnvVars: map[string]string{
"AWS_DEFAULT_REGION": "eu-west-1",
"AWS_PROFILE": "ecomarket-test", // a SEPARATE account
},
// Retries for known, transient API errors.
// Without this, a 30-minute test is lost to a rate-limiting
// error 28 minutes in.
RetryableTerraformErrors: map[string]string{
"RequestLimitExceeded": "AWS API rate limiting",
"InternalError": "Transient internal AWS error",
"Throttling": "Request throttling",
},
MaxRetries: 3,
TimeBetweenRetries: 10 * time.Second,
}
// defer guarantees the destroy EVEN IF the test fails or panics.
// It is the most important line in the file: without it, a
// failure leaves infrastructure billing indefinitely.
defer terraform.Destroy(t, options)
// InitAndApply: init + apply -auto-approve. It fails the test if it fails.
terraform.InitAndApply(t, options)
// --- Verification 1: the outputs have the expected shape ---
// terraform test would do this too. It is included because it is cheap
// and because if it fails here, nothing else makes sense.
endpoints := terraform.OutputMap(t, options, "endpoints")
assert.Contains(t, endpoints, "web")
assert.Contains(t, endpoints, "db")
// --- Verification 2: WHAT terraform test CANNOT DO ---
// A real HTTP request against the freshly deployed platform.
healthURL := fmt.Sprintf("https://%s/health", endpoints["web"])
// HttpGetWithRetry retries until it responds or the time runs
// out. It is essential: a load balancer takes 2-4 minutes to
// have healthy targets, and an immediate check always fails.
http_helper.HttpGetWithRetryWithCustomValidation(
t,
healthURL,
nil, // default TLS configuration
30, // 30 attempts...
10*time.Second, // ...every 10 s = up to 5 minutes
func(code int, body string) bool {
// The real validation: 200 AND the expected body. A 200
// with a load-balancer error page does not count.
return code == 200 && body == `{"status":"ok"}`
},
)
// --- Verification 3: idempotence ---
// A second apply must change nothing. If it does, there is a
// non-deterministic value in the configuration (a timestamp(), a
// data source with most_recent) and the plan will never converge.
// It is one of the hardest failures to detect any other way.
terraform.ApplyAndIdempotent(t, options)
}The three lines that justify this test's existence, and that terraform test cannot write:
HttpGetWithRetry: a real HTTP request, with retries, against the deployed platform. It is the only way to know that the complete chain — DNS, certificate, load balancer, security group, instance, application, database — works end to end.ApplyAndIdempotent: checks that a secondapplyproduces zero changes. It detects non-deterministic values, which are the cause of the «plan that never converges» that 06-02 warned about.defer terraform.Destroy: the guaranteed cleanup, which in Terratest is your responsibility and not the framework's.
- Testing a published module before tagging
Put this lesson together with the publishing flow from 04-05 and the missing gate appears: a version is not tagged if the tests do not pass.
flowchart TD
A["PR against the module"] --> B["fmt · validate · tflint<br/>+ security analysis"]
B --> C["terraform test<br/>unit + validations + examples<br/>(mocks, < 30 s)"]
C --> D{"Does everything pass?"}
D -->|No| A
D -->|Yes| E["Human review<br/>+ classify the change:<br/>MAJOR / MINOR / PATCH"]
E --> F["Merge to main"]
F --> G["terraform test with APPLY<br/>in the test account<br/>(15-30 min)"]
G --> H["End-to-end Terratest"]
H --> I{"All green?"}
I -->|No| J["It is NOT tagged.<br/>It gets fixed first"]
I -->|Yes| K["CHANGELOG.md<br/>+ annotated tag v3.2.0"]
K --> L["Publish to the registry"]
L --> M["Consumers upgrade<br/>dev → staging → prod<br/>with days in between"]
style C fill:#e0f2fe,stroke:#0369a1
style J fill:#fee2e2,stroke:#b91c1c
style K fill:#dcfce7,stroke:#15803d
And the specific test that corresponds to each version level, which is where testing and semantic versioning meet:
| Level | What has to be demonstrated | The test that demonstrates it |
|---|---|---|
| PATCH | That nothing observable changes | The whole suite passes without touching a single test |
| MINOR | That the new thing works and the old thing is unchanged | New tests for the new thing + the old ones untouched |
| MAJOR | That the change is intentional and documented | Old tests modified, each change justified in the CHANGELOG |
The MAJOR row contains the most useful indicator in the whole lesson: if you had to modify the tests to make them pass, you have broken the contract. That is the objective criterion that turns «is this MINOR or MAJOR?» from a battle of opinions into a mechanical check.
And there is one compatibility test worth adding to any published module:
# tests/compatibility.tftest.hcl
#
# Scenario: EXACTLY the configuration ecomarket-infra invokes it
# with today. If this test fails, the change breaks a real
# consumer and CANNOT be published as a MINOR.
mock_provider "aws" {}
run "the_ecomarket_infra_invocation_still_works" {
command = plan
variables {
# Copied verbatim from infra/network/main.tf.
base_name = "ecomarket-prod"
cidr = "10.20.0.0/16"
zones = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
subnet_bits = 8
create_nat = true
tags = { Project = "ecomarket", Environment = "prod", ManagedBy = "terraform" }
}
assert {
condition = length(output.private_subnets) == 3
error_message = "Incompatible change: ecomarket-infra expects 3 private subnets."
}
assert {
condition = output.vpc_id != null && output.nat_id != null
error_message = "Incompatible change: outputs that ecomarket-infra consumes are missing."
}
}
- Ephemeral environments, test data and cleanup
Integration tests need somewhere to deploy, and that somewhere has rules.
Where you deploy
| Option | Isolation | Cost | Recommended |
|---|---|---|---|
| A separate test account | Total | Only what the tests use | Yes, always |
| An ephemeral workspace in the dev account | By state, not by permissions | Low | Acceptable if there is nothing else |
The shared dev account |
None | Low | No: the tests trample on people's work |
The prod account |
— | — | Never |
A separate account is not a luxury: it is what lets you delete everything in it every night without thinking twice, which is the only cleanup policy that works in the long run.
The isolation mechanism within that account is the per-pull-request workspace from 06-01, now applied to tests:
#!/usr/bin/env bash
# ci/test-integration.sh — integration tests isolated per PR.
set -euo pipefail
PR="${1:?Usage: ci/test-integration.sh <pr-number>}"
export TF_VAR_base_name="ecomarket-pr${PR}"
export TF_VAR_ttl_hours=4 # the sweeper will destroy it
# trap: the cleanup runs whatever happens, even if the script
# dies. It is the bash equivalent of Terratest's `defer`.
cleanup() {
echo "Cleaning up the test environment for PR ${PR}..."
terraform -chdir=modules/network workspace select "pr-${PR}" 2>/dev/null || return 0
terraform -chdir=modules/network destroy -auto-approve || \
echo "WARNING: the destroy has failed. The sweeper will pick it up within 4 h."
terraform -chdir=modules/network workspace select default
terraform -chdir=modules/network workspace delete "pr-${PR}"
}
trap cleanup EXIT
terraform -chdir=modules/network workspace select -or-create "pr-${PR}"
terraform -chdir=modules/network test -filter=tests/integration.tftest.hclTest data: three rules
1. Never copy production data. Not «a sample», not «anonymised by eye». A production dump in a test environment turns that environment, with its lax permissions and its nightly wipe, into a system that processes personal data. Under the GDPR that has real consequences, and the security and data-protection teams must decide it, not the platform team.
2. Generate the test data with the code itself. Deterministic seeds, small volumes, obviously fake values ([email protected]). Being obviously fake stops anybody confusing a test environment with a real one.
3. Test secrets are secrets too. A password in a versioned .tftest.hcl is a versioned password, even if it is for an ephemeral environment. The right thing is to generate it:
# BAD: a real password in a versioned test file.
variables {
db_password = "Ecom2026!Prod" # ← this ends up in production one day
}
# GOOD: generated, and obviously a test value.
variables {
db_password = "test-only-never-use-in-production-2026"
}
# Or better still: TF_VAR_db_password from the CI secrets manager.When the cleanup fails
It happens: a destroy that fails because a bucket is not empty, a security group with a dangling network interface, an instance with deletion protection. The three defences, in order:
trap/defer: the cleanup runs even if the test fails.- The scheduled sweeper: a job that every night destroys anything tagged
Ephemeral = truewith an expiry date in the past (06-01). - A budget alert on the test account: if spending goes above a threshold, somebody gets a warning. It is the net that catches whatever the previous two let through.
- Realistic coverage: what remains untested
Being honest about the limits is part of knowing how to use the tool.
| What tests do NOT cover | Why | What does cover it |
|---|---|---|
| That the design is correct | A test verifies what you wrote, not whether it was a good idea | Human review (07-02) |
| That the configuration is secure | A test passes with a public bucket if nobody wrote otherwise | Static analysis and policies (07-04) |
| That the cost is acceptable | Nothing in the plan says «this is €4,000/month» | Cost estimation in the PR + a FinOps review |
| Real provider behaviours | Quotas, limits, latencies, API errors | Integration with a real apply and, even then, only partly |
| Infrastructure drift | Tests look at the code, not at the cloud | The nightly drift plan and the check blocks |
| That what is deployed still works tomorrow | It is a snapshot, not surveillance | The check blocks from 06-05 and monitoring |
| Failures that only occur at scale | 3 subnets test the same as 3; at 300 the limits appear | Nothing, other than deploying at scale |
| Interactions with what already existed | Your test starts from zero; production has eight years of history | Promotion through environments with waiting windows |
And the most dangerous trap: the false sense of security. A suite of forty tests that only check tautologies (section 2) gives the impression of being protected and protects nothing. It is worse than having no tests, because it displaces attention. A single expect_failures test on the account guard is worth more than thirty assertions that instance_type equals what was assigned to it two lines above.
And the corollary that links to the next lesson: tests do not replace policies. A test checks what somebody remembered to write in the test file; if the author of the malicious or careless code also writes the tests, there is nothing forcing them to cover the dangerous case. A policy over the plan, run by the pipeline and maintained by another team, does not depend on that. It is the «controls versus good intentions» distinction that opens 07-04.
Common Errors and Tips
Testing the provider instead of your code. assert { condition = aws_s3_bucket.x.id != "" } with command = apply costs minutes and detects nothing the apply did not detect. Tip: apply the tautology rule. If the expected value is three lines above in the resource's code, do not test it, unless you mind somebody changing it.
Using command = apply by default without realising. apply is the default value of command. A test file with no explicit command deploys real infrastructure, and discovering that from the invoice makes for a bad day. Tip: write command = plan explicitly in every unit run, even when it feels redundant.
Mixing assert and expect_failures in the same run. If the run fails as expected, the assertions are never evaluated: the test appears to check things it does not. Tip: one run for what must work, another for what must fail.
Several invalid inputs in the same run with expect_failures. Terraform aborts at the first and the second validation goes untested. One run per validation.
Believing that mock_provider tests the integration. Mocks never return AccessDenied, nor LimitExceeded, nor «that bucket name already exists». Tip: mocks for the PR, a real apply at night. Both, not one.
Forgetting defer terraform.Destroy in Terratest. In terraform test the cleanup is automatic; in Terratest it is your responsibility. Without defer, a test that panics leaves infrastructure billing. Tip: write the defer immediately after creating the Options, before the Apply.
Real passwords in .tftest.hcl files. They are versioned like any other file. Tip: obviously fake values, or TF_VAR_ from the CI secrets manager.
Integration tests in the dev account. The tests create and destroy; people are working in that account. Sooner or later a test destroys something somebody was using or collides with a name already taken. Tip: a separate account, with a budget and a sweeper.
Adding tests at the end, once the module is already published. Writing them then forces you to invent the scenarios from scratch, and they usually get written so they pass with the current code rather than so they catch faults. Tip: the expect_failures test is written in the same PR as the validation it protects. It is the equivalent of writing the condition and its test at the same time.
Not running the tests before tagging. It is the one moment when they really matter, because what gets published is consumed by others. Tip: make the publishing job require them, and make sure there is no way to tag without passing them.
Exercises
Exercise 1: classifying and fixing a test suite
A colleague has written these tests for the data module. They all pass.
# modules/data/tests/tests.tftest.hcl
variables {
base_name = "test"
suffix = "abc"
db_class = "db.t3.micro"
db_password = "Ecom2026!Prod"
vpc_id = "vpc-123"
subnets = { "eu-west-1a" = "subnet-a", "eu-west-1b" = "subnet-b" }
}
run "the_database_exists" {
assert {
condition = aws_db_instance.this.id != ""
error_message = "It has not been created."
}
}
run "the_class_is_correct" {
command = plan
assert {
condition = aws_db_instance.this.instance_class == "db.t3.micro"
error_message = "Wrong class."
}
}
run "the_bucket_exists" {
command = plan
assert {
condition = aws_s3_bucket.images.bucket != null
error_message = "There is no bucket."
}
}You are asked to:
- Identify five distinct problems, including one about cost and one about security.
- Explain why the fact that «they all pass» means nothing here.
- Rewrite the suite so that it tests things that can really fail. At a minimum: a name computation, a per-environment difference and an
expect_failures. - State which
mock_provideris needed and why it improves the run time.
Exercise 2: testing the network module's conditions
The network module has these four protections, written in 06-05:
| # | Protection | Where |
|---|---|---|
| 1 | zones must have at least 2 elements |
validation on var.zones |
| 2 | cidr + subnet_bits must not produce a prefix longer than /28 |
validation on var.cidr |
| 3 | create_nat = true requires public subnets |
precondition on aws_nat_gateway.main |
| 4 | The output guarantees ≥ 2 private subnets in ≥ 2 zones | precondition on output.private_subnets |
You are asked to:
- Write the complete
tests/validations.tftest.hcl, with onerunper protection. - For each
run, state the exactexpect_failuresaddress and why it is that one. - Add a control
runthat demonstrates that a valid configuration does plan. - Explain exactly what happens — and what message would be seen — if somebody relaxes validation 1 from
>= 2to>= 1.
Exercise 3: designing the test strategy for the ecomarket-platform module
The ecomarket-platform composition module (04-05) invokes network, data and app, exposes two variables (base_name and profile) and an internal profile table:
locals {
profiles = {
minimal = {
multi_az = false, retention_days = 0, create_nat = false
db_class = "db.t3.micro", instances = { min = 1, max = 2 }
}
standard = {
multi_az = false, retention_days = 7, create_nat = true
db_class = "db.t3.small", instances = { min = 2, max = 4 }
}
high-availability = {
multi_az = true, retention_days = 30, create_nat = true
db_class = "db.t3.medium", instances = { min = 3, max = 12 }
}
}
}You are asked to:
- Design the complete pyramid: what runs on the PR, what at night and what before tagging, with estimated times and costs.
- Write the unit tests for the profile table (at least three
runblocks, one per profile) and explain why this is not a tautology. - Write a
runthat checks that a non-existent profile fails, and explain what has to be added to the module for that test to be possible. - Write the skeleton of the nightly integration test and state which three things it checks that the unit tests cannot.
Solutions
Solution 1
1. The five problems.
| # | Problem | Category | Detail |
|---|---|---|---|
| 1 | The first run has no command |
COST | apply is the default value: that run creates a real RDS instance. And since the run blocks share state, it drags the following ones along. A suite that looked like seconds takes eight minutes and bills |
| 2 | db_password = "Ecom2026!Prod" |
SECURITY | A real-looking password, versioned in Git. And the name suggests it is the production one: if it is, this is an incident under section 4 of 07-02 |
| 3 | the_class_is_correct is a tautology |
Uselessness | instance_class = var.db_class, and the variable is db.t3.micro. The test checks that an assignment assigns |
| 4 | the_bucket_exists checks nothing |
Uselessness | != null on an attribute that always has a value. It would pass with any name, including an invalid one |
| 5 | There is no mock_provider |
Cost and accessibility | Without mocks, the tests need AWS credentials. Nobody without an account can run them, so in practice only the pipeline does |
A sixth, minor but revealing: the error_message texts («It has not been created.», «Wrong class.») do not say what value was obtained or what was expected, breaking the message rules from 06-05.
2. Why «they all pass» means nothing.
A test only adds value if it can fail for a reason you care about. These three cannot:
the_database_exists: if the DB is not created, theapplyhas already failed and therunnever gets to evaluate the assertion. The test is unreachable.the_class_is_correct: it would only fail if Terraform stopped assigning values to arguments, which is a product fault, not a fault in EcoMarket's code.the_bucket_exists: it would pass even if the name had 200 characters, upper case and underscores — that is, even if theapplywere certain to fail.
All three pass today, they will pass tomorrow and they will pass on the day somebody breaks the module. Their detection value is zero and their cost is minutes and pounds per run. It is section 16's false sense of security in its purest form.
3. The rewritten suite.
# modules/data/tests/unit.tftest.hcl
variables {
base_name = "ecomarket-dev"
suffix = "swift-cat"
vpc_id = "vpc-0123456789abcdef0"
subnets = { "eu-west-1a" = "subnet-aaa", "eu-west-1b" = "subnet-bbb" }
db_class = "db.t3.micro"
# Obviously a test value. Ideally: TF_VAR_db_password from CI.
db_password = "test-only-never-use-in-production-2026"
}
mock_provider "aws" {}
mock_provider "random" {}
# --- 1. Name computation: this can really fail. ---
run "the_bucket_name_complies_with_the_s3_rules" {
command = plan
variables {
# A long base name, which is when the computation breaks.
base_name = "ecomarket-wholesale-preproduction-europe"
}
assert {
condition = length(aws_s3_bucket.images.bucket) <= 63
error_message = format(
"The bucket name is %d characters long (S3 allows 63 at most): '%s'. Check the composition of base_name + suffix.",
length(aws_s3_bucket.images.bucket), aws_s3_bucket.images.bucket,
)
}
assert {
condition = can(regex("^[a-z0-9][a-z0-9.-]*[a-z0-9]$", aws_s3_bucket.images.bucket))
error_message = format("Invalid bucket name for S3: '%s'.", aws_s3_bucket.images.bucket)
}
}
# --- 2. Per-environment difference: the logic that really can break. ---
run "the_production_profile_enables_the_protections" {
command = plan
variables {
base_name = "ecomarket-prod"
db_class = "db.t3.medium"
high_availability = true
retention_days = 30
protect_deletion = true
}
assert {
condition = aws_db_instance.this.multi_az
error_message = "Production must be deployed across several availability zones."
}
assert {
condition = aws_db_instance.this.backup_retention_period >= 7
error_message = format(
"Production requires at least 7 days of retention; %d have been configured.",
aws_db_instance.this.backup_retention_period,
)
}
# This is not a tautology: it is a REGRESSION control over a
# security decision. It blocks the PR from exercise 2 of 07-02.
assert {
condition = aws_db_instance.this.storage_encrypted
error_message = "Encryption at rest is mandatory in EVERY environment."
}
assert {
condition = aws_db_instance.this.deletion_protection
error_message = "Production must have deletion protection enabled."
}
}
# --- 3. The output contract: what breaks the consumers. ---
run "the_outputs_keep_their_shape" {
command = plan
assert {
condition = can(output.db_endpoint) && output.db_endpoint != null
error_message = "The db_endpoint output has disappeared or is null."
}
assert {
condition = alltrue([
for key in ["Project", "Environment", "ManagedBy"] :
contains(keys(aws_db_instance.this.tags), key)
])
error_message = format(
"Mandatory tags are missing. Present: %s",
join(", ", keys(aws_db_instance.this.tags)),
)
}
}# modules/data/tests/validations.tftest.hcl
# --- 4. expect_failures: that the protections work. ---
mock_provider "aws" {}
mock_provider "random" {}
variables {
base_name = "ecomarket-dev"
suffix = "swift-cat"
vpc_id = "vpc-0123456789abcdef0"
subnets = { "eu-west-1a" = "subnet-aaa", "eu-west-1b" = "subnet-bbb" }
db_class = "db.t3.micro"
db_password = "test-only-never-use-in-production-2026"
}
run "a_short_password_must_be_rejected" {
command = plan
variables { db_password = "short" }
expect_failures = [var.db_password]
}
run "a_single_subnet_must_be_rejected" {
command = plan
# RDS requires a subnet group spanning at least 2 zones. Without the
# validation, the failure arrives from the API two minutes into the apply.
variables { subnets = { "eu-west-1a" = "subnet-aaa" } }
expect_failures = [var.subnets]
}
run "production_without_retention_must_be_blocked" {
command = plan
variables {
base_name = "ecomarket-prod"
environment = "prod"
retention_days = 0
}
expect_failures = [aws_db_instance.this]
}4. The mock_provider and its effect.
Three concrete effects:
- No credentials. Anybody on the team runs
terraform teston their laptop, including somebody contributing from outside. Tests that only the pipeline can run get written once and never looked at again. - From minutes to seconds. Without mocks, every
runwithplanmakes read calls to the AWS API to resolvedatasources and validate. With mocks, zero calls: the whole suite drops to around five seconds. - Zero cost and zero risk. Nothing gets created, nothing can be left orphaned and no account other than the test one can be touched by accident.
And random is needed because the module uses random_pet.suffix: without mocking it, the id attribute would be unknown in the plan and the assertion about the bucket name's length could not be evaluated.
Solution 2
1 and 2. The complete file, with the justification for each address.
# modules/network/tests/validations.tftest.hcl
#
# These tests check that the module REJECTS what it must reject.
# Each `run` invalidates ONE single thing: if it invalidated two,
# Terraform would abort at the first and the second would go untested.
mock_provider "aws" {}
# A VALID base configuration. Each run breaks one thing and one only.
variables {
base_name = "ecomarket-tests"
cidr = "10.20.0.0/16"
zones = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
subnet_bits = 8
create_nat = false
create_public = true
tags = { Project = "ecomarket", Environment = "test", ManagedBy = "terraform" }
}
# --- Protection 1: at least two zones ---
run "a_single_zone_must_fail" {
command = plan
variables {
zones = ["eu-west-1a"]
}
# Address: var.zones.
# Reason: the protection is a `validation` block INSIDE that
# variable's declaration. Variable validations are always
# addressed as var.<name>, not by the resource that
# consumes them.
expect_failures = [var.zones]
}
# --- Protection 2: the CIDR must allow the requested carve-up ---
run "a_cidr_that_is_too_small_must_fail" {
command = plan
variables {
# /26 + 8 bits = /34, which does not exist in IPv4 (maximum /32).
# And AWS does not even accept subnets smaller than /28.
cidr = "10.20.0.0/26"
}
# Address: var.cidr. Same reason as the previous one.
# NOTE: the validation must be on var.cidr and not on var.subnet_bits,
# because a validation can only refer to ITS own variable.
# If the check needed both at once, it would have to be
# a precondition on a resource or on a terraform_data.
expect_failures = [var.cidr]
}
# --- Protection 3: NAT with no public subnets ---
run "nat_without_public_subnets_must_fail" {
command = plan
variables {
create_nat = true
create_public = false
}
# Address: the RESOURCE, not the variable.
# Reason: this check crosses two variables, so it cannot
# live in a `validation`. It is written as a `precondition` inside
# the `lifecycle` block of aws_nat_gateway.main, and
# preconditions are addressed by the resource that contains them.
expect_failures = [aws_nat_gateway.main]
}
# --- Protection 4: the output contract ---
run "the_output_contract_must_block_a_single_zone" {
command = plan
variables {
zones = ["eu-west-1a"]
# Necessary: without this back door, validation 1 aborts
# BEFORE reaching the output and the test would check the
# wrong protection. See the note in section 3.
skip_zones_validation = true
}
# Address: output.<name>.
# Reason: the protection is a `precondition` inside the
# `output` block. It is the module's contract: it guarantees consumers
# that they will always receive at least 2 subnets in 2 different zones.
expect_failures = [output.private_subnets]
}A note on the fourth run. It is the most instructive one because it shows a real problem: two protections over the same input, and the first stops you reaching the second. There are three ways out:
| Option | Assessment |
|---|---|
A «back door» variable (skip_zones_validation) |
It works, but it adds a variable to the module that exists only for the tests. It has to be documented as internal and you have to accept that a consumer might use it |
| Test the output with a different input that breaches it without tripping validation 1 | The cleanest option if such a path exists. For example: 2 zones that resolve to the same physical zone |
| Accept that protection 4 is covered by protection 1 and not test it | Honest and sometimes correct. The output precondition is a safety net against internal refactors, not against user input |
In EcoMarket the third option is chosen for the network module and documented in the test file with a comment. A missing but justified test is preferable to a production variable that exists only for the tests.
3. The control run.
# --- Control: a valid configuration MUST plan. ---
# Without this run, a suite that only checks failures would pass in full
# even if the module were broken and never planned at all.
run "a_valid_configuration_plans_without_errors" {
command = plan
assert {
condition = length(aws_subnet.private) == 3
error_message = format(
"With 3 zones there must be 3 private subnets planned, there are %d.",
length(aws_subnet.private),
)
}
assert {
condition = length(distinct([
for s in aws_subnet.private : s.availability_zone
])) == 3
error_message = "The private subnets must be in 3 different zones."
}
assert {
condition = can(output.private_subnets)
error_message = "The private_subnets output could not be evaluated."
}
}This run is essential and it is often forgotten. A file with four expect_failures blocks and no control would pass in full if somebody broke the module in a way that makes everything fail: the four expected failures would occur, for the wrong reason.
4. What happens if somebody relaxes the validation from >= 2 to >= 1.
The corresponding run fails, and that is exactly the desired behaviour. The sequence:
- Somebody changes
condition = length(var.zones) >= 2to>= 1, perhaps because a local test was annoying them or because «one zone is enough in dev». - They run
terraform test(or the pipeline runs it on their PR). - The
a_single_zone_must_failrunpasseszones = ["eu-west-1a"]. With the relaxed validation, it no longer fails. - Terraform reports:
tests/validations.tftest.hcl... in progress
run "a_single_zone_must_fail"... fail
Error: Expected failure for var.zones, but no failure occurred.
on tests/validations.tftest.hcl line 22, in run "a_single_zone_must_fail":
22: expect_failures = [var.zones]
tests/validations.tftest.hcl... fail
Failure! 4 passed, 1 failed.The pipeline marks the check red and the PR cannot be merged (07-02 §11).
And this is the debt from 06-05 paid off literally. The conversation the change prompts is no longer «I forgot» but an explicit one: «you have relaxed a guarantee of the module; if one zone really is needed in dev, that has to be decided, documented in the CHANGELOG, published as a MAJOR — it changes the contract — and this test updated with its reason». Without the test, the change would have been merged silently and the loss of high availability would have been discovered on the day a zone went down.
Solution 3
1. The pyramid for ecomarket-platform.
| Moment | What runs | Duration | Cost | Blocks |
|---|---|---|---|---|
| Local hook | fmt, validate, tflint, gitleaks |
< 10 s | €0 | The commit |
| PR | The above + terraform test with plan + mock_provider: profiles, names, output contract, expect_failures |
< 45 s | €0 | The merge |
| PR | Security analysis (checkov/trivy) + policies over the plan (07-04) |
< 60 s | €0 | The merge |
| PR | A real plan against dev, posted as a comment |
1–2 min | €0 | No: it informs the reviewer |
| Nightly 02:00 | terraform test with apply of the complete example in the test account |
25–35 min | ~€2 | It alerts the channel |
| Nightly | Terratest: HTTP against /health + idempotence |
15 min | ~€1 | Alerts |
| Nightly | destroy + verification that nothing is left + spend report |
10 min | — | Alerts |
| Before tagging | The complete suite: unit + validations + examples + integration + compatibility with ecomarket-infra's real invocation |
40–50 min | ~€3 | The publication |
The reasoning behind the split: a composition module that deploys the whole platform takes almost half an hour for a real apply. Putting that in the PR would mean nobody ever opened a PR. The profile table, on the other hand — which is where mistakes really can happen — is tested in seconds with mocks.
2. The unit tests for the profile table.
# tests/profiles.tftest.hcl
variables {
base_name = "ecomarket-tests"
domain = "test.ecomarket.example.com"
contact = "[email protected]"
}
mock_provider "aws" {}
mock_provider "random" {}
run "the_minimal_profile_is_cheap_and_has_no_high_availability" {
command = plan
variables { profile = "minimal" }
assert {
condition = module.data.multi_az == false
error_message = "The 'minimal' profile must not enable Multi-AZ: it would double the cost."
}
assert {
condition = module.network.create_nat == false
error_message = "The 'minimal' profile must not create NAT: that is ~$33/month per zone."
}
assert {
condition = module.app.min_instances == 1
error_message = "The 'minimal' profile must start with 1 instance."
}
}
run "the_standard_profile_has_backups_but_not_multi_az" {
command = plan
variables { profile = "standard" }
assert {
condition = module.data.retention_days == 7
error_message = format(
"The 'standard' profile must retain backups for 7 days, it has %d.",
module.data.retention_days,
)
}
assert {
condition = module.data.multi_az == false
error_message = "'standard' does not include Multi-AZ: that is what 'high-availability' is for."
}
}
run "the_high_availability_profile_meets_the_production_requirements" {
command = plan
variables { profile = "high-availability" }
assert {
condition = module.data.multi_az == true
error_message = "'high-availability' MUST deploy the DB across several zones."
}
assert {
condition = module.data.retention_days >= 30
error_message = "'high-availability' must retain backups for at least 30 days."
}
assert {
condition = module.app.min_instances >= 3
error_message = "'high-availability' must start with at least 3 instances, one per zone."
}
assert {
condition = module.network.create_nat == true
error_message = "'high-availability' needs NAT for the private subnets' egress."
}
}
# A cross-cutting test: no configuration may lose encryption.
run "no_profile_disables_encryption" {
command = plan
variables { profile = "minimal" } # the laxest: if it passes here, it passes everywhere
assert {
condition = module.data.storage_encrypted == true
error_message = "NO profile may disable encryption at rest."
}
}Why this is not a tautology. The distinction is a fine one and deserves explaining. In exercise 1, instance_class == "db.t3.micro" was tautological because the value came straight from a variable the test itself set: there was no transformation in between.
Here there are three layers of logic between the input and the result, and each of them can break:
- The
lookupinlocal.profiles[var.profile], which can fail if somebody renames a key. - The translation of each profile field into the child module's argument, which can get misaligned in a refactor (the classic: moving
retention_daysfrom one module to another and forgetting a wire). - The profile table itself, which somebody may edit thinking they are touching
devwhenhigh-availabilityis what production uses.
The input is profile = "high-availability" and what gets checked is module.data.multi_az == true. Between those two things there is a table, a lookup and three module invocations. That is the composition module's logic, and it is literally everything the module contributes. If you do not test that, you are testing nothing.
On top of that, the last assertion for the minimal profile about create_nat == false has direct business value: a fault there turns the cheap profile into one that costs $33/month per zone without anybody noticing until the invoice.
3. A non-existent profile and what has to be added to the module.
run "a_non_existent_profile_must_fail_with_a_useful_message" {
command = plan
variables { profile = "super-mega-high-availability" }
expect_failures = [var.profile]
}For that test to work, the module needs a validation. Without it, local.profiles[var.profile] fails anyway, but with an internal Terraform error that does not say which profiles exist:
What has to be added:
# variables.tf of the composition module
variable "profile" {
description = <<-EOT
The platform's sizing profile. It determines Multi-AZ,
backup retention, NAT, database class and the number of
instances. See the full table in the README.
EOT
type = string
validation {
condition = contains(["minimal", "standard", "high-availability"], var.profile)
error_message = "The profile must be one of: minimal, standard, high-availability. Check the table in the README to see what each one includes."
}
}And here is the detail that makes the test valuable: the validation and its test are written in the same PR. It is the recommendation from the common-errors section, and it avoids the usual case of writing the validation, forgetting to test it, and discovering two years later that it had a typo.
There is a second case worth testing that is more subtle:
run "the_declared_profiles_and_the_validated_ones_match" {
command = plan
variables { profile = "standard" }
assert {
# Protects against the classic mismatch: somebody adds a profile to
# local.profiles and forgets to add it to the validation's list.
# The profile would exist but be unreachable, and nobody would know.
condition = length(setsubtract(
keys(local.profiles),
["minimal", "standard", "high-availability"],
)) == 0
error_message = format(
"There are profiles in local.profiles that var.profile's validation does not accept: %s",
join(", ", setsubtract(keys(local.profiles), ["minimal", "standard", "high-availability"])),
)
}
}4. The nightly integration test.
# tests/integration.tftest.hcl
#
# A REAL APPLY. ~30 min, ~€2. Test account (999999999999).
# It runs in the nightly job and before tagging a version.
variables {
base_name = "ecomarket-nightly"
profile = "standard"
domain = "nightly.test.ecomarket.example.com"
contact = "[email protected]"
}
run "the_complete_platform_deploys" {
command = apply
module {
source = "./examples/complete"
}
assert {
condition = module.platform.endpoints["web"] != ""
error_message = "The load balancer has not returned a DNS name."
}
assert {
# Only checkable after a real apply: the endpoint is assigned by AWS.
condition = can(regex("\\.rds\\.amazonaws\\.com$", module.platform.endpoints["db"]))
error_message = format(
"Unexpected database endpoint: %s",
module.platform.endpoints["db"],
)
}
assert {
# The 06-05 health check has been recorded in the state.
condition = module.platform.health_ok == true
error_message = "The platform health check did not pass after the deployment."
}
}
run "a_second_apply_changes_nothing" {
command = apply
module {
source = "./examples/complete"
}
assert {
condition = module.platform.endpoints["web"] == run.the_complete_platform_deploys.endpoints["web"]
error_message = "The endpoint has changed between two consecutive applies: there is a non-deterministic value."
}
}The three things it checks that the unit tests cannot:
- That the arguments are valid for the real provider. A mock accepts any value; AWS does not. An
instance_classthat does not exist ineu-west-1, a retired PostgreSQL engine, an incompatible combination of options: these only show up here. - That the composition works end to end. That the subnet
networkproduces is acceptable todata's subnet group; thatapp's security group really can reach port 5432; that the certificate validates. These are interactions between modules that no mock reproduces. - That the deployment is idempotent and converges. The second
rundetects the hardest failure of all to catch: a non-deterministic value (atimestamp(), adatasource withmost_recent, a tag the provider normalises) that stops the plan ever coming out at zero. With mocks it is invisible, because the mocked values are stable.
And there is a fourth, implicit one: that the destroy works. The automatic cleanup at the end of the file is a test in itself. A module whose destroy fails — because of a bucket with objects, a circular dependency, a protected resource — is a module nobody will be able to retire cleanly, and that failure only shows up here.
Conclusion
Testing infrastructure has rules of its own, and the main one is that almost everything worth testing can be tested without deploying anything.
- The pyramid has six steps, from
fmtin milliseconds to Terratest in minutes and pounds, plus a separate layer — thecheckblocks — that does not exist in software: the continuous verification that what is deployed still works. - Test your logic, not the provider's. Names, CIDRs, per-environment conditionals, profile tables, output contracts. The tautology rule discards most useless tests: if the expected value is three lines above, do not test it.
- With one exception: testing the obvious is worth it when what you want is to stop somebody changing it.
storage_encrypted == trueis a regression control over a security decision. validateneeds no credentials with-backend=false, andtflintcatches whatvalidatecannot see: non-existent instance types, modules with no pinned version, dead declarations. A linter sees the code; a policy sees the resolved plan: that is why you need both.terraform testis written in HCL, lives intests/*.tftest.hcl, and itsrunblocks execute in order sharing state within each file.command = applyis the default. Writecommand = planexplicitly, or your test suite will deploy real infrastructure without being asked.expect_failuresis the 06-05 debt paid off: it checks that the module rejects what it must reject. The test fails if the failure does not occur, so relaxing a validation breaks the pipeline instead of slipping through unnoticed. Onerunper protection, not mixed withassert, and with a controlrunthat demonstrates that a valid configuration does plan.mock_provideris what makes all of this viable: no credentials, no cost, in seconds, and runnable on any laptop. Withmock_datayou can even test the account guards without touching the cloud.- Mocks do not test the integration: they never return
AccessDenied, nor exhausted quotas, nor taken names. Mocks in the PR, a realapplyat night, in a separate account with a budget and a sweeper. - The
examples/from module 4 are test scenarios that are already written, andmoduleinsiderunexecutes them. If somebody changes the interface and forgets the example, the test fails: the examples lose the ability to lie. - Terratest answers a different question: not «is the configuration correct?» but «does the deployed system work?». Real HTTP requests, retries, idempotence. And the cleanup is yours: without
defer Destroy, a failure leaves infrastructure billing. - A version is not tagged if the tests do not pass. And the best indicator of version level is mechanical: if you had to modify the tests to make them pass, you have broken the contract and it is a MAJOR.
- Tests do not cover the design, nor security, nor cost, nor drift. And a suite of tautologies is worse than none, because it displaces attention.
That last point is the bridge. Tests check what somebody remembered to write in the test file. If the same PR that opens port 5432 to the internet also writes the tests, there is nothing forcing it to cover that case. A test is a voluntary statement by the author; it can be missing, it can be aimed the wrong way and it can be deleted in the same commit that introduces the problem.
The next lesson, Security Best Practices, pays off the biggest debt in the course and deals with exactly that difference: the policies that really are controls rather than good intentions. You will see the threat model of an IaC repository — who can do what damage — the identity Terraform runs as and why plan and apply must have different permissions, the four rules of secrets and why you have to assume the state contains them, static analysis with tfsec, checkov and trivy applied to EcoMarket's real code, and above all the policies written in Rego that run over terraform show -json in the pipeline, where they cannot be skipped by deleting a block from the code. Plus the supply chain: third-party modules and providers, the lock file as a defence, and why somebody else's data "external" deserves to be read line by line before you hand it your credentials.
