Azure: Pass secrets to Azure Function via Key Vault


In a few of my previous posts (links at the end of this post), i created Kafka consumer with Python. The same can be done with Azure Function. in this example i show how to pass secrets to the Azure Function with Azure Key Vault.

Create Key Vault ‘kv-afkv-test’ in Azure Portal

Add secrets to the Key Vault (fakes for this example):

kafkaUsername2gCLqDmYTy
kafkaPasswordo}iEzGp-r7(KYsj
adlsConnectionString(ob34oveSWX^u:dX4TVF$#o+O8ODmP

Create and Publish Azure Function ‘af-afkv-test’ in Visual Studio 2019

The Microsoft documentation explains this process in details.

The function in this example just gets the values from Key Vault and the header of the message and prints them:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using System;
using System.Threading.Tasks;

namespace KeyVaultTest
{
    public static class KeyVaultTest
    {
        [FunctionName("KeyVaultTest")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)
        {
            string my_param = req.Headers["my_param"];

            // Read the secrets from Key Vault
            var kafka_username = Environment.GetEnvironmentVariable("kv_kafka_username", EnvironmentVariableTarget.Process);
            var kafka_password = Environment.GetEnvironmentVariable("kv_kafka_password", EnvironmentVariableTarget.Process);
            var adls_connection_string = Environment.GetEnvironmentVariable("kv_adls_connection_string", 
EnvironmentVariableTarget.Process);

            // Print the Key Vault and Header values
            return new OkObjectResult($"Kafka Username: {kafka_username}. Kafka Password: {kafka_password}. ADLS Connection String: {adls_connection_string}. my_param: {my_param}.");
        }
    }
}

Link the Key Vault and the Azure Function

Turn on the identity of the Azure Function:

Add Access Policy to the Key Vault:

Add the secrets to the function:

Paste in the function’s configuration:

Repeat the same copy/paste for ‘kafkaPassword’ and ‘adlsConnectionString’.

I added kv_adls_connection_string later.

Test the Azure Function

Related posts:

Keep it simple :-)

Leave a comment

Your email address will not be published. Required fields are marked *