Header Ads

Header ADS

Terraform :: Custom Validation Rules


Custom Validation Rules

This feature was introduced in Terraform CLI v0.13.0.
This feature allows us to have more control over the validation of our variable's data. We can now automatically test that our input values are set correctly in our templates and modules, it's a basic boundary check.

The basics are explained in the documentation, here
You can specify custom validation rules for a particular variable by adding a validation block within the corresponding variable block.

 

To see what's really possible we need to combine these conditions, with the functions that are already available in Terraform:

The example below checks the vpc_id_main has the correct syntax: 

variable "vpc_id" {
type = string
default = "vpc-014eac810307cc61c"

validation {
condition = length(var.vpc_id) > 3 && substr(var.vpc_id, 0, 4) == "vpc-"
error_message = "The vpc_id value must be a valid vpc id, starting with \"vpc-\"."
}
}

The example below checks the if the amount of instances that I defined is bigger than 1 and less than 10: 

variable "instances_number" {
type = number
default = 1

validation {
condition = var.instances_number > 0 && var.instances_number <= 10
error_message = "The instances_number value must be > 0 and < 10"
}
}


Check to see value is not null: 

variable "config_file" {
type = string
description = ""
validation {
condition = length(var.config_file) > 0
error_message = "This value cannot be an empty string."
}
}


Check to see the item is set to valid options only

variable "tracing_mode" {
type = string
description = "x-rays settings"
default = "Active"

validation {
condition = contains(["PassThrough","Active"], var.tracing_mode)
error_message = "Tracing mode can only be PassThrough or Active."
}
}


Checking the role 


Checking the role for a number of instances I want to create, I've defined it to 11, but on the rule, I've defined the number should be > 0 and <= 10, thus we will see the following warning: 

isweluiz@isweluiz:~/Documents/terraform/cloud/aws$ terraform validate
│ Error: Invalid value for variable
│ on main.tf line 29, in module "aws-instance-template":
29: instances_count = 11
│ ├────────────────
│ │ var.instances_count is 11
│ The instances_count value must be > 0 and < 10
│ This was checked by the validation rule at modules/aws-instance-template/default_variables.tf:28,3-13.


As you can see this will help you construct both your own templates and anyone consuming your modules, and so increase their re-usability, which is awesome.

No comments

Theme images by sandsun. Powered by Blogger.