How to reference Key Vault secrets from other subscriptions in Terraform

How to reference Key Vault secrets from other subscriptions in Terraform

One of the great things about working with Terraform is the ability to use data sources as a way to reference existing resources, like secrets from Azure Key Vault. However, working with Azure means that one might have to work with resources in more than one subscription at the time. The way to solve this is to set up two azurerm provider blocks, one for the context that you are working in and one for the other subscription, separating them by using the alias argument.

Here is an example of how it works in practice.

terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "2.56.0"
    }
  }
}

# Default provider block, note that there is no alias set here
provider "azurerm" {
  features {}

  subscription_id = "00000000-0000-0000-0000-000000000000"
}

# Provider for the "management" subscription where we have our key vault
provider "azurerm" {
  features {}

  alias           = "management"
  subscription_id = "00000000-0000-0000-0000-000000000000"
}

# Data source, using the aliased provider to get the right context
data "azurerm_key_vault_secret" "example" {
  provider = azurerm.management
  
  name         = "administrator"
  key_vault_id = data.azurerm_key_vault.existing.id
}

# How to output the secret
output "secret_value" {
  value = data.azurerm_key_vault_secret.example.value
}

Obviously, this isn't limited to just key vault secrets but applies to everything you might want to do within the context of a different subscription.

Any questions about Terraform, feel free to ask me through Twitter and I'll create a blog post about it.

Show Comments