Home > Enterprise >  How to add multiple secrets to azure key vault using terraform
How to add multiple secrets to azure key vault using terraform

Time:02-01

I have seen examples to add one secret (or) key to azure key vault. but I have a requirement now to add multiple secrets to azure key vault using terraform.

How can I achieve that? Can anyone suggest?

Thank You.

I tried to add resource for each secret. added multiple resources like below. but that did not work.

resource "azurerm_key_vault_secret" "example1" {
  name         = "secret-sauce1"
  value        = "szechuan1"
  key_vault_id = azurerm_key_vault.example.id

  tags = {
    environment = "Production"
  }
} 

CodePudding user response:

You need to run it in a loop. See this link for more info about Terraform loops (for each or count):
https://www.cloudbolt.io/terraform-best-practices/terraform-for-loops/

Untested but something like this:

#Reference AKV in data block
data "azurerm_key_vault" "kvexample" {
  name = "mykeyvault"
  resource_group_name = "some-resource-group"
}

variable "secret_maps" {
    type = map(string)
    default = {
        "name1"= "value1"
        "name2" = "value2"
        "name3" = "value3"
    }
}

# Count loop
resource "azurerm_key_vault_secret" "kvsecrettest" {
  count = length(var.secret_maps)
  name         = keys(var.secret_maps)[count.index]
  value        = values(var.secret_maps)[count.index]
  key_vault_id = azurerm_key_vault.kvexample.id
}

#----------------- Or use For Each instead of Count
# For Each loop
resource "azurerm_key_vault_secret" "kvsecrettest" {
  for_each = var.secret_maps
  name          = each.key
  value         = each.value
  key_vault_id  = azurerm_key_vault.kvexample.id
}
  • Related