yelmir
yelmir

Reputation: 43

retrieve values from a list based on criterea using terraform syntax HCL

I am looking for a terraform expression to retrieve values from a list, i have a list of values

namespaces = [blue,red,green,ns-blue,ns-green,ns-grey]

I would like to retrieve in list format just the values contains "ns", as a result i must get:

namepsace-filtred = [ns-blue,ns-green,ns-grey]

thanks in advance.

Upvotes: 0

Views: 333

Answers (1)

Ervin Szilagyi
Ervin Szilagyi

Reputation: 16815

Assuming you have a list of strings for a variable namespace:

variable "namespaces" {
  default = ["blue", "red", "green", "ns-blue", "ns-green", "ns-grey"]
}

You can use a for with the regex function to check if a string contains a substring. Also, you have to use the can function to transform the result of the regex to a boolean:

locals {
  namepsace_filtred = [for ns in var.namespaces : ns if can(regex("ns", ns))]
}

The result of this should be something like this:

namepsace_filtred = [
  "ns-blue",
  "ns-green",
  "ns-grey",
]

Upvotes: 1

Related Questions