Preconditions on Outputs
Crumb's deploy script reads a site_url output. One day the web server comes up without a public DNS name, the output quietly becomes http://, and the deploy fails in a confusing way far from the cause. A precondition turns that silent mistake into a clear error at the source.
The rule
State the assumption; if it is false, stop with a clear message.
A precondition is a nested block with two arguments:
output "site_url" {
value = "http://${aws_instance.web.public_dns}"
description = "Address of Crumb's website"
precondition {
condition = aws_instance.web.public_dns != ""
error_message = "The web server has no public DNS name, so the site URL would be empty."
}
}condition— an expression that must betruefor things to be fine. It usually refers to other objects in the configuration.error_message— shown to the person running Terraform when the condition isfalse. Write a full sentence that says what is wrong.
Terraform checks an output's preconditions before it settles the output's value. If one fails, the run stops with an error, so nobody downstream receives a broken value. An output may have several precondition blocks; all must pass.
When is it checked? As early as possible. If the values are known during plan, the plan fails. If they are (known after apply), the check runs during apply.
Preconditions also exist in a resource's lifecycle block, along with postconditions that check a resource after it is created. Outputs accept only preconditions.
A precondition on an output is cheap insurance at a boundary. Outputs are what people and scripts rely on, so a check there protects everyone downstream, and the error points straight at the cause instead of at the script that later trips over a bad value.
The shortcut
Finish the sentence "This output is only useful if …". Whatever follows "if" becomes the condition; the reverse, stated plainly, becomes the error_message.
Finish the sentence
"The site URL is only useful if the server has a public DNS name."
The trap: writing the condition backwards. The condition describes the good case; Terraform complains when it is false.
Drills
Answer fast — trust the rule.
What two arguments does a precondition block need?
When does Terraform report a failed precondition?
The condition refers to a value shown as (known after apply). When is it checked?
Which kind of condition block can an output have?
Remember
precondition { condition = ..., error_message = ... }guards an output.- Shortcut: "only useful if …" becomes the condition.
- Trap: the condition is the good case; false is the failure.
