Module 4: Terraform Configuration

Lesson 4.7: Custom Conditions

The four mechanisms

Mechanism Where it goes When it's evaluated Failure result
Variable validation validation block inside a variable When the variable's value is known Error. The run stops.
Precondition lifecycle of a resource or data source, or inside an output Before that object is planned or evaluated Error. The run stops.
Postcondition lifecycle of a resource or data source After the object is planned, and again after it is applied. Can use self. Error. Blocks dependent objects. An object that was already created stays.
check block Top-level block with asserts and an optional scoped data block As the final step of every plan and apply Warning only. The run continues.

Since Terraform 1.9, validation conditions can reference other variables and objects, not only the variable being validated.

HCL
variable "replicas" {
  type    = number
  default = 1

  validation {
    condition     = var.environment != "prod" || var.replicas >= 3
    error_message = "prod requires at least 3 replicas."
  }
}

resource "local_file" "config" {
  filename = "${path.module}/app.conf"
  content  = "replicas = ${var.replicas}\n"

  lifecycle {
    precondition {
      condition     = var.replicas <= 5
      error_message = "This host supports at most 5 replicas."
    }
    postcondition {
      condition     = length(self.content) < 100
      error_message = "Rendered config is unexpectedly large."
    }
  }
}

check "config_file_health" {
  data "local_file" "rendered" { # scoped data source: only visible inside this check
    filename = local_file.config.filename
  }

  assert {
    condition     = strcontains(data.local_file.rendered.content, "replicas")
    error_message = "Rendered config is missing the replicas setting."
  }
}

Under the hood

  • If a scoped data source inside a check fails to read, that failure is also reported as a warning, not an error.
  • HCP Terraform health assessments can run check blocks continuously between runs. This is called continuous validation (Module 8).
  • error_message should be a full sentence. It can include interpolation.

Choosing the right mechanism

Situation Mechanism
Reject bad input Validation
Confirm an assumption before building something Precondition
Guarantee a result after building Postcondition
Monitor something without blocking deployments check