Terraform: Input Variable Checking

1 minute read

Description:

Quick post here about how you can go about using Input Validation checks with Terraform variables.

To Resolve:

  1. A simple example with two values:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    variable "region" {
       description = "(Optional) The name of the region. Example: West US."
       type        = string
       default     = "westus"
    
       validation {
          condition     = var.region == "westus" || var.region == "eastus"
          error_message = "The region must be westus or eastus."
       }
    }
    
  2. An example with many values:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    variable "sub_abbr" {
       description = <<EOF
       (Required) The abbreviated name of the subscription. Used for naming resources.
       Must be one of the following:
       abc  => subscription abc
       def  => subscription def
       ghi  => subscription ghi
       EOF
       
       type        = string
       
       validation {
       condition = (var.sub_abbr == "abc" ||
          var.sub_abbr == "def" ||
          var.sub_abbr == "ghi")
       error_message = "The subscription abbreviation must be one of: `abc,def,ghi` ."
    }
    }
    
  3. A cleaner way using contains:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    variable "sub_abbr" {
       description = <<EOF
       (Required) The abbreviated name of the subscription. Used for naming resources.
       Must be one of the following:
       abc  => subscription abc
       def  => subscription def
       ghi  => subscription ghi
       EOF
       
       type        = string
       
       validation {
          condition     = contains(["abc","def","ghi"], var.sub_abbr)
          error_message = "The subscription abbreviation must be one of: `abc,def,ghi` ."
       }
    }
    

Comments