For Loops

Terraform provides for-loops and for-each loops. These can be used to loop over variables, transform those, and output in different formats.

For example,

  • [for s in ["this is a ", "list"] : upper(s)] : this loop over the list and make all strings uppercase.

  • We can loop over a list or maps

  • We can even perform calculations or manipulations on values

  • And it's possible to output them as a list or map

For loops

In order to further explore this, let's first create a file with the name vars.tf,

variable "list1" {
  type = list(string)
  default = [1, 10, 9, 101, 3]
}

variable "list2" {
  type = list(string)
  default = ["apple", "pear", "banana", "mango"]
}

variable "map1" {
  type = map(number)
  default = {
   "apple" = 5
   "pear" = 3
   "banana" = 10
   "mango" = 0
  }
}

Let's start the Terraform console and experiment with this file,

To make things more interesting let's create a file with the name provider.tf,

Then replace the content of the vars.tf file,

Finally a file with the name ebs.tf,

Init the modules,

Let's examine the output,

For-Each loops

Let's start this by creating a file with the name provider.tf,

Then let's create a file with the name vars.tf,

Finally a file with the name securitygroup.tf,

Init the modules,

Let's examine the output,

Last updated

Was this helpful?