Handling Variable Validations in Terraform

Tanmay Bhat
3 min readMay 7

--

Variable validations allow you to ensure that the values passed to your Terraform variables meet certain criteria before the resources are created. You can add a validation block to your variable definition, which contains a condition that must evaluate to true for the variable value to be considered valid. If the condition is not met, Terraform will throw an error over plan stage.

Variable validations

Let’s imagine an example where you’re defining an EC2 machine root volume size via variable worker_root_volume_size. In this case, you can add a validation to the variable’s value i.e. disk size to be at least 30 GB, if the specified value is less than 30, the check will fail.

variable "worker_root_volume_size" {
description = "The HDD size in GB to configure for the Kasm WebApp instances"
type = number

validation {
condition = can(var.worker_root_volume_size >= 30)
error_message = "worker node should have at least a 30 GB root volume disk size."
}
}

resource "aws_instance" "worker_instance" {
...
root_block_device {
volume_size = var.worker_root_volume_size
...
}

If the validation fails, when you run terraform plan, you will receive an error message similar to the following:

Error: Invalid value for variable
on ec2.tf line 1:
1: variable "worker_root_volume_size" {
var.worker_root_volume_size is 20

worker node should have at least a 30 GB root volume disk size.

Let’s take a look at a few other variable validation examples :

Invalid subnet CIDR

In this example, we’re validating where the given CIDR for the subnet is valid or not using the built-in function cidrhost. Read more on the function here.

variable "primary_vpc_subnet_cidr" {
description = "The subnet CIDR to use for the VPC"
type = string
default = "10.10.1.0/16"

validation {
condition = can(cidrhost(var.primary_vpc_subnet_cidr, 0))
error_message = "The VPC subnet must be valid IPv4 CIDR."
}
}

Invalid AWS Region

Here we’re validating the specified aws-region value with the approved regions to create the infrastructure.

variable "aws_region" {
description = "The region in which to create the infrastructure"
type = string
nullable = false
default = "CHANGE-ME"
validation {
condition = var.aws_region == "us-west-2" || var.aws_region == "eu-west-1"
error_message = "The variable 'aws_region' must be one of the following regions: us-west-2, eu-west-1"
}
}

Invalid ECR repository name

Here we’re validating whether the ECR repo name is in uppercase or not, since it's an invalid naming convention.

variable "ecr_repo_name" {
validation {
condition = var.ecr_repo_name == upper(var.ecr_repo_name)
error_message = "ECR repository name cannot be in uppercase"
}
}

--

--