[Cloud Ops Tips & Tricks 1] Using Basic Loops in Terraform Templates

Adam Yang
Adam Yang
Nov 5 · 2 min read

#DevOps #Infrastructure-as-Code #Terraform #AWS

Among all the Infrastructure-as-Code tools I have used, I would say Terraform is the most powerful one not only because of its unified user experience for different platforms but also because of the syntax it has (the HCL syntax) is close to programming languages that developers are familiar with.

Terraform has a lot of advanced features that other similar tools cannot offer. In this article, I will give you a brief introduction of the first powerful feature that I love — Basic Loops.

Use Cases

Imagine that you need to create or configure a set of identical cloud resources regularly at work, like creating a list of new users for the development team, adding alerts to all VMs, attach an IAM role to multiple EC2 instances. Instead of doing it manually or writing a bash script, you can write a Terraform template for this particular task and whenever you have to do it again, all you need to do is to input the variables of the templates (like the instance IDs, list of usernames) and apply the template again.

How to write a Terraform Template with Basic Loops

Below is an example Terraform template for creating one IAM user in AWS. To make it become a template that can create multiple users in one go with the list of usernames you provide, you may follow the 3 steps below.

1. Change the input variable type to list

In this case, we will define a list of usernames as the input variable instead of one single user name, like below:

variable “user_name” {

type = list

}

2. Within the resource configuration that will be iterated through, add a [count] parameter to define the total number of the iteration as the length of the list

resource “aws_iam_user” “example” {

count = length(var.user_name)

name = var.user_name

……

3. Change the variable part of the resource configuration

resource “aws_iam_user” “example” {

count = length(var.user_name)

name = var.user_name[count.index]

……

It’s done! Now if you run “terraform apply” and enter a list of usernames as below, terraform will create all your users in one go.

Using the [count] parameter is just the basic way to deal with loops. Terraform also provides other parameters like [For] and [For_each] to achieve nested loops and other advanced configurations possible.

Reference: https://www.terraform.io/docs/configuration/resources.html

Adam Yang

Written by

Adam Yang

Cloud Engineer based in Hong Kong

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade