Set a secret within Azure KeyVault to App settings of Azure Functions


Summary

How to set Azure KeyVault’s secret to application setting of Azure Functions?

Steps

In first, turn on managed id. So, click Identityin your Azure Functions instance.

Toggle Status.

Next, open your Azure KeyVault instance. Click Access policies menu.

Click Add Access Policy link.

Select Secret Management in Configure from template (optional)field.

Control permissions in Secret permissions field. This example take minimum permission (get only).

Next, click None selected. Then, type your Azure Functions’s Object ID that is on Identity page of your Azure Functions instance to search filed. If you get your Azure Functions instance in search result, you click it. Finally, click Add button.

Click Save button.

Back to your Azure Functions instance. Then, click Configuration.

Click New application setting.

Type according to the reference syntax of Azure KeyVault in the input field.
The syntax is here:

This example is Variable1 that has aiueo365 in Value field.

I used syntax is here.

@Microsoft.KeyVault(VaultName=YOUR_VAULT_NAME;SecretName=YOUR_VAULT_SECRET_NAME)

To access the Variable1 from Azure Functions, use Environment.GetEnvironmentVariable as follows:

namespace Hoge
{
    public static class HogeApi
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string value = Environment.GetEnvironmentVariable("Variable1");
            string responseMessage = $"Variable1: {value}";

            return new OkObjectResult(responseMessage);
        }
    }
}

After deploying your code to Azure, it’s a good idea to run it in the Azure portal. You can check the value.

References