Azure Key Vault Terraform Deployment Patterns for Secrets and Keys

Introduction

Azure Key Vault is a cloud service that provides a secure store for secrets, such as keys, passwords, and certificates. This article focuses on the process of deploying a Terraform file to create a key vault and a key. Terraform enables the definition, preview, and deployment of cloud infrastructure. Using Terraform, you create configuration files using HCL syntax. The HCL syntax allows you to specify the cloud provider - such as Azure - and the elements that make up your cloud infrastructure. After you create your configuration files, you create an execution plan that allows you to preview your infrastructure changes before they're deployed. Once you verify the changes, you apply the execution plan to deploy the infrastructure.

In this article, you learn how to:
Prerequisites
Create a directory to test and run the sample Terraform code

Azure Key Vault is a Microsoft Azure resource that securely stores and manages sensitive data, including secrets, encryption keys, and certificates, it features soft deletion of secrets, renovation of certificates, and security features including Role-Based Access Control (RBAC) and private network access.

Managing secrets, certificates, and keys securely is a critical part of any cloud infrastructure. Azure Key Vault is Microsoft’s go-to solution for secure key management, and in this blog, we’ll walk through how to deploy it using Terraform.

What is Azure Key Vault?
Azure Key Vault is a handy tool for securely storing sensitive information like secrets, encryption keys, and certificates. Centralising the storage of your sensitive data makes it easier to manage. Plus, it gives you fine-grained control over who can access what, helping you maintain strong security practices.

It’s never ideal to embed secrets into your code or configuration files, so storing them in Azure Key Vault and then calling the information as and when needed is the preferred solution.

Azure Key Vault offers a lot of features that can improve your security posture, soft delete, purge protection, and integration with Azure role based access control (RBAC) and managed identities

It can also manage key rotation policies and work with hardware security modules (HSMs) for extra protection.

There are two SKUs available with Azure Key Vault, Standard and Premium. The standard SKU supports most use cases, while premium adds support for HSM-backed keys and advanced scenarios. You can view full pricing details on the Azure Pricing page.

Key Vault is a foundational piece of any secure Azure architecture. Getting it right in Terraform means your secrets management, encryption key storage, and certificate lifecycle are all reproducible and auditable from the start.

Terraform Prerequisites and Environment Setup

Before diving into the code, make sure you’ve got the following set up:

  • Terraform installed (version 1.10.0 or later)
  • An active Azure subscription
  • The Azure CLI installed and logged in
  • A service principal or user account with sufficient permissions to deploy resources
  • Familiarity with basic Terraform concepts (providers, resources, variables)

The prerequisite list sets the operational baseline for any reproducible Key Vault deployment. Without Terraform 1.10.0 or later, provider constraints and language features used in the reference configurations may fail to parse. The active Azure subscription is the billing and identity boundary where the Key Vault resource will be created. Azure CLI login establishes the authentication context that Terraform uses to obtain the current client configuration and to validate subscription and tenant IDs.

The service principal or user account with sufficient permissions directly impacts the ability to create resource groups, Key Vaults, and role assignments. Insufficient permissions result in authorization failures during terraform apply. Familiarity with providers, resources, and variables reduces misconfiguration risk when mapping HCL to Azure API objects.

You need:

Your subscription_id, this is a GUID and you can get it using one of the following ways:Using Azure CLI:
az account subscription list

Using the Azure Portal.

Your tenant_id, this is a GUID and you can get it using one of the following ways:Using Azure CLI:
az account tenant list

Using the Azure Portal in the column Directory ID.

The subscriptionid and tenantid are required for provider authentication. The subscriptionid is a GUID that identifies the billing scope. The tenantid is a GUID that identifies the Azure Active Directory tenant. Both are retrieved via Azure CLI or Azure Portal. Hardcoding these values in the provider block couples the configuration to a specific tenant and subscription.

Provider Configuration and Version Constraints

The Terraform configuration starts by declaring the Terraform version and required providers.

terraform { required_version = ">= 1.10.0" required_providers { azurerm = { source = "hashicorp/azurerm" version = ">= 3.71, < 5.0.0" } random = { source = "hashicorp/random" version = ">= 3.5.1, < 4.0.0" } azapi = { source = "Azure/azapi" version = ">= 2.2.0, < 3.0.0" } } }

provider "azapi" {

Configuration options

}
provider "azurerm" {
features {}
subscription_id = "XXXX-XXXX-XXXX-XXXX"
}

We're using:
- azurerm to deploy Azure resources
- random to randomly select a region
- azapi to support the modules we are using

You must configure the providers with your Azure subscription details. The subscription_id in the azurerm provider should be updated with your actual ID.

A second provider declaration pattern is also shown in the reference material.

```
terraform {
required_providers {
azurerm: {
source : "hashicorp/azurerm"
version: "4.11.0"
}
}
}
provider "azurerm" {

Configuration options

features {
keyvault {
purge
softdeleteondestroy : true
recover
softdeletedkeyvaults: true
}
}
subscription
id: "a838fdd3-56b8-4508-93db-9611367b3aee" # Put your 'subscriptionid' here
tenant
id: "c4421ca3-5bd8-472b-99c4-6b231540eac1" # Put your 'tenantid' here
}
data "azurerm
client_config" "current" {}
```

In this file you declare the Terraform provider.

The provider block defines how Terraform authenticates to Azure and how Key Vault lifecycle behaviors are handled. The features block with keyvault purgesoftdeleteondestroy and recoversoftdeletedkeyvaults controls soft-delete behavior on destroy. Setting purgesoftdeleteondestroy to true ensures that soft-deleted vaults are purged when the resource is destroyed, which has irreversible impact on recoverability. The data source azurermclient_config current captures the current tenant ID for use in resource definitions.

Version constraints such as >= 3.71, < 5.0.0 for azurerm and >= 3.5.1, < 4.0.0 for random provide stability. The constraints prevent unexpected breaking changes from provider upgrades while allowing patch updates.

Resource Group and Key Vault Resource Definition

The Terraform configuration will:

  • Randomly pick a region from a list
  • Create a new Azure resource group
  • Deploy an Azure Key Vault instance into that resource group
  • Assign an access policy to the current user or service principal running the code

The resource group creation is defined as:

resource "azurerm_resource_group" "secrets_rg" { name : "secrets" location: "westus3" }

The Key Vault resource definition is defined as:

resource "azurerm_key_vault" "secrets_keyvault" { tenant_id : data.azurerm_client_config.current.tenant_id resource_group_name: azurerm_resource_group.secrets_rg.name name : "secrets" location: azurerm_resource_group.secrets_rg.location enable_rbac_authorization : true enabled_for_deployment : false enabled_for_disk_encryption :

The resource group name secrets and location westus3 anchor the Key Vault in a specific region. Using a dedicated resource group isolates secrets management resources from other workloads. The location is propagated from the resource group to the Key Vault, ensuring co-location.

The Key Vault resource uses tenantid from data source azurermclientconfig.current.tenantid to bind the vault to the correct Azure AD tenant. The name secrets is used for both the resource group and the vault in the example. enablerbacauthorization set to true opts the vault into the newer RBAC authorization model. enabledfordeployment set to false prevents the vault from being used for deployment authentication. enabledfordisk_encryption is referenced but truncated in the source.

RBAC Authorization versus Access Policies

They are defined per-vault and offer granular permissions on keys, secrets, and certificates. Each vault supports up to 1024 access policies.

RBAC authorization is the newer model. It uses Azure role assignments at the vault, resource group, or subscription level. Built-in roles like Key Vault Secrets User and Key Vault Administrator simplify management and work consistently with the rest of Azure RBAC.

For new deployments, RBAC is the recommended approach. It centralizes access control and integrates with Privileged Identity Management (PIM) for just-in-time access.

The access policy model defines per-vault policies with granular permissions on keys, secrets, and certificates. Each vault supports up to 1024 access policies. The limit of 1024 access policies constrains the scale of user-based access control within a single vault.

RBAC authorization is the newer model. It uses Azure role assignments at the vault, resource group, or subscription level. Built-in roles like Key Vault Secrets User and Key Vault Administrator simplify management and work consistently with the rest of Azure RBAC.

For new deployments, RBAC is the recommended approach. It centralizes access control and integrates with Privileged Identity Management (PIM) for just-in-time access.

The shift from access policies to RBAC impacts operational governance. RBAC centralizes access control in Azure role assignments and integrates with Privileged Identity Management for just-in-time access. RBAC also works consistently with the rest of Azure RBAC, reducing the need for vault-specific policy learning.

In this post, I will show you how to use Terraform to create an Azure Key Vault and populate it adding some secrets

Additionally, I will show you how to use Terraform to assign a user a role so that they can create secrets in Azure Key Vault.

Create an Azure Key Vault using Terraform
What do you need
Your subscription_id, this is a GUID and you can get it using one of the following ways:Using Azure CLI:
az account subscription list

Using the Azure Portal.
Your tenant_id, this is a GUID and you can get it using one of the following ways:Using Azure CLI:
az account tenant list

Using the Azure Portal in the column Directory ID.

The post demonstrates the workflow of creating a vault with RBAC and assigning a user a role to create secrets. The role assignment enables least privilege access for secret creation without granting full vault administration.

Key Vault Features and SKU Options

Azure Key Vault is a Microsoft Azure resource that securely stores and manages sensitive data, including secrets, encryption keys, and certificates, it features soft deletion of secrets, renovation of certificates, and security features including Role-Based Access Control (RBAC) and private network access.

Soft delete is a safety net that prevents accidental permanent loss. Soft delete of secrets and purge protection are referenced as features that improve security posture.

Azure Key Vault offers a lot of features that can improve your security posture, soft delete, purge protection, and integration with Azure role based access control (RBAC) and managed identities

It can also manage key rotation policies and work with hardware security modules (HSMs) for extra protection.

There are two SKUs available with Azure Key Vault, Standard and Premium. The standard SKU supports most use cases, while premium adds support for HSM-backed keys and advanced scenarios. You can view full pricing details on the Azure Pricing page.

The SKU choice affects cost and capability. Standard SKU supports most use cases. Premium adds support for HSM-backed keys and advanced scenarios. HSM-backed keys provide FIPS 140-2 Level 3 compliance for key management.

Deployment Workflow and Verification

Terraform enables the definition, preview, and deployment of cloud infrastructure. Using Terraform, you create configuration files using HCL syntax. The HCL syntax allows you to specify the cloud provider - such as Azure - and the elements that make up your cloud infrastructure. After you create your configuration files, you create an execution plan that allows you to preview your infrastructure changes before they're deployed. Once you verify the changes, you apply the execution plan to deploy the infrastructure.

The execution plan preview reduces risk by showing exactly what resources will be created, modified, or destroyed. Verification before apply prevents unintended changes to production Key Vaults.

You can also verify that the access policy has been applied by reviewing your permissions in the Key Vault settings.

Wrapping Up
Deploying Azure Key Vault with Terraform is a clean, repeatable way to manage your secure resources. With just a few lines of code, you can automate what would normally take several steps in the Azure Portal.

The repeatability of Terraform reduces manual errors in portal-based creation. Automation via HCL makes Key Vault deployment auditable and version controlled.

Configuration Summary Table

Component Example Value Purpose
Provider azurerm Deploy Azure resources
Provider random Randomly select a region
Provider azapi Support modules
Resource Group secrets Container for Key Vault
Location westus3 Azure region
Key Vault Name secrets Vault identifier
enablerbacauthorization true Use RBAC model
SKU Standard / Premium Standard for most use, Premium for HSM
Soft Delete enabled Prevent immediate loss

The table summarizes the core configuration elements referenced across the sources. The values illustrate a minimal reproducible configuration.

Practical Terraform File Structure

The reference material shows a main.tf file for provider declaration and a keyvault.tf file for resources.

Terraform files
main.tf
```
terraform {
required_providers {
azurerm: {
source : "hashicorp/azurerm"
version: "4.11.0"
}
}
}
provider "azurerm" {

Configuration options

features {
keyvault {
purge
softdeleteondestroy : true
recover
softdeletedkeyvaults: true
}
}
subscription
id: "a838fdd3-56b8-4508-93db-9611367b3aee" # Put your 'subscriptionid' here
tenant
id: "c4421ca3-5bd8-472b-99c4-6b231540eac1" # Put your 'tenantid' here
}
data "azurerm
client_config" "current" {}
```

keyvault.tf
resource "azurerm_resource_group" "secrets_rg" { name : "secrets" location: "westus3" } resource "azurerm_key_vault" "secrets_keyvault" { tenant_id : data.azurerm_client_config.current.tenant_id resource_group_name: azurerm_resource_group.secrets_rg.name name : "secrets" location: azurerm_resource_group.secrets_rg.location enable_rbac_authorization : true enabled_for_deployment : false enabled_for_disk_encryption :

Separating provider configuration from resource definitions improves modularity. The main.tf file centralizes authentication and provider features. The keyvault.tf file defines the resource group and Key Vault.

Conclusion

Key Vault is a foundational piece of any secure Azure architecture. Getting it right in Terraform means your secrets management, encryption key storage, and certificate lifecycle are all reproducible and auditable from the start.

The reference facts consistently point to RBAC as the recommended authorization model for new deployments. The combination of Terraform version constraints, provider configuration with subscription and tenant IDs, resource group creation, and Key Vault resource definition with enablerbacauthorization true forms a baseline pattern that can be extended to populate secrets, assign roles, and enable soft delete and purge protection.

The Standard versus Premium SKU decision hinges on HSM requirements and compliance. The soft delete and purge protection features provide recovery safety nets. The use of Terraform execution plans provides preview safety before deployment.

Deploying Azure Key Vault with Terraform is a clean, repeatable way to manage your secure resources. With just a few lines of code, you can automate what would normally take several steps in the Azure Portal.

The material demonstrates that Terraform configuration for Azure Key Vault requires provider setup, subscription and tenant identification, resource group definition, vault definition with RBAC enabled, and optional role assignments for secret creation. The pattern is repeatable across environments and supports centralized access control via Azure RBAC and PIM integration.

Sources

  1. Microsoft Learn
  2. Juan Orbegoso
  3. Techie Lass
  4. OneUptime

Related Posts