0

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)
Dan Carlton
  • 13
  • 1
  • 4

3 Answers3

4

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

Mark B
  • 183,023
  • 24
  • 297
  • 295
Vova Bilyachat
  • 18,765
  • 4
  • 55
  • 80
3

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
Marcin
  • 215,873
  • 14
  • 235
  • 294
0

I ended up using index as suggested.

priority            = (index(var.application_rule_collections, each.value) + 100)
Dan Carlton
  • 13
  • 1
  • 4