Referencing Azure Key Vault secrets in Terraform

A quick blog post on how to store your secrets in Azure Key Vault and referencing them within your Terraform configurations.

The Azure Key Vault and secrets

Azure key Vault and secrets is certainly the recommended approach for storing secrets in Azure!

Benefits include:

  • Azures recommendation service for secret and even certificate management
  • Secret rotation with base
  • Secure access permissions can be set on the Key Vault and secrets
  • Managed Identities can be configured for access

Now the Terraform

I am assuming you have used Terraform previously; rather than attempting to create and store secrets in variables etc; I will show how you can reference secret values from within Azure Key Vault. This will be done by using data resources

A data resource in Terraform in short, allows you to reference specific values of an Azure resource without modifying or applying a change to the resource. They are great to use within your Terraform configurations!

I have previously created a Key Vault: thomasthorntoncloudkv and secret: secret1

Firstly I will reference the Azure Key Vault in a data block

data "azurerm_key_vault" "thomasthorntoncloudkv" {
  name                = "thomasthorntoncloudkv"
  resource_group_name = "thomasthorntoncloud"
}

Next, the Key Vault secret – notice the reference to the Key Vault ID? Referenced from the above data block

data "azurerm_key_vault_secret" "secret1" {
  name         = "secret1"
  key_vault_id = data.azurerm_key_vault.thomasthorntoncloudkv.id
}

Now to use this secret1 value – I will be randomly referencing as resource group name, just to show how to reference Azure Key Vault secrets within your Terraform configuration. (Ensure your user / service principal / managed identity has the correct access permissions to the secret or you will be faced with permission error )

resource "azurerm_resource_group" "main" {
  name     = data.azurerm_key_vault_secret.secret1.value
  location = "West Europe"
}

Simple, but effective – I like it 🙂

GitHub repository here

7 comments

  1. Question? How did you authenticate to the AzureRM provider in the first place? what about that SP provider secret? Any thoughts?

Leave a Reply