Deploy an Azure Key Vault with Terraform

In this blog post, I will show you how to create an Azure Key Vault on Microsoft Azure with Terraform code.

Key Vault Secret Store

Azure Key Vault is a secret store service that allows us to store passwords, certificates and keys using API requests, Terraform, PowerShell and Azure CLI.

I will create a standard Azure Key Vault with a 7 days soft delete retention in the following Terraform configuration.

Configuration

The configuration will also give the person that runs the code to get permissions to retrieve secrets. It is also important to note that the vault name needs to be globally unique across all the Azure services.

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

provider "azurerm" {
  features {
    key_vault {
      purge_soft_delete_on_destroy = true
    }
  }
}

data "azurerm_client_config" "current" {}

resource "azurerm_resource_group" "rg" {
  name     = "linux"
  location = "westus"
}

resource "azurerm_key_vault" "azvault" {
  name                        = "ntwkeyvault1"
  location                    = azurerm_resource_group.rg.location
  resource_group_name         = azurerm_resource_group.rg.name
  enabled_for_disk_encryption = true
  tenant_id                   = data.azurerm_client_config.current.tenant_id
  soft_delete_retention_days  = 7
  purge_protection_enabled    = false

  sku_name = "standard"

  access_policy {
    tenant_id = data.azurerm_client_config.current.tenant_id
    object_id = data.azurerm_client_config.current.object_id

    key_permissions = [
      "get",
    ]

    secret_permissions = [
      "get",
    ]

    storage_permissions = [
      "get",
    ]
  }
}

Posted

in

by