Radhika
Radhika

Reputation: 27

How to add multiple secrets to azure key vault using terraform

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.

module "keyvault_secret" {

  source = "../../modules/keyvault_secret"

  count               = length(var.secrets)
  keyVaultSecretName  = keys(var.secrets)[count.index]
  keyVaultSecretValue = values(var.secrets)[count.index]
  keyVaultId          = data.azurerm_key_vault.key_vault.id
}

variables: 
variable "secrets" {
  type = map(string)
}
 
variables.tfvars:

secrets  = $(secrets)

in YAML pipeline:

displayName: DEV
    variables: 
      - group: 'Environment - Dev' 
      - name: secrets
        value:  '{"testAPIKey1" = $(testAPIKey1) , "testAPIKey2" = $(testAPIKey2) }' 

i have defined those key values in above variable group - Environment - Dev

This is what the error throws

Expected a closing parenthesis to terminate the expression. ##[error]Terraform command 'plan' failed with exit code '1'.: Unbalanced parentheses ##[error] Error: Unbalanced parentheses

Upvotes: 0

Views: 2474

Answers (1)

Niclas
Niclas

Reputation: 1262

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
}

Upvotes: 2

Related Questions