Use Azure Key Vault to Manage Terraform Secret Variables

Most of the time, we keep secrets in a .tfvars file in Terraform. That is fine. But we can make security even better if we move the secrets into a Vault instead.
In this blog, we will use Azure Key Vault to manage Terraform secret variables.
(Want to know why we use Azure Key Vault? Read this: Why use Azure Key Vault?)
Right now, I have these Azure Resources. I created them with Terraform.

If you look at the Terraform code, you will see that the Web App uses a Terraform variable with sensitive data (a secret). The value of this variable lives in the terraform.tfvars file.

Here is what I want. I will not keep the secret in terraform.tfvars anymore. I will keep it in Azure Key Vault instead.
So let’s create an Azure Key Vault first.
I will create it in the Azure Portal. If you want to create it with Terraform, that is fine too. No problem.

Fill in the form. Choose any settings you like.

Mine looks like this. Click Create.

It is created.

To manage secrets in Azure Key Vault, we need the “Key Vault Secrets Officer” role.
So let’s add the role.
Open the Azure Key Vault we just created. Then click Add role assignment.

Search for the role named Key Vault Secrets Officer > click it > click Next

Click Select members > search for your own name (or the person you want to give access to) and click it > click Select > click Review + assign

Read the settings one more time. If everything looks right, click Review + assign.

Done. Now I can manage Azure Key Vault secrets.
Let’s create a secret.
Go to the Secrets tab > click Generate/Import

Enter a name and a value, then click Create.

Great! The secret is created.

Next, we will change the Terraform code to read the secret from Azure Key Vault.
To get the secret value, we will use the azurerm_key_vault_secret data block (https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/data-sources/key_vault_secret)

I ran terraform plan to test it. I got No Changes, just what I wanted. Awesome! 🎉
That’s all! Now we can use Azure Key Vault to manage Terraform secret variables.
I keep the source code for this blog at https://github.com/ChaiyoKung/azure-key-vault-secret-tfvars. Feel free to take a look. If you give it a star, I will be happy. ⭐
Thank you!