Preconditions, postconditions and check blocks

Intermediate · 22 min

Write down what a resource assumes and what it guarantees. Which custom conditions stop an apply, which only warn, and how they differ from validation.

Before thisInput variables and validationData sources

Ned in the Cloud · 22 min

Preconditions, postconditions and check blocks

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Ned in the CloudReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A `precondition` inside a resource's `lifecycle` block states an assumption that must hold before the object is created or updated. A `postcondition` states a guarantee about the object afterwards. Both stop the run with your error message when they fail.
  • Both work on resources and data sources, and `precondition` also works on outputs. They arrived in Terraform 1.2.
  • A `check` block holds assertions evaluated as the last step of a plan or apply. A failed assertion is a warning only and the operation continues. Checks arrived in 1.5.
  • Input variable `validation` looks at one variable's value. Conditions can look at anything the resource can reach, such as a data source's attributes, so they catch mismatches between values.
  • Use a precondition for a bad input, a postcondition for a bad result from a provider, and a check for something that should be true about the running system but must not block a change.

A valid plan for the wrong thing

terraform validate passes. The plan is clean. Apply starts, and four minutes later the cloud rejects the request because the instance type needs an ARM image and the AMI you looked up is x86. The configuration was syntactically fine and logically wrong, and Terraform discovered it by trying. Better is to write the assumption down where Terraform can test it first, with a message that says what to fix. That is what custom conditions are for.

Preconditions

A precondition goes in the lifecycle block of a resource or data source, and it is a statement that must be true before Terraform evaluates that object. I wrote this example from the language docs. I did not run it, since there is no Terraform or AWS account on this machine:

data "aws_ami" "web" {
  owners      = ["amazon"]
  most_recent = true
  # filters
}

resource "aws_instance" "web" {
  ami           = data.aws_ami.web.id
  instance_type = var.instance_type

  lifecycle {
    precondition {
      condition     = data.aws_ami.web.architecture == "x86_64"
      error_message = "The AMI must be x86_64 to match instance_type ${var.instance_type}."
    }
  }
}

If the condition is false, Terraform stops with your message, and the instance is never touched. Precondition and postcondition checks arrived together in Terraform 1.2, and a precondition also works on an output. Since 1.2 too, the changelog notes that the error message can use expressions, so you can include the offending value.

Postconditions

A postcondition goes in the same place and is evaluated after the object exists. It is a guarantee that downstream code relies on, and a failure blocks whatever depends on the object. This catches the case where the provider returned something unexpected: a subnet without the tag the next module expects, a data source returning an empty list. Inside a postcondition you refer to the object itself with self.

I wrote a toy to show the ordering. It is a Python stand-in with my own wording, and the messages are not Terraform’s. A precondition fails before the resource exists. A postcondition fails after, and the check at the end only warns:

--- wrong architecture
Error: Resource precondition failed: AMI architecture is arm64, need x86_64. Nothing was created.
exit: 1
--- right architecture
aws_instance.web: created (t3.small)
Error: Resource postcondition failed: instance must be EBS optimized. Dependents will not run.
Warning: Check block assertion failed: endpoint returned 503
exit: 1

Check blocks

A check block is for things that should be true but should not stop a change. Terraform 1.5 added it. The docs say Terraform runs a check as the last step of a plan or apply, after it has planned or provisioned the infrastructure, and a failed assertion produces a warning while the operation continues. They call it the only validation that does not block operations.

check "site_is_up" {
  data "http" "home" {
    url = "https://${aws_lb.web.dns_name}/health"
  }

  assert {
    condition     = data.http.home.status_code == 200
    error_message = "The health endpoint did not return 200."
  }
}

Written from the check block docs, not run. A check can hold its own scoped data source, as above. That data source can only be referenced inside the check, and it is how a check reads the outside world without making the rest of the configuration depend on it. A check block can contain several assertions. HCP Terraform can run checks continuously as health checks on a workspace. Checks also run during import operations, per the 1.5 changelog.

Which one

The table below shows the choice I use.

Question Use
Is this input acceptable? (one variable, no other context) validation on the variable
Do these two things agree before I create something? precondition
Did the provider give me what the rest of the code needs? postcondition
Is the running system healthy, without blocking a change? check

Variable validation, covered in the language group, looks at one variable. Terraform 1.9 relaxed it so it can refer to other values, but it still belongs to that variable and fires when the variable is evaluated. A precondition sits on the thing that has the assumption, so the error appears next to the resource that needs it. Keep messages short and say what to do.

Do not overuse

Every condition is code you maintain and a place a run can fail. A postcondition that repeats what the provider already enforces adds noise. Put conditions at boundaries: where a module takes in values from outside, where a data source can return something surprising, and where a wrong value is expensive. Test them with a bad input once, so you know the message reads well.

About the video

The embed is Ned Bellavance’s “Using Precondition and Postcondition Blocks in Terraform”, published June 2023 (Terraform 1.2 features), 22 minutes. His description explains pre- and postconditions as sanitising inputs and making guarantees for the next link in the chain, on data sources, resources and outputs. That is this lesson’s main subject. It has no chapters. Check blocks are in his separate video, linked in deeper, from August 2023. Neither video covers the 1.9 variable validation changes, which he treats in another episode. English was judged from the title, description and the channel’s English auto-caption track.

Where this fits

Conditions make a configuration fail early and loudly. The next two lessons deal with what happens to the secrets that configurations pass around, starting with sensitive values and secrets in state.

Check yourself

  1. 01Which block would you use to make sure a looked-up AMI is x86 before launching an instance from it?

    A `precondition` on the instance, referencing the AMI data source's `architecture`. It fails the run before any instance is created, with your message.

  2. 02Which of precondition, postcondition and check blocks can fail an apply, and which cannot?

    Preconditions and postconditions stop the operation with an error. A check block only reports a warning and lets the operation finish.

  3. 03Why can a precondition do something a variable `validation` cannot?

    Validation is attached to one variable. A precondition lives on a resource or data source and can reference other resources, data sources and variables together, so it can test whether two values agree.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark