vivek mishra
vivek mishra

Reputation: 91

Understanding Terraform for_each loop iteration

I am learning terraform and trying to understand the for_each loop iteration in terraform.

I am iterating through a loop for creating RGs in Azure cloud and what I want to understand is the difference between accessing the value of an instance using . or [""]. So for example, below is my tfvar file:

resource_groups = {
  resource_group_1 = {
    name     = "terraform-apply-1"
    location = "eastus2"
    tags = {
      created_by = "[email protected]"
    }
  },
  resource_group_2 = {
    name     = "terraform-apply-2"
    location = "eastus2"
    tags = {
      created_by = "[email protected]"
    }
  },

  resource_group_3 = {
    name     = "terraform-apply-3"
    location = "eastus2"
    tags = {
      created_by = "[email protected]"
      contact_dl = "[email protected]"
    }
  }
}

and below is my terraform main.tf file:

resource "azurerm_resource_group" "terraformRG" {
  for_each = var.resource_groups
  name = each.value.name
  location = each.value.location
  tags = each.value.tags
}

I am confused with the expression in for_each in RG creation block. Both the below codes works and create RGs:

name = each.value.name
name = each.value["name"]

I want to understand the difference between the two and which one is correct.

Upvotes: 3

Views: 520

Answers (1)

Marcin
Marcin

Reputation: 238081

They are equivalent as explained in the docs:

Map/object attributes with names that are valid identifiers can also be accessed using the dot-separated attribute notation, like local.object.attrname. In cases where a map might contain arbitrary user-specified keys, we recommend using only the square-bracket index notation (local.map["keyname"]).

The main difference is that dot notation requires key attributes to be valid identifiers. In contrast, the square-bracket notation works with any identifiers.

Upvotes: 3

Related Questions