Home > OS >  Use cases - for vs for_each in terraform - struggling to visualise
Use cases - for vs for_each in terraform - struggling to visualise

Time:11-24

Is the for expression in Terraform basically just to provide more granular control on a for_each meta argument, so maybe it just iterates on a subset of a list, for example?

The difference between for_each and count is clear enough. I am just a bit lost trying to visualise the point of the for

Many thanks for any pointers, including articles. Google isn't proving that helpful

CodePudding user response:

Hmm, answering my own Q..

Seems to be helpful to apply a function to a list,etc that is being iterated in a resource e.g. changing case, converting variable type, decoding from base64, etc

CodePudding user response:

In Terraform for and for_each are used for different purposes.

for_each is a meta-argument. It is applied to resources and to modules (Terraform 0.13 and above). for_each meta-arguments accepts a set or a map, for every item from the set/map a new resource is created.

For example:

resource "aws_instance" "example" {
  for_each = {
    "t2.micro" = "ami-b374d5a5"
    "t3.nano"  = "ami-4b32be2b"
  }

  instance_type = each.key
  ami           = each.value
}

This will create 2 EC2 instances with instance types and AMIs from the map. Please note, for_each provides each.key and each.value objects which can be used when iterating through the map to reference its key-value items. If the input of a for_each is a set, than each.key and each.value are pointing to the same value.

for, in the other hand, is an expression used to manipulate lists, sets, tuples and maps. It can be used to apply some transformations to the elements of those complex types.

For example:

variable "names" {
  default = ["alice", "bob"]
}

locals {
  upper = [for n in names: upper(n)] # result will be ["ALICE", "BOB"]
}

The ouput of a for expression can be used as input for a for_each.

Example:

var ids {
 default = ["b374d5a5", "4b32be2b"]
}

resource "aws_instance" "example" {
  for_each = toset([for id in ids: "ami-${id}"])

  instance_type = "t2.micro"
  ami           = each.value
}
  • Related