Variable Validation in Terraform
Introduction:
In this post we will deep dive into custom validation rules for input variables in terraform as well explained in official documentation.
For example, we have declared a variable in variable.tf file as :
variable "ami_id" {
type = string
description = "The id of machine image (AMI) to use for the server."
}
Now we add a validation rule to this variable block:
variable "ami_id" {
type = string
description = "The id of machine image (AMI) to use for the server."
validation {
condition = length(var.ami_id) > 4 && substr(var.ami_id, 0, 4) == "ami-"
error_message = "The ami_id value must be a valid AMI id, starting with \"ami-\"."
}
}
Next, we’ll use can function to validate below:
Boolean variables
variable "boolean_variable" {
type = bool
description = "Example to validate a boolean variable."
validation {
condition = can(regex("^([t][r][u][e]|[f][a][l][s][e])$",var.boolean_variable))
error = "The boolean_variable must be either true or false."
}
}
valid inputs : true || false
invalid inputs: tru, no, 0, 1, yes
IP address
variable "ip_address" {
type = string
description = "Example to validate IP address."
validation {
condition = can(regex("^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$",var.ip_address))
error_message = "Invalid IP address provided."
}
}
valid inputs : “10.10.60.181”
invalid inputs : “10.0.1.” , “10.40.0.256” , “10.0.10,180”
List of IP addresses
variable "ip_address_list" {
type = string
description = "Example to validate list of IP addresses."
validation {
condition = can([for ip in var.ip_address_list: regex("^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", ip)])
error_message = "Incorrect IP."
}
}
valid inputs : [“10.40.0.16”, “10.60.0.17”, “10.50.0.18”]
invalid inputs: [“10.40.0.256”, “10.60.017”, “10.50,0.18”]
Note: Validation error message must be at least one full English sentence starting with an uppercase letter and ending with a period or question mark.
You can validate your regex here .