Throughout module 5, EcoMarket kept accumulating hand-written checks. In 05-01 a guard appeared that verified the active credentials belonged to the account expected for the environment, and we introduced it with a "preconditions are covered formally in 06-05". In 05-03 and 05-04 the same thing happened for the subscription and the project. In 05-05 we finished with a data "http" on /health and an assert confirming that the platform responded after the deployment. And in this very module they have kept appearing: the workspace guard in 06-01, the 16 KB user_data check in the exercises of 06-02, the open-port validations in 06-03.
They are all the same family of instruments and we have used them without ordering them. This lesson orders them.
What you are going to see is not just syntax. It is a criterion: what should break the plan and what should merely warn. A module that fails loudly when an assumption is broken saves hours of debugging for whoever uses it; a module that blocks the apply because an external service took two seconds too long to respond is a module nobody wants. The difference between those two behaviours is one line of code and a conscious decision.
- Terraform's spectrum of validations
Terraform offers five different instruments for checking things, and each has its own territory.
| Instrument | Where it is written | What it checks | Does it block? | Seen in |
|---|---|---|---|---|
validation |
Inside variable |
The input value before it is used | Yes, a hard error | 02-02 |
precondition |
The lifecycle of a resource or data |
The assumptions that must hold before creating or reading | Yes, a hard error | This lesson |
postcondition |
The lifecycle of a resource or data |
The guarantees that must hold afterwards | Yes, a hard error | This lesson |
precondition in output |
Inside output |
A module's output contract | Yes, a hard error | This lesson |
check |
A top-level block | Health verifications, non-blocking | No, it only warns | This lesson |
terraform test |
.tftest.hcl files |
The module's behaviour for specific inputs | Yes, in the pipeline | 07-03 |
The most useful way to understand them is as a chain with the infrastructure in the middle:
flowchart LR
V["validation<br/><i>is the input<br/>value valid?</i>"] --> P["precondition<br/><i>do my assumptions<br/>hold?</i>"]
P --> R["RESOURCE<br/>create / update"]
R --> Q["postcondition<br/><i>is the result<br/>what I promised?</i>"]
Q --> O["precondition in output<br/><i>is the module's<br/>contract met?</i>"]
O --> C["check<br/><i>is the platform<br/>still healthy?</i>"]
And the question each one answers, in a sentence:
validation: "have I been given a sensible value?"precondition: "is the world the way I need it in order to do this?"postcondition: "did what I just did end up the way it should have?"preconditioninoutput: "does what I return meet what I promised whoever uses my module?"check: "does this actually work, right now?"
- When each one runs
This is the section you have to reread most often, because the behaviour is not uniform and the consequences are significant.
flowchart TD
subgraph plan["terraform plan"]
A1["1. Load configuration<br/>and state"] --> A2["2. Variable validation<br/>❌ immediate error"]
A2 --> A3["3. Refresh: read the real state"]
A3 --> A4["4. Resolve data sources<br/>+ their pre/postconditions<br/>❌ error if they fail"]
A4 --> A5["5. Compute the changes"]
A5 --> A6["6. Resource preconditions,<br/>if the values are known<br/>❌ error if they fail"]
A6 --> A7["7. check blocks<br/>⚠️ WARNING if they fail"]
end
plan --> apply
subgraph apply["terraform apply"]
B1["8. Deferred preconditions<br/>❌ error"] --> B2["9. Create/modify the resource"]
B2 --> B3["10. postcondition<br/>❌ error, resource ALREADY created"]
B3 --> B4["11. check blocks<br/>⚠️ WARNING"]
end
The four practical consequences that follow from the diagram:
| Fact | Consequence |
|---|---|
Conditions over known values are evaluated during the plan |
A broken assumption is caught before anything is touched |
Conditions over unknown values are deferred to the apply |
The failure arrives mid-deployment, with resources already created |
| Postconditions are evaluated after creating | If one fails, the resource already exists. Terraform flags the error but undoes nothing |
check blocks are evaluated in both and never block |
They appear as warnings, not as errors |
The third is the surprising one. A failing postcondition does not roll the resource back: it leaves it created and marks the apply as failed. The state keeps the resource inside it. That is why a postcondition is a guarantee that gets verified, not a transaction that gets undone.
precondition: the assumptions before creating
precondition: the assumptions before creatingIt is written inside lifecycle, and it accepts as many blocks as you like:
resource "..." "..." {
# ...
lifecycle {
precondition {
condition = <boolean expression>
error_message = "<what happened and what to do>"
}
}
}Case 1: the AMI must be of the right architecture
A classic and expensive failure: launching a t4g (ARM) instance with an image compiled for x86_64. The instance boots, cloud-init fails, the auto scaling group kills it, launches another, and the loop continues until somebody looks at the logs twenty minutes later.
data "aws_ami" "ecomarket" {
most_recent = true
owners = ["self"]
filter {
name = "name"
values = ["ecomarket-web-*"]
}
}
resource "aws_launch_template" "web" {
name_prefix = "${local.prefix}-web-"
image_id = data.aws_ami.ecomarket.id
instance_type = local.current.web_class
lifecycle {
create_before_destroy = true
precondition {
# Families with a "g" in the name (t4g, m6g, c7g) are Graviton/ARM.
# The rest are x86_64. The image has to match.
condition = (
startswith(local.current.web_class, "t4g") ||
startswith(local.current.web_class, "m6g") ||
startswith(local.current.web_class, "c7g")
) ? data.aws_ami.ecomarket.architecture == "arm64" : data.aws_ami.ecomarket.architecture == "x86_64"
error_message = format(
"Architecture mismatch: instance class '%s' is not compatible with image '%s', whose architecture is %s. Build the image for the right architecture with Packer, or change the instance class in %s.tfvars.",
local.current.web_class,
data.aws_ami.ecomarket.name,
data.aws_ami.ecomarket.architecture,
var.environment,
)
}
}
}The error, when it fires:
╷ │ Error: Resource precondition failed │ │ on modules/app/compute.tf line 24, in resource "aws_launch_template" "web": │ 24: condition = ( │ │ Architecture mismatch: instance class 't4g.medium' is not compatible with │ image 'ecomarket-web-2.5.0', whose architecture is x86_64. Build the image │ for the right architecture with Packer, or change the instance class in │ prod.tfvars. ╵
Compare that message with what would have happened without the precondition: twenty minutes of instances dying in a loop, a glance at /var/log/cloud-init-output.log to find an Exec format error, and the deduction that the architecture did not match. The precondition turns a half-hour incident into a three-second plan error.
Case 2: the subnet must be in the expected zone
data "aws_subnet" "data" {
id = var.data_subnet_id
}
resource "aws_db_instance" "main" {
identifier = "${local.prefix}-db"
db_subnet_group_name = aws_db_subnet_group.main.name
availability_zone = var.preferred_zone
# ...
lifecycle {
precondition {
condition = data.aws_subnet.data.availability_zone == var.preferred_zone
error_message = format(
"Subnet %s is in zone %s, but the database has been requested in %s. An RDS instance must sit in a subnet in its own zone. Check var.preferred_zone or the subnet that was assigned.",
var.data_subnet_id,
data.aws_subnet.data.availability_zone,
var.preferred_zone,
)
}
}
}Without this precondition, the error arrives from the AWS API mid-apply, after three minutes of waiting, and says something like Cannot find version ... in availability zone, which does not point at the problem.
Case 3: the instance class must be on the environment's allowed list
This case has an important peculiarity: it is not the same as a validation on the variable.
variable "environments" {
type = map(object({
web_class = string
db_class = string
# ...
}))
}
locals {
# The allowed list depends on the ENVIRONMENT, not just on the value.
allowed_classes = {
dev = ["t3.micro", "t3.small", "t4g.micro", "t4g.small"]
staging = ["t3.small", "t3.medium", "m6i.large"]
prod = ["m6i.large", "m6i.xlarge", "c6i.xlarge", "c6i.2xlarge"]
}
}
resource "aws_launch_template" "web" {
# ...
lifecycle {
precondition {
condition = contains(local.allowed_classes[var.environment], local.current.web_class)
error_message = format(
"Class '%s' is not allowed in the '%s' environment. Allowed classes: %s. If you need another class, open a pull request modifying local.allowed_classes and justify the cost with FinOps ([email protected]).",
local.current.web_class,
var.environment,
join(", ", local.allowed_classes[var.environment]),
)
}
}
}Why this is a precondition and not a validation: a variable validation can only refer to that variable. Here the condition crosses two things — var.environment and local.current.web_class — and a validation does not allow that. Since Terraform 1.9, a validation can refer to other variables and to locals, which blurs the boundary, but the practical rule is still clear:
Use validation when |
Use precondition when |
|---|---|
| The check is about the value itself (format, range, enumeration) | The check crosses variables, locals or cloud data |
| The error should be seen as early as possible, before anything else | The check needs a resolved data source |
| The variable is a module's public interface | The assumption is internal to the resource |
The real boundary: if you need a data, it is a precondition. A validation cannot read the cloud.
Preconditions on data sources
They work the same way and are particularly useful for validating what has been read:
data "aws_ami" "ecomarket" {
most_recent = true
owners = ["self"]
filter {
name = "name"
values = ["ecomarket-web-${var.image_version}"]
}
lifecycle {
precondition {
condition = can(regex("^\\d+\\.\\d+\\.\\d+$", var.image_version))
error_message = format(
"Image version '%s' is not in semantic format (X.Y.Z). Do not use 'latest' or moving tags: the version must be explicit and written in the environment's .tfvars.",
var.image_version,
)
}
}
}This precondition is evaluated before the data source is resolved, so it avoids a pointless query and gives a far better message than the Your query returned no results that AWS would return.
postcondition: the guarantees after creating
postcondition: the guarantees after creatingSame syntax, different moment, and one extra capability: self.
resource "..." "..." {
# ...
lifecycle {
postcondition {
condition = self.<attribute> ...
error_message = "..."
}
}
}self refers to the resource itself once created, with its attributes resolved. In a precondition, self does not exist — the resource is not there yet — and using it gives an explicit error:
Case 1: the bucket must end up with versioning enabled
resource "aws_s3_bucket_versioning" "invoices" {
bucket = aws_s3_bucket.invoices.id
versioning_configuration {
status = "Enabled"
}
lifecycle {
postcondition {
condition = self.versioning_configuration[0].status == "Enabled"
error_message = "Versioning on the invoices bucket has ended up disabled. It is a compliance requirement: seven years of retention demand versioning. Check whether an organisation policy is blocking it."
}
}
}It looks redundant — we have just set it to Enabled — and it is not. It checks that the API accepted what it was asked for. There are real scenarios where it does not: an organisation service control policy denying the operation, a provider that swallows an error, or a race condition with another process. Without the postcondition, the apply would say "applied" and the bucket would end up without versioning.
Case 2: the load balancer must have at least two zones
resource "aws_lb" "main" {
name = "${local.prefix}-lb"
load_balancer_type = "application"
subnets = [for z, s in var.public_subnets : s.id]
security_groups = [aws_security_group.load_balancer.id]
lifecycle {
postcondition {
condition = length(self.subnets) >= 2
error_message = format(
"The load balancer ended up with %d subnet(s). An ALB needs at least two availability zones in order to tolerate losing one. Check that var.public_subnets has entries for at least two different zones.",
length(self.subnets),
)
}
postcondition {
# Two subnets in the SAME zone are not high availability.
condition = length(distinct([for az in self.availability_zones : az.zone_name])) >= 2
error_message = "The load balancer has several subnets but they are all in the same availability zone. That is not high availability: losing one zone takes the platform out of service."
}
}
}The second postcondition is a lovely example of why these checks exist: the first one passes and the system still does not tolerate failure. A requirement is not expressed well by counting resources; it is expressed by counting distinct zones.
Case 3: the AMI must be no more than 90 days old
This is a postcondition on a data source, and it is the use that adds the most value: validating what the cloud has handed back to you.
data "aws_ami" "ecomarket" {
most_recent = true
owners = ["self"]
filter {
name = "name"
values = ["ecomarket-web-*"]
}
lifecycle {
postcondition {
# creation_date arrives as "2026-06-01T10:23:45.000Z".
# timecmp returns -1 if the first is earlier than the second.
condition = timecmp(
self.creation_date,
timeadd(plantimestamp(), "-2160h"), # 90 days back
) > 0
error_message = format(
"EcoMarket's most recent image ('%s') was created on %s, more than 90 days ago. An old image accumulates unpatched vulnerabilities. Trigger a new image build with Packer before deploying, or justify the exception with the security team ([email protected]).",
self.name,
formatdate("DD/MM/YYYY", self.creation_date),
)
}
}
}Three decisions in that condition:
plantimestamp()and nottimestamp(): the instant is fixed when the plan starts, so the plan and theapplyof that plan agree (06-02).-2160his 90 days in hours, becausetimeadddoes not accept days as a unit.timecmp(...) > 0means "the creation date is later than the cut-off", that is, the image is newer than 90 days.
Mind the effect of time drift. This postcondition will break the plan on day 91, without anybody having changed anything. That is exactly the point — to force the image to be rebuilt — but you have to know it before putting it into production, because one day the main branch will stop applying. If the team is not ready for that, the right instrument is a
checkthat warns rather than a postcondition that blocks. It is the decision in section 10.
precondition or postcondition: how to choose
| Question | Answer |
|---|---|
| Is the check about something that already exists before creating? | precondition |
Do you need self? |
postcondition, necessarily |
| Do you want to catch the problem before spending time and money? | precondition |
| Do you want to guarantee the result is correct? | postcondition |
Is the check about a data source you are reading? |
The data source's postcondition |
| If it fails, would you rather nothing had been created? | precondition: a postcondition leaves the resource created |
The last row is the golden rule. When in doubt, precondition: it is cheaper and it fails earlier.
precondition in outputs: a module's contract
precondition in outputs: a module's contractIn an output, the precondition is written directly in the block, not inside a lifecycle:
output "endpoints" {
description = "The platform's entry points, for the application team."
value = {
web = "https://${aws_lb.main.dns_name}"
db = aws_db_instance.main.endpoint
bucket = aws_s3_bucket.images.bucket
}
precondition {
condition = aws_lb.main.dns_name != ""
error_message = "The load balancer returned no DNS name. The 'endpoints' output would be useless to the application team."
}
precondition {
condition = can(regex("^[a-z0-9.-]+:[0-9]+$", aws_db_instance.main.endpoint))
error_message = format(
"The database endpoint ('%s') is not in the expected host:port format. This module's consumer expects to be able to break it apart with split(\":\", ...).",
aws_db_instance.main.endpoint,
)
}
}Why outputs are a good place to validate. A module's outputs are its public contract: what it promises whoever uses it. A precondition on an output turns that promise into something verified on every apply, instead of a sentence in documentation nobody reads.
And the decisive argument: whoever consumes the module cannot validate those guarantees. If module.app.load_balancer_dns returns an empty string, the consumer will find out three resources later, with an error from another provider that never mentions your module. With the precondition on the output, the error names the module, names the output and says what was expected.
╷ │ Error: Module output value precondition failed │ │ on modules/app/outputs.tf line 14, in output "endpoints": │ 14: condition = aws_lb.main.dns_name != "" │ │ The load balancer returned no DNS name. The 'endpoints' output would be │ useless to the application team. ╵
A practical rule for published modules like EcoMarket's (terraform-aws-ecomarket-network, -data, -app): every output documented with a concrete promise should have a precondition that verifies it. If the description says "it always returns at least two subnets", that is a condition, not a sentence.
output "private_subnets" {
description = "Map of zone -> private subnet. It always contains at least two distinct zones."
value = { for z, s in aws_subnet.private : z => { id = s.id, cidr = s.cidr_block, zone = z } }
precondition {
condition = length(aws_subnet.private) >= 2
error_message = format(
"The 'network' module produced %d private subnet(s) and its contract guarantees at least 2. Check the 'zones' variable: it must hold at least two different availability zones.",
length(aws_subnet.private),
)
}
}
- The
check block: verifying without blocking
check block: verifying without blockingcheck is a top-level block; it does not live inside any resource. It was introduced in Terraform 1.5 and its defining feature is that it never blocks.
check "<name>" {
# Optional: a "scoped" data source, visible only inside the check.
data "<type>" "<name>" {
# ...
}
assert {
condition = <boolean expression>
error_message = "<what failed>"
}
# There can be several asserts.
assert {
condition = ...
error_message = ...
}
}Three characteristics that set it apart from everything above:
| Characteristic | Detail |
|---|---|
| It is top-level | It belongs to no resource; it can check cross-cutting things |
It can contain a scoped data |
That data source only exists inside the check, and if it fails to resolve, that too is a warning, not an error |
| It never blocks | A failed assert produces a warning; the apply carries on and finishes successfully |
That second characteristic is subtle and very important. An ordinary data "http" that cannot connect breaks the plan. The same data source inside a check produces a warning. That is what lets you check external services without a network problem blocking a deployment.
check versus postcondition
| Criterion | postcondition |
check |
|---|---|---|
| Location | Inside a resource's or data source's lifecycle |
Top-level |
| Scope | One specific resource | Anything, several resources included |
| If it fails | Error: the apply fails |
Warning: the apply finishes fine |
| Its own data source | No: it uses the module's | Yes, scoped, and its failures also warn |
Access to self |
Yes | No |
| When it is evaluated | When that resource is created or modified | On every plan and apply, always |
| Appears in the state | No | Yes, in check_results |
| What it is for | Guaranteeing the resource came out right | Verifying the system works |
The "when it is evaluated" row is the most underrated: a check is evaluated on every plan, even when there are no changes. A postcondition is only evaluated if its resource is touched. That makes check blocks the monitoring instrument of section 12.
- EcoMarket's account guard, formalised
Let us take the guard from 05-01 and do it properly.
# infra/app/guards.tf
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
locals {
# Map of environment -> expected account. Fictitious identifiers.
expected_accounts = {
dev = "123456789012"
staging = "123456789013"
prod = "123456789014"
}
expected_regions = {
dev = "eu-west-1"
staging = "eu-west-1"
prod = "eu-west-1"
}
}
check "environment_and_credentials_match" {
assert {
condition = data.aws_caller_identity.current.account_id == local.expected_accounts[var.environment]
error_message = format(
"WRONG ACCOUNT: you are authenticated against %s but the '%s' environment lives in account %s. Run 'export AWS_PROFILE=ecomarket-%s' and try again. Current identity: %s",
data.aws_caller_identity.current.account_id,
var.environment,
local.expected_accounts[var.environment],
var.environment,
data.aws_caller_identity.current.arn,
)
}
assert {
condition = data.aws_region.current.name == local.expected_regions[var.environment]
error_message = format(
"WRONG REGION: the provider points at %s but the '%s' environment is deployed in %s. Check AWS_REGION or the provider configuration.",
data.aws_region.current.name,
var.environment,
local.expected_regions[var.environment],
)
}
assert {
condition = terraform.workspace == "default" || terraform.workspace == var.environment
error_message = format(
"INCONSISTENT WORKSPACE: the active workspace is '%s' but the variables loaded are for '%s'. EcoMarket does not use workspaces for environments (see 06-01): run 'terraform workspace select default'.",
terraform.workspace,
var.environment,
)
}
}And this is what it looks like when it fails:
$ terraform plan -var-file=prod.tfvars data.aws_caller_identity.current: Reading... data.aws_region.current: Reading... data.aws_caller_identity.current: Read complete after 0s [id=123456789012] Terraform used the selected providers to generate the following execution plan. # module.app.aws_launch_template.web will be updated in-place ... Plan: 0 to add, 3 to change, 0 to destroy. ╷ │ Warning: Check block assertion failed │ │ on guards.tf line 22, in check "environment_and_credentials_match": │ 22: condition = data.aws_caller_identity.current.account_id == local.expected_accounts[var.environment] │ │ WRONG ACCOUNT: you are authenticated against 123456789012 but the 'prod' │ environment lives in account 123456789014. Run 'export │ AWS_PROFILE=ecomarket-prod' and try again. Current identity: │ arn:aws:sts::123456789012:assumed-role/developer/joan ╵
But look at the plan: it is still there, and it can be applied. A warning stops nothing. For development that is fine: it warns without holding up legitimate experiments. For production, it is not enough.
The blocking version for production
# A resource that always exists and costs nothing makes a good anchor.
resource "terraform_data" "environment_guard" {
input = {
environment = var.environment
account = data.aws_caller_identity.current.account_id
region = data.aws_region.current.name
}
lifecycle {
precondition {
condition = data.aws_caller_identity.current.account_id == local.expected_accounts[var.environment]
error_message = format(
"WRONG ACCOUNT: authenticated against %s, the '%s' environment lives in %s. Nothing will be applied. Run: export AWS_PROFILE=ecomarket-%s",
data.aws_caller_identity.current.account_id,
var.environment,
local.expected_accounts[var.environment],
var.environment,
)
}
}
}Now the plan fails with an error and nothing can be applied:
╷ │ Error: Resource precondition failed │ │ on guards.tf line 14, in resource "terraform_data" "environment_guard": │ 14: condition = data.aws_caller_identity.current.account_id == ... │ │ WRONG ACCOUNT: authenticated against 123456789012, the 'prod' environment │ lives in 123456789014. Nothing will be applied. Run: export AWS_PROFILE=ecomarket-prod ╵
The terraform_data from 05-05 turns out to be the perfect anchor: it calls no API, it costs nothing, it is always present in the plan and its only job is to hold the precondition.
Careful with the anchor. If you pick a business resource as the anchor — the load balancer, say — the precondition is only evaluated when that resource is planned. With
terraform_dataand aninputthat changes with the variables, the resource is always in the graph and the precondition is always evaluated. That is the difference between a guard that protects and a guard that sometimes protects.
- The platform health check
The second outstanding case from module 5.
terraform {
required_providers {
http = {
source = "hashicorp/http"
version = "~> 3.4"
}
}
}
check "platform_responds" {
# A SCOPED data source: it only exists inside this check.
# If the request fails outright (DNS, TLS, timeout),
# that too is a WARNING, not an apply error.
data "http" "health" {
url = "https://${module.app.load_balancer_dns}/health"
retry {
attempts = 10
min_delay_ms = 3000
max_delay_ms = 15000
}
request_timeout_ms = 10000
}
assert {
condition = data.http.health.status_code == 200
error_message = format(
"The platform is not responding correctly on /health: code %d. URL checked: https://%s/health. Check the target group's status and the application logs before signing the deployment off.",
data.http.health.status_code,
module.app.load_balancer_dns,
)
}
assert {
# The health endpoint returns JSON with the status of its dependencies.
condition = try(jsondecode(data.http.health.response_body).database, "") == "ok"
error_message = format(
"The platform responds but reports a problem with the database. Full response: %s",
data.http.health.response_body,
)
}
assert {
# The deployed version must match the one Terraform believes it put there.
condition = try(jsondecode(data.http.health.response_body).version, "") == var.image_version
error_message = format(
"The platform responds with version '%s' but version '%s' was deployed. The scaling group's rolling update has probably not finished yet: check again in a few minutes.",
try(jsondecode(data.http.health.response_body).version, "unknown"),
var.image_version,
)
}
}Why this is a check and not a postcondition, with three independent reasons:
- A transient failure must not break the deployment. If the load balancer takes a minute longer than expected to mark the instances healthy, a failed
applyadds nothing: the infrastructure is already fine and will sort itself out. - The check crosses several resources. It depends on the load balancer, the scaling group, the database, DNS and the application. It belongs to none of them.
- It must always be evaluated, even when there are no changes, so that it can serve as continuous monitoring (section 12).
And the third assertion — comparing the version that responds with the one deployed — is the kind of check that only occurs to somebody who has lived through a deployment that said "applied" while the old instances were still serving traffic.
The warnings in the output
Terraform will perform the following actions: ... Apply complete! Resources: 0 added, 2 changed, 0 destroyed. ╷ │ Warning: Check block assertion failed │ │ on health.tf line 34, in check "platform_responds": │ 34: condition = try(jsondecode(data.http.health.response_body).version, "") == var.image_version │ │ The platform responds with version '2.4.1' but version '2.5.0' was │ deployed. The scaling group's rolling update has probably not finished │ yet: check again in a few minutes. ╵
The apply finishes successfully with exit code 0. The warning stays in the output and in the state.
The warning when the value is not known at plan time
Before the first apply, module.app.load_balancer_dns does not exist yet, so the check cannot be evaluated:
╷ │ Warning: Check block assertion known after apply │ │ on health.tf line 22, in check "platform_responds": │ 22: condition = data.http.health.status_code == 200 │ │ The condition could not be evaluated at this time, a result will be known │ when this plan is applied. ╵
It is normal and expected on initial creation. If it shows up in a plan for an already deployed environment, however, it means something along the path is being replaced.
check_results: where the result lives
check_results: where the result livesThe results of check blocks are stored in the state, in a check_results section we mentioned in passing in 03-02.
[
{
"object_kind": "check",
"config_addr": "check.environment_and_credentials_match",
"status": "pass",
"objects": [
{
"object_addr": "check.environment_and_credentials_match",
"status": "pass"
}
]
},
{
"object_kind": "check",
"config_addr": "check.platform_responds",
"status": "fail",
"objects": [
{
"object_addr": "check.platform_responds",
"status": "fail",
"failure_messages": [
"The platform responds with version '2.4.1' but version '2.5.0' was deployed. The scaling group's rolling update has probably not finished yet: check again in a few minutes."
]
}
]
}
]The possible statuses are pass, fail, error (the scoped data source could not be resolved) and unknown (not evaluable at plan time).
This enables two useful things:
# 1. Query the health status without running anything
$ terraform state pull | jq -r '
.check_results[]? |
select(.status != "pass") |
"\(.config_addr): \(.status)"
'
check.platform_responds: fail
# 2. In the pipeline: extract the warnings from a plan in JSON
$ terraform plan -out=plan.tfplan
$ terraform show -json plan.tfplan | jq -r '
.checks[]? |
select(.status != "pass") |
"\(.address.to_display): \(.status) — \(.instances[0].problems[0].message // "no message")"
'The second query is the basis of section 12.
- Strategy: what breaks the plan and what warns
This is the part you do not learn from reading the syntax documentation, and it is what distinguishes a well-thought-out configuration.
The criterion is the expected damage and the ability of whoever receives the message to act on it.
| Question | If the answer is yes... |
|---|---|
| Would carrying on cause irreversible or expensive damage? | Block |
| Is the problem in the code, and can whoever is running it fix it now? | Block |
| Could the failure be down to something transient (network, timing, propagation)? | Warn |
| Is the problem outside Terraform's reach? | Warn |
| Do I want to find out even when I am not applying anything? | Warn (check) |
| Would blocking leave somebody unable to deploy an urgent fix? | Warn |
The last question is the one most people forget. A check that is too strict in production can prevent the deployment of an incident fix, and at that point the protection has become the problem.
EcoMarket's decision table
| Check | Instrument | Why |
|---|---|---|
| The CIDR has a valid format | validation |
A pure input error, detectable without touching anything |
The environment is in var.environments |
Direct indexing var.environments[var.environment] |
The Invalid index error is already clear enough |
The AWS account matches the environment in prod |
precondition |
Applying in the wrong account is the most expensive damage imaginable |
The AWS account matches the environment in dev |
check |
Warning is enough; blocking would hold up legitimate experiments |
| The AMI architecture matches the class | precondition |
A code error, fixable now, and without it you get 20 minutes of instances dying |
| The instance class is on the environment's list | precondition |
Cost control: an m6i.8xlarge in dev is money wasted |
The user_data fits in 16 KB |
precondition |
A hard API limit; it would fail anyway, but with a worse message |
| The bucket ends up with versioning | postcondition |
A compliance requirement; if it is not met, you need to know |
| The load balancer has ≥ 2 zones | postcondition |
A design guarantee verifiable after creation |
| The AMI is less than 90 days old | check |
Important, but blocking would prevent deploying an urgent fix |
The platform returns 200 on /health |
check |
It depends on timing and on external services |
The database reports healthy via /health |
check |
Outside Terraform's control |
| The deployed version matches the requested one | check |
Rolling updates take time; it is not a failure |
| The TLS certificate expires in less than 30 days | check |
A continuous warning; blocking would fix nothing |
| The module returns a non-empty DNS name | precondition in output |
The module's contract with its consumer |
| The module produces ≥ 2 subnets | precondition in output |
Likewise |
| The module behaves well with odd inputs | terraform test |
It is not a deployment check, it is a test of the code |
| No security group opens SSH to the internet | A security policy (07-04) | It must apply to the whole repository, not resource by resource |
The last two rows mark the limits described in section 13.
The same condition, two behaviours depending on the environment
There is no way to make a precondition conditional — the lifecycle block accepts neither dynamic nor conditionals, as we saw in 06-03. But the condition can be:
resource "terraform_data" "environment_guard" {
input = var.environment
lifecycle {
precondition {
# In prod it blocks; in the other environments the condition is
# trivially true and gets in nobody's way.
condition = (
var.environment != "prod" ||
data.aws_caller_identity.current.account_id == local.expected_accounts["prod"]
)
error_message = format(
"Attempt to apply in PRODUCTION from account %s. Production lives in %s. Operation aborted.",
data.aws_caller_identity.current.account_id,
local.expected_accounts["prod"],
)
}
}
}
# And alongside it, the check that warns always, in every environment.
check "correct_account" {
assert {
condition = data.aws_caller_identity.current.account_id == local.expected_accounts[var.environment]
error_message = format(
"The active account (%s) is not the one expected for '%s' (%s).",
data.aws_caller_identity.current.account_id,
var.environment,
local.expected_accounts[var.environment],
)
}
}The var.environment != "prod" || <real condition> pattern is the idiomatic way of writing a precondition that only acts in one environment. It reads as "either we are not in production, or the condition holds".
- Error messages that are actually useful
An error_message is the only thing somebody who perhaps did not write the code will see, at three in the morning, with an incident open. It deserves the same care as the code.
The four rules
| Rule | Without it | With it |
|---|---|---|
| 1. Say which value you received | "Instance class not allowed" | "Class 't3.xlarge' is not allowed in 'dev'" |
| 2. Say what you expected | "The account is not correct" | "Account 123456789014 was expected" |
| 3. Say what to do | "Invalid configuration" | "Run: export AWS_PROFILE=ecomarket-prod" |
| 4. Say who to ask | (nothing) | "Justify the exception with [email protected]" |
Bad, better, good
# ❌ BAD: it says nothing useful.
error_message = "Invalid configuration."
# 🔶 BETTER: it says what is happening, but not what to do.
error_message = "The instance class is not allowed in this environment."
# ✅ GOOD: value received, expected values, action and contact.
error_message = format(
"Class '%s' is not allowed in the '%s' environment. Allowed classes: %s. To use another one, modify local.allowed_classes in a pull request and justify the cost with FinOps ([email protected]).",
local.current.web_class,
var.environment,
join(", ", local.allowed_classes[var.environment]),
)Technical details about messages
# 1. Long messages, readable in the code: a heredoc.
error_message = <<-MSG
The invoices bucket has ended up without versioning.
This breaches the 7-year retention requirement.
Probable causes:
- An organisation service control policy is blocking it.
- Somebody disabled it from the console.
Contact [email protected] before continuing.
MSG
# 2. Do NOT interpolate sensitive values: the message is printed in the
# clear in the output and in the pipeline logs.
# ❌
error_message = "The password '${var.db_password}' does not meet the policy."
# ✅
error_message = format(
"The database password has %d characters and at least 16 are required.",
length(var.db_password),
)
# 3. The message must be a STRING and must be evaluable. If it depends on
# a value unknown at plan time, Terraform defers the whole evaluation
# to the apply, which makes the error far less useful.Point 2 is a genuine security warning: length() of a sensitive value is not sensitive, but the interpolated value would be, and error_message is printed unmasked.
The impact on whoever uses your module
Compare the two experiences of somebody who consumes terraform-aws-ecomarket-network and passes it a single zone:
Without a precondition:
╷ │ Error: creating ELBv2 application Load Balancer: ValidationError: │ At least two subnets in two different Availability Zones must be specified │ │ with module.app.aws_lb.main, │ on .terraform/modules/app/load_balancer.tf line 3: ╵
The error points at a file inside .terraform/modules/, mentions a resource the consumer never wrote and does not say which variable to change. Half an hour of investigation.
With a precondition on the network module's output:
╷ │ Error: Module output value precondition failed │ │ on .terraform/modules/network/outputs.tf line 12, in output "private_subnets": │ │ The 'network' module produced 1 private subnet(s) and its contract │ guarantees at least 2. Check the 'zones' variable: it must hold at least │ two different availability zones. ╵
The module's name, what was expected, what was received and which variable to touch. Thirty seconds.
That difference is the entire argument in favour of conditions in published modules.
- Continuous monitoring from a scheduled pipeline
check blocks are evaluated on every plan, even with no changes. That lets you use them as a continuous verification system without writing any tooling.
# .github/workflows/platform-health.yml
name: Platform health
on:
schedule:
- cron: "0 * * * *" # hourly
workflow_dispatch:
jobs:
check:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
environment: [dev, staging, prod]
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.9.8
- name: Read-only credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/ecomarket-read-${{ matrix.environment }}
aws-region: eu-west-1
- run: terraform init -input=false
- name: Plan and evaluate the checks
id: plan
run: |
set +e
terraform plan -input=false -lock=false \
-var-file="${{ matrix.environment }}.tfvars" \
-out=plan.tfplan
echo "code=$?" >> "$GITHUB_OUTPUT"
- name: Extract the check block warnings
run: |
terraform show -json plan.tfplan > plan.json
FAILURES=$(jq -r '
[.checks[]? | select(.status != "pass")] | length
' plan.json)
if [[ "$FAILURES" -gt 0 ]]; then
echo "### Failed checks in ${{ matrix.environment }}" >> "$GITHUB_STEP_SUMMARY"
jq -r '
.checks[]? | select(.status != "pass") |
"- **\(.address.to_display)** (\(.status)): \(.instances[0].problems[0].message // "no message")"
' plan.json >> "$GITHUB_STEP_SUMMARY"
echo "NOTIFY=1" >> "$GITHUB_ENV"
fi
- name: Notify the team
if: env.NOTIFY == '1'
run: |
curl -sS -X POST "$TEAM_WEBHOOK" \
-H 'Content-Type: application/json' \
-d "$(jq -n --arg e "${{ matrix.environment }}" \
'{text: ("Health checks failed in " + $e + ". See the job summary.")}')"
env:
TEAM_WEBHOOK: ${{ secrets.TEAM_WEBHOOK }}Three decisions in that pipeline:
-lock=false: it is a read-only plan and it must not block anybody who is applying. With remote state in S3, an unlocked plan is safe.- Read-only credentials: the scheduled job does not need to be able to apply, and must not be able to.
- The
plan's exit code is kept separate from thecheckfailures:-detailed-exitcodedetects configuration drift; thecheckblocks detect functional problems. They are two different signals and they deserve two different alerts.
What to check continuously
check "certificates_valid" {
data "aws_acm_certificate" "main" {
domain = "ecomarket.example.com"
statuses = ["ISSUED"]
}
assert {
condition = timecmp(
data.aws_acm_certificate.main.not_after,
timeadd(plantimestamp(), "720h"), # 30 days
) > 0
error_message = format(
"The certificate for ecomarket.example.com expires on %s, in less than 30 days. ACM's automatic renewal requires the DNS validation records to still exist: verify them.",
formatdate("DD/MM/YYYY", data.aws_acm_certificate.main.not_after),
)
}
}
check "recent_backups" {
data "aws_db_snapshot" "latest" {
db_instance_identifier = module.data.db_identifier
most_recent = true
}
assert {
condition = timecmp(
data.aws_db_snapshot.latest.snapshot_create_time,
timeadd(plantimestamp(), "-26h"),
) > 0
error_message = format(
"The database's latest backup is from %s, more than 26 hours ago. The daily backup window is not running. Check backup_retention_period and the maintenance window.",
data.aws_db_snapshot.latest.snapshot_create_time,
)
}
}Cost warning. An hourly scheduled plan across three environments is 72 runs a day, each with its full refresh: hundreds of AWS API calls a day. Read calls are free on most services, but they count towards rate limits and can interfere with other processes. Hourly is reasonable for production; every six hours is enough for the rest. And if the health check is all you care about, an external availability monitor is cheaper and more honest than a
terraform plan.
And the conceptual warning, more important than the cost one: Terraform's check blocks are not a substitute for an observability system. They have no history, no thresholds, no aggregation, no silencing, no on-call escalation. They are a useful complement because they live alongside the infrastructure's definition and run without extra tooling. Real monitoring belongs somewhere else.
- Limitations: what a condition cannot do
13.1 A precondition cannot refer to itself
resource "aws_instance" "web" {
instance_type = var.class
lifecycle {
precondition {
condition = self.instance_type != "t2.nano" # ❌
error_message = "..."
}
}
}The resource does not exist yet. Use var.class directly, or a postcondition if you genuinely need the resolved value.
13.2 Unknown values defer the evaluation
resource "aws_lb" "main" {
# ...
lifecycle {
postcondition {
condition = can(regex("^ecomarket-", self.dns_name))
error_message = "..."
}
}
}On the first plan, self.dns_name does not exist. Terraform cannot evaluate the condition and defers the check to the apply. With a check, the warning says so explicitly:
│ Warning: Check block assertion known after apply │ │ The condition could not be evaluated at this time, a result will be known │ when this plan is applied.
The operational consequence: a condition that depends on resource attributes does not protect during the plan, only during the apply. If you want protection at plan time, the condition has to depend on variables, locals and resolvable data sources.
A related and annoying error: if the condition returns null rather than a boolean — easy if you misuse try — Terraform rejects it:
╷ │ Error: Invalid condition result │ │ Condition expression must return either true or false, not null. ╵
The fix: condition = try(<expression>, false), so that absence translates into an explicit failure rather than into null.
13.3 There is no dynamic for conditions
As we saw in 06-03, lifecycle is a meta-argument and cannot be generated dynamically. You cannot write "one precondition per element of this list". The alternative is a single condition with alltrue:
lifecycle {
precondition {
condition = alltrue([
for zone, subnet in var.subnets : can(cidrnetmask(subnet.cidr))
])
error_message = format(
"Some subnet has an invalid CIDR. Subnets received: %s",
jsonencode({ for z, s in var.subnets : z => s.cidr }),
)
}
}The trade-off is that the message cannot point at which one failed, only that one did. Hence the jsonencode of the whole map in the message: if you cannot name the culprit, at least show the list.
13.4 They are not a substitute for tests
A condition verifies this particular run, with these particular values. It does not verify that the module behaves well with other values, or with edge cases, or that a refactor has not broken anything.
# This checks that IN THIS RUN there are at least two subnets.
postcondition {
condition = length(aws_subnet.private) >= 2
}# This checks that the MODULE behaves as it should, given specific
# inputs, without deploying anything. It is terraform test (07-03).
run "single_zone_must_fail" {
command = plan
variables {
zones = ["eu-west-1a"]
}
expect_failures = [output.private_subnets]
}They are complementary: conditions protect the deployment, tests protect the code. 07-03 develops the second half.
13.5 They are not a substitute for security policies
A precondition lives in the resource where you wrote it. There is no way to say "no security group in this repository may open port 22 to the internet" with preconditions: you would have to write it in every security group, including the ones somebody adds tomorrow and the ones that come inside third-party modules.
That is the job of a policy tool — OPA with Conftest, Sentinel, or the ecosystem's static analysers — which are applied to the complete plan in JSON and cover everything that is there, whoever wrote it. It is the subject of 07-04.
| Instrument | Scope | Who writes it | Can it be bypassed |
|---|---|---|---|
precondition / postcondition |
The resource it sits in | Whoever writes the module | Yes: by deleting the block |
check |
Whatever you like, non-blocking | Whoever writes the configuration | Yes: it is only a warning |
terraform test |
The module, in the pipeline | Whoever maintains the module | Yes: by skipping the pipeline |
| A policy (OPA/Sentinel) | The whole plan, always | Security, outside the repository | No, if it is enforced in the pipeline |
The last row is the difference between a good practice and a control. Conditions are good practices: they help whoever wants to do things right. Policies are controls: they stop things being done wrong.
Common Mistakes and Tips
Using self in a precondition. The resource does not exist yet. The special "self" object is not available in this context. If you need the resolved value, it is a postcondition.
Expecting a failed postcondition to roll the resource back. It does not: the resource is already created and in the state, and the apply ends in an error. When in doubt, precondition.
Putting a check where a block was needed. A warning stops nothing. If applying in the wrong account is unacceptable, the guard has to be a precondition, not a check.
Putting a precondition where a warning was needed. A health check that depends on network timing turns a correct deployment into a failed apply, and the next thing that happens is somebody adding -target to skip it.
Hanging a precondition off a resource that is not always planned. It is only evaluated when that resource enters the plan. For global guards, a terraform_data with a variable input is always present.
Writing an error_message without saying the value you received. "Invalid configuration" forces the reader to go through the code to work out what happened. Always interpolate the value and say what to do.
Interpolating a sensitive value into error_message. The message is printed in the clear, in the terminal and in the pipeline logs. Interpolate length(), a hash or a prefix, never the value.
Conditions that return null. Condition expression must return either true or false, not null. It usually comes from a misused try: condition = try(<expr>, false).
Writing a date-based postcondition that will break the plan in 90 days. It is legitimate and it has to be decided consciously, because one day the main branch will stop applying without anybody having changed anything. If the team is not ready, use a check.
Believing a check replaces monitoring. It has no history, no thresholds, no on-call, no silencing. It is a complement that lives alongside the infrastructure, not an observability system.
Believing preconditions are a security control. They are bypassed by deleting the block. Controls belong in the pipeline, with policies applied to the complete plan that whoever writes the configuration cannot modify.
Tip: write the condition thinking of whoever will read it at three in the morning. The message is the part of the code that gets read the most and cared for the least.
Tip: in a published module, every promise in an output's documentation should be a precondition. If the description says "it always returns at least two subnets", that is verifiable.
Exercises
Exercise 1: classifying ten checks
For each one, choose the instrument (validation, precondition, postcondition, precondition in output, check, terraform test or an external policy), say where you would write it and justify it in one sentence.
var.environmentmay only bedev,stagingorprod.- The desired number of instances cannot be greater than the maximum.
- The subnet the database goes in must be private (no route to the internet gateway).
- After creating the bucket, the public access block must be enabled on all four of its options.
- The
datamodule must always return an endpoint inhost:portformat. - The domain's TLS certificate must be valid and not expire in less than 30 days.
- No resource in the repository may be created without the
CostCentertag. - The
networkmodule must fail cleanly if given a CIDR smaller than/20. - The database password must have at least 16 characters.
- The auto scaling group must end up with at least two zones configured.
Exercise 2: the complete production guard
Write a complete infra/app/guards.tf for EcoMarket with these requirements:
- Block any
applyinprodif the active account is not123456789014. - Block if the region is not
eu-west-1, in any environment. - Warn if the active workspace is not
default(EcoMarket does not use workspaces for environments). - Warn if EcoMarket's most recent image is more than 60 days old.
- Block if the environment's instance class is not on its allowed list.
- Warn if the desired number of instances in
prodis fewer than 3.
For each check, write an error_message that follows the four rules from section 11, and add a comment justifying why it blocks or why it only warns.
Exercise 3: the module nobody knows how to use
The terraform-aws-ecomarket-network module gets these recurring complaints from the teams that consume it:
- "I passed it one zone and the error came out inside the
appmodule, three resources further along." - "I passed it a
/26CIDR and theapplyfailed creating the third subnet, after creating the first two." - "I set
create_nat = truewith no public subnets and it failed with an AWS error I did not understand." - "The module returned an empty subnets map and I did not find out until the load balancer."
- Write the conditions that would turn each of those four complaints into a clear, early error, stating the instrument and its exact location.
- For the second complaint, explain why a precondition is clearly better than letting the API fail, and work out how many subnets fit in a
/26withsubnet_bits = 8. - Explain which part of these checks should additionally be tests with
terraform testand why conditions alone are not enough.
Solutions
Solution 1
| # | Instrument | Where | Justification |
|---|---|---|---|
| 1 | validation |
In variable "environment" |
A check on the value itself, needing nothing external; it should fail as early as possible |
| 2 | validation (1.9+) or precondition |
In variable "environments", or on the aws_autoscaling_group resource |
It crosses two fields of the same object; since 1.9 a validation can do it, and before that it was a precondition |
| 3 | precondition |
In the lifecycle of aws_db_instance |
It needs to read the route table with a data source: a validation cannot touch the cloud |
| 4 | postcondition |
In the lifecycle of aws_s3_bucket_public_access_block |
It verifies that the API accepted what was asked; it needs self |
| 5 | precondition in output |
In the data module's output "endpoint" |
It is the module's contract with its consumer, who cannot validate it themselves |
| 6 | check |
A top-level block, with a scoped data "aws_acm_certificate" |
Blocking would fix nothing and would prevent deploying an urgent fix; it must be evaluated always, even with no changes |
| 7 | An external policy (OPA/Sentinel) | In the pipeline, over the plan in JSON | "No resource" cannot be expressed resource by resource; it has to cover resources somebody adds tomorrow and those from third-party modules |
| 8 | terraform test |
tests/network.tftest.hcl, with expect_failures |
It is not a deployment check: it verifies the module's behaviour for a specific input, without deploying |
| 9 | validation |
In variable "db_password" |
A pure input value. Without interpolating the password into the message: use length() |
| 10 | postcondition |
In the lifecycle of aws_autoscaling_group |
A guarantee verifiable after creation, with self.availability_zones or self.vpc_zone_identifier |
Cases 7 and 8 are the ones that separate conditions from the tools that complement them.
Solution 2
# infra/app/guards.tf
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
data "aws_ami" "ecomarket" {
most_recent = true
owners = ["self"]
filter {
name = "name"
values = ["ecomarket-web-*"]
}
}
locals {
expected_accounts = {
dev = "123456789012"
staging = "123456789013"
prod = "123456789014"
}
allowed_classes = {
dev = ["t3.micro", "t3.small", "t4g.micro", "t4g.small"]
staging = ["t3.small", "t3.medium", "m6i.large"]
prod = ["m6i.large", "m6i.xlarge", "c6i.xlarge", "c6i.2xlarge"]
}
expected_region = "eu-west-1"
}
# ══════════════════════════════════════════════════════════════════
# BLOCKING: preconditions on an anchor that is ALWAYS planned.
# terraform_data calls no API, costs nothing and its input depends
# on the variables, so it is in the graph on every plan.
# ══════════════════════════════════════════════════════════════════
resource "terraform_data" "guards" {
input = {
environment = var.environment
account = data.aws_caller_identity.current.account_id
region = data.aws_region.current.name
class = local.current.web_class
}
lifecycle {
# ── Requirement 1. BLOCKS.
# Applying the production configuration against another account can
# destroy somebody else's infrastructure or duplicate production in a
# test account. It is the most expensive, most irreversible damage
# possible: it must never reach the apply.
# The "environment != prod ||" pattern makes it act in production only.
precondition {
condition = (
var.environment != "prod" ||
data.aws_caller_identity.current.account_id == local.expected_accounts["prod"]
)
error_message = format(
"WRONG ACCOUNT FOR PRODUCTION. Active credentials: account %s (%s). Production lives in account %s. Nothing will be applied. Run: export AWS_PROFILE=ecomarket-prod && terraform plan -var-file=prod.tfvars. If you believe you should have access, write to [email protected].",
data.aws_caller_identity.current.account_id,
data.aws_caller_identity.current.arn,
local.expected_accounts["prod"],
)
}
# ── Requirement 2. BLOCKS, in every environment.
# Deploying in another region creates a complete parallel platform:
# VPC, database, load balancer. Double the bill and nobody notices
# until the next cost review. On top of that, the backend key assumes
# eu-west-1: the state would end up describing another region.
precondition {
condition = data.aws_region.current.name == local.expected_region
error_message = format(
"WRONG REGION: the provider points at '%s' and EcoMarket is deployed in '%s' in every environment. Deploying in another region would create a parallel platform with a bill of its own. Check the AWS_REGION environment variable or the provider block. Contact: [email protected]",
data.aws_region.current.name,
local.expected_region,
)
}
# ── Requirement 5. BLOCKS.
# Cost control: an m6i.8xlarge in dev is ~$1,000/month nobody has
# approved. It is a code error, whoever is running it can fix it right
# now by editing the .tfvars, and blocking prevents no legitimate
# urgent deployment.
precondition {
condition = contains(local.allowed_classes[var.environment], local.current.web_class)
error_message = format(
"INSTANCE CLASS NOT ALLOWED: '%s' is not authorised in the '%s' environment. Allowed classes: %s. Fix %s.tfvars. If you need a larger class, open a pull request against local.allowed_classes with the cost justification approved by FinOps ([email protected]).",
local.current.web_class,
var.environment,
join(", ", local.allowed_classes[var.environment]),
var.environment,
)
}
}
}
# ══════════════════════════════════════════════════════════════════
# NON-BLOCKING: warnings evaluated on EVERY plan.
# ══════════════════════════════════════════════════════════════════
# ── Requirement 3. WARNS.
# EcoMarket does not use workspaces for environments (see 06-01), so a
# workspace other than "default" means somebody experimented and did not
# switch back. It is an inconsistency worth flagging, but it could be a
# legitimate ephemeral environment: blocking would be excessive.
check "default_workspace" {
assert {
condition = terraform.workspace == "default"
error_message = format(
"UNEXPECTED WORKSPACE: the active workspace is '%s' and this directory is meant to be used always in 'default' (EcoMarket separates environments with .tfvars files, not with workspaces). If it was not intentional, run: terraform workspace select default",
terraform.workspace,
)
}
}
# ── Requirement 4. WARNS.
# An old image accumulates unpatched vulnerabilities, but blocking would
# prevent deploying an incident fix exactly when it is most needed. The
# warning appears on every plan and in the scheduled pipeline, which is
# where it should be acted on.
check "recent_image" {
assert {
condition = timecmp(
data.aws_ami.ecomarket.creation_date,
timeadd(plantimestamp(), "-1440h"), # 60 days
) > 0
error_message = format(
"OLD IMAGE: the most recent image '%s' was created on %s, more than 60 days ago. It has outstanding security patches. Trigger a new image build with Packer from the image pipeline. If the deployment is urgent, carry on and open a rebuild task. Contact: [email protected]",
data.aws_ami.ecomarket.name,
formatdate("DD/MM/YYYY", data.aws_ami.ecomarket.creation_date),
)
}
}
# ── Requirement 6. WARNS.
# Fewer than three instances in production reduces fault tolerance, but it
# may be deliberate (a temporary reduction for cost, a maintenance
# window). Blocking would prevent a legitimate emergency operation;
# warning leaves a record in the plan and in the state.
check "minimum_production_capacity" {
assert {
condition = var.environment != "prod" || local.current.web_instances.desired >= 3
error_message = format(
"LOW CAPACITY IN PRODUCTION: %d desired instances have been configured and the baseline is 3 (one per availability zone). With fewer, losing one zone drops capacity below the service threshold. If it is a deliberate temporary reduction, ignore this warning and document it. Check web_instances.desired in prod.tfvars.",
local.current.web_instances.desired,
)
}
}A summary of the criterion applied, which is what was really being assessed:
| Requirement | Decision | Deciding criterion |
|---|---|---|
1. Account in prod |
Blocks | Irreversible and hugely expensive damage |
| 2. Region | Blocks | A parallel platform on the meter; a code error fixable now |
| 3. Workspace | Warns | It may be legitimate; it causes no damage by itself |
| 4. Image age | Warns | Blocking would prevent deploying an urgent fix |
| 5. Instance class | Blocks | Cost control; a code error; it holds up no emergency |
6. Capacity in prod |
Warns | It may be a deliberate emergency operation |
Solution 3
1. The four conditions:
# modules/network/variables.tf
variable "zones" {
description = "Availability zones. At least 2 are needed for high availability."
type = list(string)
# Complaint 1, first line of defence: it fails BEFORE anything else,
# even before data sources are resolved.
validation {
condition = length(var.zones) >= 2
error_message = "At least 2 availability zones are required. The AWS application load balancer demands subnets in two different zones, and with a single zone the platform does not tolerate losing a data centre."
}
validation {
condition = length(distinct(var.zones)) == length(var.zones)
error_message = "The zones list contains duplicates. Each zone must appear only once."
}
}
variable "cidr" {
description = "The VPC's CIDR block. It must be /20 or larger to hold the subnets."
type = string
validation {
condition = can(cidrnetmask(var.cidr))
error_message = "The CIDR must be a valid IPv4 block, for example 10.20.0.0/16."
}
# Complaint 2: it fails BEFORE any subnet is created.
validation {
condition = tonumber(split("/", var.cidr)[1]) <= 20
error_message = "The VPC's CIDR must be /20 or larger (less specific). A smaller block leaves no room for the private and public subnets of each zone."
}
}# modules/network/network.tf
resource "aws_vpc" "main" {
cidr_block = var.cidr
# ...
lifecycle {
# Complaint 2, the exact check: it crosses the CIDR, the subnet bits
# and the number of zones. A validation could not do this before 1.9,
# and here the expression is complex enough to deserve a precondition
# with a detailed message.
precondition {
condition = (
pow(2, var.subnet_bits) >= length(var.zones) * 2 &&
tonumber(split("/", var.cidr)[1]) + var.subnet_bits <= 28
)
error_message = format(
"The addressing does not fit: with a CIDR of %s and subnet_bits=%d there is only room for %d subnets of size /%d, and %d are needed (%d zones x 2: private and public). Use a larger CIDR or reduce subnet_bits.",
var.cidr,
var.subnet_bits,
pow(2, var.subnet_bits),
tonumber(split("/", var.cidr)[1]) + var.subnet_bits,
length(var.zones) * 2,
length(var.zones),
)
}
}
}
resource "aws_nat_gateway" "main" {
count = var.create_nat ? length(var.zones) : 0
# ...
lifecycle {
# Complaint 3: a NAT gateway needs a PUBLIC subnet to live in.
# Without this precondition, the error comes from the AWS API and says
# something about a subnet with no route to the internet gateway, which
# does not point at the variable that has to change.
precondition {
condition = !var.create_nat || length(local.public_subnets) > 0
error_message = "create_nat = true was requested but no public subnets are defined. A NAT gateway must live in a public subnet with a route to the internet gateway. Check the subnet configuration or set create_nat = false."
}
}
}# modules/network/outputs.tf
output "private_subnets" {
description = "Map of zone -> private subnet. Guarantees at least 2 distinct zones."
value = {
for z, s in aws_subnet.private : z => {
id = s.id
cidr = s.cidr_block
zone = z
}
}
# Complaint 4: the module's contract, verified. Without this, an empty
# map travels all the way to the load balancer and blows up there with an
# error from another resource the consumer never wrote.
precondition {
condition = length(aws_subnet.private) >= 2
error_message = format(
"The 'network' module produced %d private subnet(s) and its contract guarantees at least 2. Check the 'zones' variable.",
length(aws_subnet.private),
)
}
precondition {
condition = length(distinct([for s in aws_subnet.private : s.availability_zone])) >= 2
error_message = "The private subnets have all ended up in the same availability zone. That is not high availability: check the 'zones' variable."
}
}2. Why a precondition is better than letting the API fail, and the /26 calculation:
Without the precondition, the sequence is this:
terraform applystarts and creates the VPC.- It creates the first subnet:
cidrsubnet("10.20.0.0/26", 8, 0)→ error. - The
applyfails withInvalid CIDRorCIDR block is not a subset of the VPC CIDR. - The VPC is left created, half-finished, and has to be cleaned up by hand or with a
destroy. - The message does not say that the problem is the size of the input CIDR.
With the precondition, the plan fails in three seconds, nothing is created and the message says exactly which CIDR is needed.
The calculation. A /26 with subnet_bits = 8 would produce /34 subnets, which do not exist: the maximum in IPv4 is /32. With the course's functions:
And AWS imposes an extra limit: the smallest subnet allowed is /28, with 16 addresses of which it reserves 5, leaving 11 usable. Hence the <= 28 in the condition. To hold six subnets (three zones x 2) of size /28, the VPC's CIDR has to be at least /25, and in practice /24 to leave headroom. The /20 the validation demands is a recommendation with reasonable slack, not the theoretical minimum.
3. What should additionally be terraform test, and why conditions alone are not enough:
Conditions and tests answer different questions:
| Question | Who answers it |
|---|---|
| "Does this particular deployment meet the assumptions?" | The conditions |
| "Does the module fail the way it should when I give it a bad input?" | terraform test |
| "Has a refactor broken any of those guarantees?" | terraform test |
All four complaints should have a corresponding test:
# modules/network/tests/validations.tftest.hcl
run "single_zone_must_fail" {
command = plan
variables {
cidr = "10.20.0.0/16"
zones = ["eu-west-1a"]
subnet_bits = 8
base_name = "test"
}
expect_failures = [var.zones]
}
run "cidr_too_small_must_fail" {
command = plan
variables {
cidr = "10.20.0.0/26"
zones = ["eu-west-1a", "eu-west-1b"]
subnet_bits = 8
base_name = "test"
}
expect_failures = [var.cidr]
}
run "nat_without_public_subnets_must_fail" {
command = plan
variables {
cidr = "10.20.0.0/16"
zones = ["eu-west-1a", "eu-west-1b"]
subnet_bits = 8
create_nat = true
create_public = false
base_name = "test"
}
expect_failures = [aws_nat_gateway.main]
}
run "valid_configuration_must_plan" {
command = plan
variables {
cidr = "10.20.0.0/16"
zones = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
subnet_bits = 8
base_name = "test"
}
assert {
condition = length(aws_subnet.private) == 3
error_message = "With 3 zones, 3 private subnets must be created."
}
}The three reasons conditions are not enough:
- Conditions are only evaluated when somebody deploys. If nobody uses the module with a single zone, nobody discovers that the precondition had a typo and never fires. The test is run by the pipeline on every pull request, without deploying anything.
- Conditions do not verify that they fail when they should. A badly written precondition —
>=where>belonged, or a condition that is always true — goes unnoticed.expect_failureschecks exactly that: that the module rejects bad inputs. - A refactor can break them silently. Somebody reorganises the
locals, the precondition stops referring to the right thing, and nobody finds out until a consumer brings the cryptic error back. The test catches it in the pipeline, before the version is published.
The summary: conditions protect the deployment; tests protect the conditions. And module 7 takes care of the second half.
Conclusion
This lesson closes module 6 and settles module 5's last debt: everything EcoMarket used to check by hand is now a guarantee Terraform itself verifies.
- Five instruments, five questions.
validationasks whether the input value makes sense;precondition, whether the world is the way it needs to be;postcondition, whether the result came out right;preconditioninoutput, whether the module keeps what it promised; andcheck, whether this actually works right now. - The moment of evaluation changes everything. Conditions over known values are evaluated during the
plan; those depending on resource attributes are deferred to theapply. And a failing postcondition leaves the resource created: there is no rollback. When in doubt, precondition. selfonly exists in postconditions. In a precondition, the resource is not there yet.- Preconditions in outputs are a module's contract. They turn a sentence of documentation into something verified on every
apply, and they replace a cryptic error inside.terraform/modules/with a message that says which variable to change. checkis top-level, it can carry its own scopeddata source, it is evaluated on every plan and it never blocks. Those four properties make it the instrument for health checking and for continuous monitoring from a scheduled pipeline.- EcoMarket's account guard has two faces: a
checkthat warns in every environment and apreconditionon aterraform_datathat blocks in production. The anchor matters: a precondition hanging off a resource that is not always planned is a guard that sometimes protects. - The health check is a
checkfor three independent reasons: a transient failure must not break a correct deployment, the check crosses several resources and none of them owns it, and it must be evaluated always, even with no changes. - The decision between blocking and warning comes down to two questions: would carrying on cause irreversible damage? and would blocking prevent an urgent fix being deployed? A control that is too strict ends up with a
-targetto get round it. - The error message is the most-read part of the code. Say the value you received, say the one you expected, say what to do and say who to ask. And never interpolate a sensitive value: the message is printed in the clear.
check_resultsstores the result in the state, which lets you query health without running anything and extract the warnings withjqfrom the pipeline.- Conditions have five limits: they cannot refer to themselves in a precondition, they cannot see values unknown at plan time, they cannot be generated with
dynamic, they are not a substitute for module tests and they are not a substitute for security policies, because they are bypassed by deleting the block.
And with that, module 6 comes to an end. Looking back: workspaces and why EcoMarket chose separate .tfvars, with the six problems workspaces do not solve and the three cases where they really are the right tool; the functions organised by what you need to do, with cidrsubnet taken apart bit by bit and the 100 offset finally justified, templatefile with its five rules and the functions that break idempotence; dynamic blocks, with module 5's three cases explained and the criterion for preferring a separate resource; importing, which has brought the invoices bucket and the small-hours load balancer into the state; and these conditions, which turn what used to be comments and habits into guarantees.
Module 7, Terraform Best Practices, moves up a level and stops talking about the language to talk about how it is worked with as a team and over time. You will see code organisation — the conversation about directories we left half-finished in 06-01, now with its variants and trade-offs; version control applied to infrastructure, with what goes in the repository, what must never go in and how to review a pull request that modifies production; code testing with terraform test, which is what protects the conditions you have just written and what lets you refactor a published module without fear; security practices, including the policies that really are controls rather than good intentions, static analysis of the plan and secret management; and Terragrunt, the answer to the question left open when EcoMarket went from three environments to twelve.
