Skip to main content

Create reference to Azure Key Vault content from function code

Requirements: Basic Azure Function knowledge and access to an Azure Key Vault & Azure Function.

This topic shows you how to work with secrets from Azure Key Vault in your Azure Functions code without requiring any code changes. Azure Key VaultĀ is a service that provides centralized secrets management, with full control over access policies and audit history. This article uses managed identities to access other resources.

Add your secret to Azure Key Vault

First, the secret must be created in the Azure Key Vault. For this, an Azure Key Vault must exist and the permissions to create a new item must be available. There you can insert the secret that you want to use later in the code.

image.png

Create managed identity of function

To be able to display the secret in the Function code, you have to activate the Managed Identity in the Function App. You can do this via the menu item "Identity" and then switch the status to "On" under "System assigned". Don't forget to save your selection.

image.png

Create access policy

Then you can go back to the Key Vault and create a new access policy under "Access policies" -> "Create".

image.png

There you have to select the desired permissions. The Azure Function then connects to the Key Vault with these permissions. To read only the secret content, only the "Get" permission under "Secret permissions" is used.

image.png

At the end you have to select the managed identity of the Azure Function and save the access policy.

Create environment variable link

Here you first enter the name of the variable that you want to address in the code. Under "Value" you have to insert the following content and complete it with your values:

@Microsoft.KeyVault(SecretUri=https://<keyvaultname>.vault.azure.net/secrets/<secretname>

image.png

Get environment variable content

Then you can read the variable in your function code using the environment as follows:

$env:<secretname>

image.png

Thus, the values can be stored securely without all user accounts needing authorization.