Read this after completing this section

What are Preconditions & Postconditions?

Checks that must be true before or after a resource is created.

If check fails → Terraform stops with error message.


precondition

Runs before resource creation — validates input or state before proceeding.

Syntax

lifecycle {
  precondition {
    condition     = <expression>
    error_message = "Error text if condition is false"
  }
}

Example: Bucket name must not be empty

resource "aws_s3_bucket" "example" {
  bucket = var.bucket_name

  lifecycle {
    precondition {
      condition     = var.bucket_name != ""
      error_message = "The bucket name must not be empty."
    }
  }
}

How it works:

User runs: terraform apply
  ↓
Precondition checks: is bucket_name != "" ?
  ↓
If true  → proceeds to create bucket
If false → stops with error: "The bucket name must not be empty."

Use case: Validate variables before wasting time creating resources.


postcondition

Runs after resource creation — validates the created resource has expected properties.

Syntax