Terraform Validations

Terraform validations are a set of checks performed on a Terraform configuration to ensure its correctness and adherence to best practices before executing the infrastructure-as-code deployment.

Validation of input variables in Terraform uses the validation block. This allows us to impose certain conditions on the values of the input variables, ensuring that they conform to specific expectations before Terraform executes the plan.

Consider an example where you’re defining a variable for an AWS region. You want to ensure that only specific AWS regions are used. You can set up a validation block to allow only certain values:

variable "region" {
  description = "AWS region"

  validation {
    condition     = contains(["us-west-1", "us-west-2", "us-east-1", "us-east-2"], var.region)
    error_message = "The region must be either us-west-1, us-west-2, us-east-1 or us-east-2."
  }
}

In this example, if a region other than “us-west-1”, “us-west-2”, “us-east-1”, or “us-east-2” is provided, Terraform will return an error and halt execution.

For a second example, consider a variable for setting the size of a disk. You want to ensure that the disk size is at least 10 GB and not more than 1000 GB. You can use a validation block as follows:

variable "disk_size" {
  description = "Size of the disk in GB"

  validation {
    condition     = (var.disk_size >= 10) && (var.disk_size <= 1000)
    error_message = "The disk size must be between 10 and 1000 GB."
  }
}

Here, if the provided disk size is less than 10 GB or more than 1000 GB, Terraform will return an error and stop the execution.

These validation blocks help to ensure that the input provided by users, or defined elsewhere, adhere to the expectations of your infrastructure configurations. This assists in maintaining the reliability and correctness of your infrastructure deployments.

You can use multiple different validation blocks for the variable.

Validation blocks can only reference the variable where it is set, so you cannot use a single validation block against multiple different variables.

Last modified July 21, 2024: update (e2ae86c)