Loops in a Template

This lesson will cover how to pass array values into a template using a loop.

You can pass in an array of values into a template and loop through them.

Project example

Let’s take a look at an example of how to do that:

%{ for addr in ip_addrs ~}
backend ${addr}:${port}
%{ endfor ~}
Project example for loops in template

This time we are just rendering the template straight to the output. Notice that we are passing in an array for ip_addrs. Let’s look at the code in more detail:

  • In the template, we loop around the ip_addrs array by using a foreach loop.

  • To do a foreach loop we use the syntax %{ for <var> in <variable_name ∼} where <var> is any identifier we want to use to reference the current looped item and <variable_name> is the name of the array that is passed into the template.

  • All of the lines we now write are inside the loop until we signal the end of the loop by putting %{ endfor ∼}.

  • Notice that inside the loop we are using the current value from the ip_addr array and we are always referencing the port.

Project output

When we run the above project, you will notice the following output is rendered for the template:

Press + to interact
backend 10.0.0.1:8080
backend 10.0.0.2:8080

The word “backend” is constant as that is just text, so we see it in each iteration around the loop. The current element of the ip_addr array is then printed, followed by the passed port, which always has the value 8080.

📝Note: Once you are done with the project, do not forget to run terraform destroy and then confirm with yes to delete all of the resources in this project.

Combine loops

The fact that we can combine loops with interpolated values means that you can write some quite elaborate templates. These can be useful for programmatically generating things like IAM policies, where you can pass in the ARN of resources that Terraform creates and use as part of the template.

Get hands-on with 1300+ tech skills courses.