Quickstart: Create an Azure key vault and key using Terraform
Azure Key Vault is a cloud service that provides a secure store for secrets, such as keys, passwords, and certificate. 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:
- Create a random value for the Azure resource group name using random_pet
- Create an Azure resource group using azurerm_resource_group
- Create a random value using random_string
- Create an Azure key vault using azurerm_key_vault
- Create an Azure key vault key using azurerm_key_vault_key
Prerequisites
Implement the Terraform code
Note
The sample code for this article is located in the Azure Terraform GitHub repo. You can view the log file containing the test results from current and previous versions of Terraform.
See more articles and sample code showing how to use Terraform to manage Azure resources
Create a directory in which to test and run the sample Terraform code and make it the current directory.
Create a file named
providers.tf
and insert the following code:terraform { required_version = ">=1.0" required_providers { azurerm = { source = "hashicorp/azurerm" version = "~>3.0" } random = { source = "hashicorp/random" version = "~>3.0" } } } provider "azurerm" { features {} }
Create a file named
main.tf
and insert the following code:resource "random_pet" "rg_name" { prefix = var.resource_group_name_prefix } resource "azurerm_resource_group" "rg" { name = random_pet.rg_name.id location = var.resource_group_location } data "azurerm_client_config" "current" {} resource "random_string" "azurerm_key_vault_name" { length = 13 lower = true numeric = false special = false upper = false } locals { current_user_id = coalesce(var.msi_id, data.azurerm_client_config.current.object_id) } resource "azurerm_key_vault" "vault" { name = coalesce(var.vault_name, "vault-${random_string.azurerm_key_vault_name.result}") location = azurerm_resource_group.rg.location resource_group_name = azurerm_resource_group.rg.name tenant_id = data.azurerm_client_config.current.tenant_id sku_name = var.sku_name soft_delete_retention_days = 7 access_policy { tenant_id = data.azurerm_client_config.current.tenant_id object_id = local.current_user_id key_permissions = var.key_permissions secret_permissions = var.secret_permissions } } resource "random_string" "azurerm_key_vault_key_name" { length = 13 lower = true numeric = false special = false upper = false } resource "azurerm_key_vault_key" "key" { name = coalesce(var.key_name, "key-${random_string.azurerm_key_vault_key_name.result}") key_vault_id = azurerm_key_vault.vault.id key_type = var.key_type key_size = var.key_size key_opts = var.key_ops rotation_policy { automatic { time_before_expiry = "P30D" } expire_after = "P90D" notify_before_expiry = "P29D" } }
Create a file named
variables.tf
and insert the following code:variable "resource_group_location" { type = string description = "Location for all resources." default = "eastus" } variable "resource_group_name_prefix" { type = string description = "Prefix of the resource group name that's combined with a random ID so name is unique in your Azure subscription." default = "rg" } variable "vault_name" { type = string description = "The name of the key vault to be created. The value will be randomly generated if blank." default = "" } variable "key_name" { type = string description = "The name of the key to be created. The value will be randomly generated if blank." default = "" } variable "sku_name" { type = string description = "The SKU of the vault to be created." default = "standard" validation { condition = contains(["standard", "premium"], var.sku_name) error_message = "The sku_name must be one of the following: standard, premium." } } variable "key_permissions" { type = list(string) description = "List of key permissions." default = ["List", "Create", "Delete", "Get", "Purge", "Recover", "Update", "GetRotationPolicy", "SetRotationPolicy"] } variable "secret_permissions" { type = list(string) description = "List of secret permissions." default = ["Set"] } variable "key_type" { description = "The JsonWebKeyType of the key to be created." default = "RSA" type = string validation { condition = contains(["EC", "EC-HSM", "RSA", "RSA-HSM"], var.key_type) error_message = "The key_type must be one of the following: EC, EC-HSM, RSA, RSA-HSM." } } variable "key_ops" { type = list(string) description = "The permitted JSON web key operations of the key to be created." default = ["decrypt", "encrypt", "sign", "unwrapKey", "verify", "wrapKey"] } variable "key_size" { type = number description = "The size in bits of the key to be created." default = 2048 } variable "msi_id" { type = string description = "The Managed Service Identity ID. If this value isn't null (the default), 'data.azurerm_client_config.current.object_id' will be set to this value." default = null }
Create a file named
outputs.tf
and insert the following code:output "resource_group_name" { value = azurerm_resource_group.rg.name } output "azurerm_key_vault_name" { value = azurerm_key_vault.vault.name } output "azurerm_key_vault_id" { value = azurerm_key_vault.vault.id }
Initialize Terraform
Run terraform init to initialize the Terraform deployment. This command downloads the Azure provider required to manage your Azure resources.
terraform init -upgrade
Key points:
- The
-upgrade
parameter upgrades the necessary provider plugins to the newest version that complies with the configuration's version constraints.
Create a Terraform execution plan
Run terraform plan to create an execution plan.
terraform plan -out main.tfplan
Key points:
- The
terraform plan
command creates an execution plan, but doesn't execute it. Instead, it determines what actions are necessary to create the configuration specified in your configuration files. This pattern allows you to verify whether the execution plan matches your expectations before making any changes to actual resources. - The optional
-out
parameter allows you to specify an output file for the plan. Using the-out
parameter ensures that the plan you reviewed is exactly what is applied.
Apply a Terraform execution plan
Run terraform apply to apply the execution plan to your cloud infrastructure.
terraform apply main.tfplan
Key points:
- The example
terraform apply
command assumes you previously ranterraform plan -out main.tfplan
. - If you specified a different filename for the
-out
parameter, use that same filename in the call toterraform apply
. - If you didn't use the
-out
parameter, callterraform apply
without any parameters.
Verify the results
Get the Azure key vault name.
azurerm_key_vault_name=$(terraform output -raw azurerm_key_vault_name)
Run az keyvault key list to display information about the key vault's keys.
az keyvault key list --vault-name $azurerm_key_vault_name
Clean up resources
When you no longer need the resources created via Terraform, do the following steps:
Run terraform plan and specify the
destroy
flag.terraform plan -destroy -out main.destroy.tfplan
Key points:
- The
terraform plan
command creates an execution plan, but doesn't execute it. Instead, it determines what actions are necessary to create the configuration specified in your configuration files. This pattern allows you to verify whether the execution plan matches your expectations before making any changes to actual resources. - The optional
-out
parameter allows you to specify an output file for the plan. Using the-out
parameter ensures that the plan you reviewed is exactly what is applied.
- The
Run terraform apply to apply the execution plan.
terraform apply main.destroy.tfplan
Troubleshoot Terraform on Azure
Troubleshoot common problems when using Terraform on Azure
Next steps
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for