Terraform Tutorial · Modules and Quality · Lesson 22 of 25

Terraform Validation and Checks

Catch mistakes early with variable validation, preconditions and postconditions on resources, and check blocks that continuously verify your infrastructure.

Variable validation

Validate with regex and can()
variable "instance_type" {
  default = "t3.small"

  validation {
    condition     = can(regex("^t3\\.", var.instance_type))
    error_message = "Only t3 instance types are allowed."
  }
}

variable "cidr" {
  default = "10.20.0.0/16"

  validation {
    condition     = can(cidrhost(var.cidr, 0))
    error_message = "cidr must be a valid IPv4 CIDR block."
  }
}

output "checked" {
  value = "${var.instance_type} in ${var.cidr}"
}

Output

checked = "t3.small in 10.20.0.0/16"

Run this on your computer — see “Get Started” for setup.

Preconditions and postconditions

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

  lifecycle {
    precondition {
      condition     = data.aws_ami.app.architecture == "x86_64"
      error_message = "The AMI must be x86_64."
    }
    postcondition {
      condition     = self.public_ip != ""
      error_message = "The instance must get a public IP."
    }
  }
}

check blocks

check blocks (Terraform 1.5+) run on every plan and apply and report warnings instead of stopping, which makes them good for health checks:

check "website" {
  data "http" "home" {
    url = "https://${aws_lb.app.dns_name}/health"
  }
  assert {
    condition     = data.http.home.status_code == 200
    error_message = "The health check didn't return 200."
  }
}

Test yourself

What happens when a check block's assert fails?

  1. The apply stops
  2. Terraform shows a warning and continues
  3. The resource is destroyed
  4. Nothing is reported
Show answer

Answer: Terraform shows a warning and continues