skip to Main Content

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)

3

Answers


  1. Chosen as BEST ANSWER

    I ended up using index as suggested.

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

  2. 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
    
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search