You’ve now seen how to use loops to create multiple copies of entire resources and inline blocks, but what if you need a loop to set a single variable or parameter?
Imagine that you wrote some Terraform code that took in a list of names:
variable "names" {
description = "A list of names"
type = list(string)
default = ["neo", "trinity", "morpheus"]
}
How could you convert all of these names to uppercase? In a general-purpose programming language such as Python, you could write the following for-loop:
names = ["neo", "trinity", "morpheus"]
upper_case_names = []
for name in names:
upper_case_names.append(name.upper())
print upper_case_names
Python offers another way to write the exact for-loop in one line using a syntax known as a list comprehension:
upper_case_names = [name.upper() for name in names]
Python also allows you to filter the resulting list by specifying a condition:
short_upper_case_names = [name.upper() for name in names if len(name) < 5]
Terraform offers similar functionality in the form of a for expression (not to be confused with the for_each expression you saw in the previous section). The basic syntax of a for expression is as follows:
[for :