Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (2023)

  • Code example

This example shows what to do when a KeyVault secret used by your Azure Function is "pulled over" or updated as part of normal security operations in your organizations.

Typically, organizations require that all secrets, keys, etc. are stored in KeyVault and activated on demand (in the event of a breach) or as part of a routine policy.

In these cases, your Azure function may also use these KeyVault secrets, specifically viaApplication Settings KeyVault References. In this scenario, the Azure Function needs to be instructed to "get" the secret value from KeyVault to get the updated value. This example shows how this can be done using a combination of Event Grid and Logic Apps.


  • When a KeyVault secret is updated, it emits anew secret versionsubscriber eventKey Vault event grid messages.
  • To send these messages, Logic Apps can subscribe to the KeyVault instance and even filter these message types.
  • Using Azure featuresKonfiguration REST-APIUpdating the KeyVault reference to point to the newly created secret version causes the host to reboot and reevaluate the application configuration. The new secret value is reflected at runtime of the function.

the implementation

In this example, we deploy two different instances of Application Insights. The instrumentation key from the first instance is placed in a KeyVault secret and the Azure function uses a KeyVault reference asAPPINSIGHTS_INSTRUMENTATIONKEYapplication settings. The Azure function hook is a timer trigger that runs approximately every five seconds and simply sends a message with the current UTC time to the Application Insights instance you are communicating with.

If we change the KeyVault secret for the second Application Insights instrumentation key, you'll see the event fire for your logic app, and your logic app will update the app settings in the Azure function. If you have the Live Streaming tab open for both Application Insights instances at the same time, you can see that one instance stops receiving messages while the other starts receiving them. This completes the sequence of events that are triggered simply by changing the secret value in the KeyVault.

How to implement the example

The implementation of this example usesTerraformar, and finishes with aContainers for Visual Studio code developmentto ensure you have everything you need to deploy. If this is your first time using a dev container, you should definitely give it a tryinstallation stepsto make sure you have everything you need.

1. Clone the repository

Clone this repository or your own fork to your local machine.

2. Open the workspace in its container

When prompted by Visual Studio Code, reopen the workspace in its development container. It may take a few minutes to install all of the container layers and get you to a bash prompt. Make sure Docker is running ;)

(Video) Automated secrets rotation in Azure Key Vault

3. Sign in to the Azure CLI

Without Terminal Bash from VS Code, output respregister azcommand andaz account set --subscription <your subscription ID>Commands to sign in to Azure and target the subscription you want to deploy the sample to.

4. Create a service principal

To do a fully hands-free implementation of Logic Apps and enable authentication to Event Grid without an OAuth flow, create a service principal in your Azure subscription by issuing theaz ad sp crear-a-rbacDomain. When this completes, you will get an output similar to the following:

{ "appId": "...", "displayName": "...", "name": "...", "password": "...", "tenant": "..." }

save theApp-IDmipasswordFields from this output to the next step

5. Implantation via Terraform

In the VSCode terminal window, issue the following commands:

cd terraformterraform apply -var prefix=<a unique prefix for you> -var sp_client_id=<top appId> -var sp_client_secret=<top password>

This will first generate any changes that will be made to your Azure subscription as part of the Terraform deployment and will wait for you to type 'yes' for the application to run. The following functions are implemented for this example:

  • A new resource group named "serverless-sample-" containing:
  • Logic Apps API connection to Event Grid
  • 2 instances of Application Insights
  • key safe
  • Service Plan for Consumer Applications
  • blue paper
  • logical application
  • Log Analysis Workspace
  • storage account

Enter yes and Terraform will work its magic.

6. Add the Application Insights KeyVault secret application configuration to the function app.

A Terraform output is a deployment script that you must run to finish configuring your function app application for Application Insights and to deploy your function code. Just run in VSCode's bash terminal window


Note: You may need to refresh the files in the explorer pane in VS Code to view the generated filedeploy_app.shpresent interraformarPasta.

vonterraformar/Directory where it is located after runningTerraforming-App.

Note: We cannot set the APPINSIGHTS_INSTRUMENTATIONKEY value via Terraform (yet) because all other app settings will be cleared when we deploy via the ARM template and there is a race condition between the function app and KeyVault when we try to embed them. Part of your function app implementation. In a production scenario, this would be done as part of the DevOps pipeline used to execute the Terraform plan. Similarly, the DevOps pipeline would build and deploy the function app.

7. Observe the result

the blue function

Go to the newly created Azure role in your portal. your name will be<prefix>-serverless-function-applicationValue you entered during Terraform deployment.

There are a few things to note:

(Video) Managing KeyVault Secrets in your JavaScript Azure Functions Code

  • The Function app has one function:timer5sek
    Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (1)
  • SobIdeassee the KeyVault Application Configuration Reference forAPPINSIGHTS_INSTRUMENTATIONKEY
    Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (2)
    Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (3)\

Note: It is important to note theLacka secret version identifier in the URL. By using this method, we always get the latest version of the secret, which allows for the desired behavior. Alternatively, you can create a process thatUpdateÖAPPINSIGHTS_INSTRUMENTATIONKEYApplication configuration with the URL coming as part of the Event Grid eventnew secret version.

watchConditionmark in reference; this tells you that the connection between your function app and KeyVault is good and you can extract the value from KeyVault as expected

  • In the IAM (Access Control) area of ​​your function app, you will find an entry for your logic app under Role assignments.

Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (4)

Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (5)

This is to give your logic app the necessary permissions to issue the soft restart request to your function app. Without it, the Azure REST API request made by Logic Apps gets a403 VERBOTENanswer.

Binding between Logic App and Azure Function is done through this part inprincipal.tf:

############################################## # ### ########################### Atribución de funciones############## ## ##### ######################################## ### ####### #########resource „azurerm_role_assignment“ „laToFunction“ { scope = azurerm_function_app.fxn.id role_definition_name = „Contributor of site web“ principal_id = azurerm_template_deployment.logicapp.outputs[“logicAppServicePrincipalId „] }

and the fact that your logic app was built with a managed service identity assigned as part of your ARM template deployment:

"Identity": { "Type": "SystemAssigned"},
  • The function app itself has a managed service identity:

Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (6)

Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (7)

This is part of configuring Azure's ability to use KeyVault credentials and allows KeyVault to restrict access to keys, secrets, and other things to specific identities. This access is enforced by this part of our Terraform implementation:

# Zugangspolitik für eine Azure-Funktion access_policy { object_id = azurerm_function_app.fxn.identity[0].principal_id tenant_id = data.azurerm_client_config.current.tenant_id secret_permissions = [ "get", ] }

thereby ensuring that even if someone submits a function code trying to change a value in the KeyVault, they cannot do so; The role only has "Get Secret" permission, which is all it needs.

The Logic App

Access the newly created logic app in your portal. your name will be<prefix> -serverless -laWo<prefix>is the value you enter during Terraform deployment.

(Video) Azure Functions Secure Secrets with Key Vault and Managed Identities | Azure Functions Next Steps

execution logic

CliqueLogic App Designeron the left side of the worksheet so you can see your logic app's design surface.

Clicking on the title bar of each block in your logic app expands the content to look like this:

Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (8)

Let's examine each logic block.

  1. This block connects theDeductionthe logic app. When we create this in Terraform via the ARM template implementation, it automatically requests an Event Grid subscription from the resource specified inresource nameand listens for the event type specified inEvent type element - 1. The logic app trigger handles the Event Grid signature validation event, allowing everything to communicate seamlessly.

  2. As part of our terraform, we'll populate the value of this logic app variable with the secret names we entered into KeyVault.

  3. We use this 'if' statement (also known as a conditional block) to say "If the subject of the event we received (which matches the name of the secret that thenew secret versionevent) is in ourkey to seearray variable" so that we can ignore changes to other secrets in the same vault.

  4. Here we use the Azure REST API to get the list of current app configurations for the function app because when we update we need to deploy thematApplication configuration values, not just modified ones.

  5. We analyze the answer ofTAKEcall and sendSETGo to Settings when using Logic Apps.definirPropiedadFunction to set the value ofAPPINSIGHTS_INSTRUMENTATIONKEYset to the new value.

You'll notice that both REST calls use identity-managed authentication using the identity we've assigned to the logic app and the user access role mentioned aboveSite contributorAccess to the function app. If this user access role is missing, this logic app block will fail.


The important part of setting up your logic app is that our Terraform implementation has assigned a managed identity to it. You can see this in itidentityLogic app area:

Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (9)

(Video) Secure your secrets with Azure Functions & KeyVault

key safe

Go to the newly created Key Vault in your portal. your name will be<prefix>-serverless-kvValue you entered during Terraform deployment.

The important Key Vault bits for this example are theeventsmiaccess policiesArea

Event Settings

Earlier you saw that the logic app's Event Grid trigger is configured to receive events from the Key Vault function. Deploying Logic App with this connector installed automatically creates the Event Grid subscription to Key Vault. Click on thateventsarea of ​​your KeyVault and look at theSubscriptionsArea near below:

Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (10)

Here you can see the logic app registered as a webhook receiver for KeyVault events.

access policies

In order for the function app to be able to read the values ​​of the Key Vault secrets, remember that our terraform gave it this permission in the Key Vault configuration. You can see this in the Access Policies section:

Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (11)

put everything together

If you are using Live Stream for the first instance of Application Insights (using the-Firstsuffix), see how the function logs messages every 5 seconds:

Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (12)

Switch to secondary Application Insights (using the-secondsuffix), you will likely see a screen like this:

Handling Rotation Changes of KeyVault Secrets Used by an Azure Function - Code Examples (13)

But if you take the instrumentation key from the child and update the KeyVault secretappinsights-instrumentationkeyThis shows the change in behavior when the event is propagated through the system and the function app is restarted to get the new KeyVault value.

(Video) AZ 204 — Azure Key Vault - Rotate Key


1. Integrate Azure functions with Azure KeyVault
(Gwyneth Peña-Siguenza)
2. Azure Key Vault Tutorial : Step-By-Step-Demo | Secret, Key, Certificates
3. Azure Key Vault Secrets within Azure DevOps Pipelines
(Houssem Dellai)
4. How to use Azure Key Vault + .NET Core easily | Secrets, Keys and Certificates - English
(Jose Async)
5. Azure Key Vault Deep Dive (AZ-500)
(John Savill's Technical Training)
6. Using Azure Key Vault Key Rotation Policies
(John Savill's Technical Training)
Top Articles
Latest Posts
Article information

Author: Nathanial Hackett

Last Updated: 03/24/2023

Views: 6152

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Nathanial Hackett

Birthday: 1997-10-09

Address: Apt. 935 264 Abshire Canyon, South Nerissachester, NM 01800

Phone: +9752624861224

Job: Forward Technology Assistant

Hobby: Listening to music, Shopping, Vacation, Baton twirling, Flower arranging, Blacksmithing, Do it yourself

Introduction: My name is Nathanial Hackett, I am a lovely, curious, smiling, lively, thoughtful, courageous, lively person who loves writing and wants to share my knowledge and understanding with you.