Sunday, September 8, 2024

Advanced Input Variable Validation with Terraform

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

resource "azurerm_resource_group" "az-region01-rg" {
  name     = "${var.location01}-test"
  location = var.location01
}


resource "azurerm_resource_group" "az-region02-rg" {
  name     = "${var.location02}-test"
  location = var.location02
}

variable.tf - variable location02 has a validation condition which compares the input values of the location01 variable with location02 variable

variable "location01" {
  type        = string
  description = "Location of the resource group 01"
}

variable "location02" {
  type = string
  validation {
    condition     = var.location02 != var.location01
    error_message = "Location 02 should be different from Location 01"
  }
}

Let's change the input values as below in terraform.tfvars. location01 and location02 have different values.

terraform.tfvars 

location01 = "westus"
location02 = "eastus"

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