Terraform contains function not working as expected

133 Views Asked by At

I want to filter my list of strings in Terraform based on the 'app' and 'db' tiers. However, the contains function returns an empty result with the string 'app'

variable "tiers" {
  type    = list(string)
  default = ["app-1", "app-2", "db-1", "db-2"]
}

output "iterate-apps" {
  value = [
    for app_id in var.tiers : app_id
    if contains(["app"], app_id)    
  ]
}

Actual :

+ iterate-apps = []

Expected :
iterate-apps = [ + "app-1", "app-2" ]

correct me what is wrong in the above code ?

2

There are 2 best solutions below

0
Marcin On BEST ANSWER

Its better to use strcontains, rather than contains:

output "iterate-apps" {
  value = [
    for app_id in var.tiers : app_id
    if strcontains(app_id, "app")    
  ]
}
0
Uday Kiran On

You can use regular expression

output "iterate-apps" {
  value = [
    for app_id in var.tiers : app_id
    if length(regexall("(?i)\\bapp\\b", app_id)) > 0
  ]
}