Omer Shliva
Omer Shliva

Reputation: 303

Terraform Azure provider - How do I add via terraform more than one key and/or secret for my key vault?

All the examples I saw provide 1 key and or q secret. Is there a way to add another one (or more)?

Upvotes: 1

Views: 2460

Answers (1)

Nancy Xiong
Nancy Xiong

Reputation: 28284

To add multiple keys or secrets for your key vault, you just need to add the resources azurerm_key_vault_key and azurerm_key_vault_secret multiple times.

It's recommended to create such resources in the loop. Terraform offers several different looping constructs, each intended to be used in a slightly different scenario:

  • count parameter: loop over resources.
  • for_each expressions: loop over resources and inline blocks within a resource.
  • for expressions: loop over lists and maps.

For example, create one or more keys and secrets with count parameters.

variable "key_lists" {
    type = list(string)
    default = ["key1","key2","key3"]
    
}

variable "secret_maps" {
    type = map(string)
    default = {
        "name1"= "value1"
        "aaa" = "111"
        "bbb" = "222"
    }
}

resource "azurerm_key_vault_key" "generated" {
  count        = length(var.key_lists)
  name         = var.key_lists[count.index]
  key_vault_id = azurerm_key_vault.example.id
  key_type     = "RSA"
  key_size     = 2048

  key_opts = [
    "decrypt",
    "encrypt",
    "sign",
    "unwrapKey",
    "verify",
    "wrapKey",
  ]
}

resource "azurerm_key_vault_secret" "example" {
  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.example.id

}

You could read this blog for more Terraform loop tips.

Upvotes: 2

Related Questions