0
0
AzureHow-ToBeginner · 4 min read

How to Use Azure Key Vault with Azure Functions Securely

To use Azure Key Vault with Azure Functions, enable a managed identity for your function app and grant it access to the Key Vault. Then, use the Azure SDK or configuration references to securely retrieve secrets inside your function code.
📐

Syntax

Here is the basic syntax to access Azure Key Vault secrets in an Azure Function using managed identity and environment variables.

  • AzureWebJobsStorage: Storage connection string for the function app.
  • KeyVaultName: The name of your Azure Key Vault.
  • SecretUri: The full URI of the secret in Key Vault.
  • Use Azure SDK client SecretClient with DefaultAzureCredential to authenticate.
python
import os
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient

key_vault_name = os.environ["KeyVaultName"]
secret_name = "MySecret"

KVUri = f"https://{key_vault_name}.vault.azure.net"

credential = DefaultAzureCredential()
client = SecretClient(vault_url=KVUri, credential=credential)

retrieved_secret = client.get_secret(secret_name)
print(f"Secret value: {retrieved_secret.value}")
💻

Example

This example shows a simple Azure Function in Python that reads a secret from Azure Key Vault using managed identity.

Make sure the function app has a system-assigned managed identity enabled and that identity has Get permission on the Key Vault secrets.

python
import logging
import os
import azure.functions as func
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    key_vault_name = os.environ.get('KeyVaultName')
    secret_name = 'MySecret'
    kv_uri = f'https://{key_vault_name}.vault.azure.net'

    credential = DefaultAzureCredential()
    client = SecretClient(vault_url=kv_uri, credential=credential)

    try:
        secret = client.get_secret(secret_name)
        return func.HttpResponse(f"Secret value: {secret.value}", status_code=200)
    except Exception as e:
        logging.error(f"Error retrieving secret: {e}")
        return func.HttpResponse("Failed to get secret", status_code=500)
Output
Secret value: your-secret-value
⚠️

Common Pitfalls

  • Managed identity not enabled: The function app must have a system-assigned or user-assigned managed identity enabled.
  • Access policies missing: The managed identity must have Get permission on Key Vault secrets.
  • Incorrect secret URI or name: Use the exact secret name and correct vault URI.
  • Local development: Use Azure CLI login or environment variables for credentials when testing locally.
python
## Wrong: No managed identity or permissions
# client = SecretClient(vault_url="https://myvault.vault.azure.net", credential=None)

## Right: Use DefaultAzureCredential with managed identity enabled
# credential = DefaultAzureCredential()
# client = SecretClient(vault_url="https://myvault.vault.azure.net", credential=credential)
📊

Quick Reference

StepDescription
Enable Managed IdentityTurn on system-assigned or user-assigned identity for your Azure Function app.
Set Key Vault Access PolicyGrant the managed identity 'Get' permission on secrets in your Key Vault.
Use Azure SDKIn your function code, use DefaultAzureCredential and SecretClient to fetch secrets.
Configure EnvironmentSet KeyVaultName and other settings as environment variables in the function app.
Local TestingUse Azure CLI login or environment variables to authenticate when running locally.

Key Takeaways

Enable managed identity on your Azure Function app to authenticate securely with Key Vault.
Grant the managed identity 'Get' permission on Key Vault secrets via access policies.
Use Azure SDK's DefaultAzureCredential and SecretClient to access secrets in your function code.
Set Key Vault name and secret names as environment variables for flexible configuration.
Test locally with Azure CLI authentication or environment variables before deploying.