skip to Main Content

Azure Key Vault name is globally unique and is all we need to connect to it when using Azure CLI, for example:

az keyvault secret set --name dummy --vault-name $kv_name --value XYZ

Here we set a secret in an Azure key vault given by just its name.

However, the terraform azurerm_key_vault data source requires both the key vault and the resource group name.

This seems to be a redundant requirement. Is it possible to connect to the AKV in terraform without knowing the resource group? Just by the key vault name?

2

Answers


  1. No, it’s not possible to connect to an existing Azure Key Vault in Terraform without providing the resource group name. The resource group is a required parameter in the azurerm_key_vault data source because the key vault name alone is not globally unique in Azure. There could be multiple key vaults with the same name in different resource groups, which is why Terraform needs to know which resource group to look in.

    If you only have the key vault name, you can use the Azure CLI or Azure PowerShell to retrieve the resource group name. For example, in Azure CLI you can use the following command:

    az keyvault show --name <key_vault_name> --query "resourceGroup"
    

    This will return the name of the resource group that the key vault is in, which you can then use in your Terraform code. I hope my answer was helpful 🙂

    Login or Signup to reply.
  2. Yes you can but it’s a bit unconventional. There is a data source called azurerm resources. This will let you look up any existing resource using its name, resource group, resource type, or tags.

    Most simply you would only need the name of your KeyVault and the resource type: Microsoft.KeyVault.

    The code would look like this :

    data "azurerm_resources" "keyvault" {
      name="kv-too-many-secrets"
      type ="Microsoft.KeyVault/vaults"
    }
    
    locals {
     keyvault_rg = split(data.azurerm_resources.id, "/")[
    }
    
    data "azurerm_key_vault" "example" {
      name                = "kv-too-many-secrets"
      resource_group_name = local.keyvault_rg
    }
    

    Please forgive me if my string formatting is off or the index is wrong but the idea is that the resource group name is embedded in the resource ID of our keyvault and we can extract it from there.

    Here is a video explaining the approach.

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