Search code examples
terraformterraform0.12+terraform-template-file

adding extra element to a list in terraform if condition is met


I have a list in terraform that looks something like:

array = ["a","b","c"]

Within this terraform file there are two variables called age and gender, and I want to make it so that the list called array has an extra element called "d" if age is equal to 12 and gender is equal to male (i.e. if var.age == 12 && var.gender == 'male' then array should be ["a","b","c","d"], else array should be ["a","b","c"]). Would the following going along the right path, or would I need to use another method?

array = ["a","b","c", var.age == 12 && var.gender == 'male' ? "d" : null]

Solution

  • There are few ways you could do it. One way would be (example):

    variable "array" {
      default = ["a","b","c"]
    }
    
    variable "age" {
      default = 12
    }
    
    variable "gender" {
      default = "male"
    }
    
    locals {
      array = var.age == 12 && var.gender == "male" ? concat(var.array, ["d"]) : var.array
    }
    
    output "test" {
      value = local.array
    }