DEV Community

Roberth Strand
Roberth Strand

Posted on • Originally published at robstr.dev on

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
}


Enter fullscreen mode Exit fullscreen mode

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.

Developer-first embedded dashboards

Developer-first embedded dashboards

Embed in minutes, load in milliseconds, extend infinitely. Import any chart, connect to any database, embed anywhere. Scale elegantly, monitor effortlessly, CI/CD & version control.

Get early access

Top comments (0)

AWS Q Developer image

What is MCP? No, Really!

See MCP in action and explore how MCP decouples agents from servers, allowing for seamless integration with cloud-based resources and remote functionality.

Watch the demo

👋 Kindness is contagious

Discover fresh viewpoints in this insightful post, supported by our vibrant DEV Community. Every developer’s experience matters—add your thoughts and help us grow together.

A simple “thank you” can uplift the author and spark new discussions—leave yours below!

On DEV, knowledge-sharing connects us and drives innovation. Found this useful? A quick note of appreciation makes a real impact.

Okay