简体   繁体   中英

Terraform - Increment a Variable in a for_each Loop

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?

EDIT

I ended up using index as suggested below.

  priority            = (index(var.application_rule_collections, each.value) + 100)

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

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

I ended up using index as suggested.

priority            = (index(var.application_rule_collections, each.value) + 100)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM