Azure QueueTriggered Function app dotnet-isolated input binding from keyvault

1.7k views Asked by At

I am trying to connect my function app to keyvault and get queue name and connection secrets. This was working well with .netcore3.1 app using the ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder) method in FunctionStartup.

After upgrading to .net5 dotnet-isolated, the bindings does not work. I configured azurekeyvault in Program.cs but still it does not pick from keyvault.

QueueFunction

 public static void Run([QueueTrigger("%QueueName%", Connection = "QueueConnection")] string message, string id)
    

Startup.cs (.netcore3.1)- working

  public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
    {
        var azureKeyVaultURL = Environment.GetEnvironmentVariable("AzureKeyVaultURL");
        var azureKeyVaultADAppID = Environment.GetEnvironmentVariable("AzureKeyVaultMIAppID");


        builder.ConfigurationBuilder
                    .SetBasePath(Environment.CurrentDirectory)
                    .AddAzureKeyVault(new Uri(azureKeyVaultURL), new ManagedIdentityCredential(azureKeyVaultADAppID))
                    .AddEnvironmentVariables()
                .Build();
    }

Program.cs (.net5)- Not working

var host = new HostBuilder()
            .ConfigureFunctionsWorkerDefaults()
            .ConfigureAppConfiguration(config =>{
                 var azureKeyVaultURL = Environment.GetEnvironmentVariable("AzureKeyVaultURL");
                var azureKeyVaultADAppID = Environment.GetEnvironmentVariable("AzureKeyVaultMIAppID");

                config
                   .SetBasePath(Environment.CurrentDirectory)
                   .AddAzureKeyVault(new Uri(azureKeyVaultURL), new ManagedIdentityCredential(azureKeyVaultADAppID))
                   .AddEnvironmentVariables()
                .Build();
            })
2

There are 2 answers

5
Doris Lv On

Here is the HostBuilder pipeline sample from official document, notice that the Build function:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(s =>
    {
        s.AddSingleton<IHttpResponderService, DefaultHttpResponderService>();
    })
    .Build();
1
Boris Lipschitz On

you need to use another overload of ConfigureAppConfiguration method:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureAppConfiguration((hostBuilder, config) =>
    {
        if (hostBuilder.HostingEnvironment.IsProduction())
        {
            var builtConfig = config.Build();
            var secretClient = new SecretClient(new Uri($"https://{builtConfig["KeyVaultName"]}.vault.azure.net/"), new DefaultAzureCredential());
            config.AddAzureKeyVault(secretClient, new KeyVaultSecretManager());
        }
    })
    .Build();