Terraform provides a variable validation feature that allows defining conditions to validate variable inputs. Previously, variable validation only allowed validating the input of the variable itself. However, starting with Terraform 1.9, this feature has been enhanced to allow the addition of validation conditions that reference other input variables and objects. This blog presents a simple example that explains how to add a condition to one variable that references another variable.
Pre-requites: Terraform 1.9 or greater
The following sample script is used to create two Azure resource groups. One in the West Europe region and the other in the East US region. The two resource groups should not be created in the same region.
main.tf- script for creating two resource groups
variable.tf - variable location02 has a validation condition which compares the input values of the location01 variable with location02 variable
Let's change the input values as below in terraform.tfvars. location01 and location02 have different values.
terraform.tfvars
Now run the terraform init and terraform plan commands. The terraform plan will results as shown below without any validation errors because it meets the defined variable validation condition.
Now change the input values as shown below in the terrafom.tfvars file. Then, run terraform plan to see the results when the same value is assigned to both location1 and location2.
location01 = "eastus"
location02 ="eastus".
Now, a variable validation error has occurred as defined in the variable validations. Similarly, variable validation can be used to ensure that users provide valid and expected values, preventing misconfigurations
No comments:
Post a Comment