Earlier in this blog post series, you learned about string interpolations, which allow you to reference Terraform code within strings:
"Hello, ${var.name}"
String directives allow you to use control statements (e.g., for-loops and if-statements) within strings using a syntax similar to string interpolations, but instead of a dollar sign and curly braces (${…}), you use a percent sign and curly braces (%{…}).
Terraform supports two types of string directives: for-loops and conditionals. In this section, we’ll go over for-loops; we’ll come back to conditionals later in the blog post. The for string directive uses the following syntax:
%{ for
where COLLECTION is a list or map to loop over, ITEM is the local variable name to assign to each item in COLLECTION, and BODY is what to render each iteration (which can reference ITEM). Here’s an example:
variable "names" {
description = "Names to render"
type = list(string)
default = ["neo", "trinity", "morpheus"]
}
output "for_directive" {
value = "%{ for name in var.names }${name}, %{ endfor }"
}
When you run terraform apply, you get the following output:
$ terraform apply
(...)
Outputs:
for_directive = "neo, trinity, morpheus, "