[NoBrainer] Define Azure Key Vault with embedded Access Policy in Terraform

azurerm (Azure resource manager) provider for terraform allows definition of Key Vault access policies either within the azurerm_key_vault resource via the access_policy block or by using the azurerm_key_vault_access_policy resource (using both methods for access policy management leads to conflicts).

The advantage of defining Key Vault access policies within the azurerm_key_vault resource over defining azurerm_key_vault_access_policy resource(s) is, that the access policy/policies are created together with the Key Vault which avoids definition of explicit dependencies to ensure that access policy is in place before accessing the Key Vault (i.e. if an access policy gets deployed for the service account that executes terraform so that a new secret can be created by terraform during terraform apply).

Such an Azure Key Vault resource definition with an embedded access policy looks as follows:

Terraform version: >= 1.1.0
azurerm version: ~> 3.9.0

data "azurerm_client_config" "current" {}

# Create Azure Key Vault
resource "azurerm_key_vault" "kv" {
  name                = "arbitrary-key-vault"
  location            = "switzerlandnorth"
  resource_group_name = "my-resource-group"
  tenant_id           = data.azurerm_client_config.current.tenant_id

  sku_name = "standard"

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

      secret_permissions = [
        "Get",
        "List",
        "Purge",
        "Recover",
        "Restore",
        "Set",
        "Delete"
      ]

      certificate_permissions = [
        "Get",
        "GetIssuers",
        "List",
        "ListIssuers",
        "Update",
        "Create",
        "SetIssuers",
        "ManageIssuers",
        "Delete"
      ]

      application_id = null
      key_permissions = null
      storage_permissions = null
    }
  ]
}

Important: all attributes of access_policy object(s) have to be set (in case of no value, set to null). Otherwise the following error gets thrown during terraform validate.

│ Inappropriate value for attribute "access_policy": element 0: attributes
│ "application_id", "key_permissions", and "storage_permissions" are
│ required.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Website Powered by WordPress.com.

Up ↑

%d bloggers like this: