Home > other >  Terraform - Increment a Variable in a for_each Loop
Terraform - Increment a Variable in a for_each Loop

Time:08-24

I am trying to figure out a way to add an incrementing number to resource.

Here is a snippet of my code. I would like to make the priority an incrementing number, instead of passing in a fixed number.

Current Code


resource "azurerm_firewall_network_rule_collection" "netrc" {
   for_each            = {for network_rule_collection in var.network_rule_collections: network_rule_collection.name => network_rule_collection}
   name                = "netrc-${each.key}"
   azure_firewall_name = var.afw_name
   resource_group_name = var.resource_group_name
   priority            = var.priority
   action              = each.value.action

Basically, I want to look something like this:

     priority            = (each.index *  10)   140

I tried to use each.key, but in this module, each.key is a string.

I also tried a counter but you cannot combine a counter with a for_each loop.

Any thoughts or suggestions?

CodePudding user response:

One way would be to pre-calculate the priorities:

locals {
  priorities = {
          for idx, network_rule_collection in var.network_rule_collections: 
              network_rule_collection.name => idx * 10   140
          }
}

then

resource "azurerm_firewall_network_rule_collection" "netrc" {
   for_each            = {for network_rule_collection in var.network_rule_collections: network_rule_collection.name => network_rule_collection}
   name                = "netrc-${each.key}"
   azure_firewall_name = var.afw_name
   resource_group_name = var.resource_group_name
   priority            = local.priorities[each.key]
   action              = each.value.action

CodePudding user response:

I think you can try to use index

priority = index(var.network_rule_collections, each.value)    140

PS: you will probably have to modify it its just as an example

  • Related