Home:ALL Converter>Terraform: how to iterate over key-value pairs of map input and use Key as index

Terraform: how to iterate over key-value pairs of map input and use Key as index

Ask Time:2021-09-22T05:12:04         Author:Maki

Json Formatter

Here is the sample code:

    locals {
  helper_list = [
    {
    "keyname" = "app_primary_key"
    "name" = "AppPrimary--ReadWriteKey"
    "value" = "dont know yet"
    "env" = "user"
  },
    {
    "keyname" = "storage_account_key"
    "name" = "StorageAccount--ReadWriteConnectionString"
    "value" = "dont know yet"
    "env" = "app"
  },
  ]
}

resource "azurerm_key_vault_secret" "injections" {
    for_each = { for idx, v in local.helper_list: idx => v }
    name = each.value.name
    value = each.value.value
    key_vault_id = azurerm_key_vault.example.id
}

I followed this link to generate code above Terraform: how to iterate over key-value pairs of map input via json file Everything is good except for the index key.

When I do terraform plan this is the sample output:

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # azurerm_key_vault_secret.injections["0"] will be created
  + resource "azurerm_key_vault_secret" "injections" {
      + id             = (known after apply)
      + key_vault_id   = "/subscriptions/c-abe849261f68/resourceGroups/storageRG/providers/Microsoft.KeyVault/vaults/keyvaultinjection"
      + name           = "AppPrimary--ReadWriteKey"
      + value          = (sensitive value)
      + version        = (known after apply)
      + versionless_id = (known after apply)
    }

  # azurerm_key_vault_secret.injections["1"] will be created
  + resource "azurerm_key_vault_secret" "injections" {
      + id             = (known after apply)
      + key_vault_id   = "/subscriptions/c-abe849261f68/resourceGroups/storageRG/providers/Microsoft.KeyVault/vaults/keyvaultinjection"
      + name           = "StorageAccount--ReadWriteConnectionString"
      + value          = (sensitive value)
      + version        = (known after apply)
      + versionless_id = (known after apply)
    }

Plan: 2 to add, 0 to change, 0 to destroy.

What I need is to replace the index number to a keyname:

from

azurerm_key_vault_secret.injections["0"] azurerm_key_vault_secret.injections["1"]

to

azurerm_key_vault_secret.injections["app_primary_key"] azurerm_key_vault_secret.injections["storage_account_key"]

How can I tell it to use the keyname as index?? Thanks,

Author:Maki,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69275609/terraform-how-to-iterate-over-key-value-pairs-of-map-input-and-use-key-as-index
yy