Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Functions, how to have multiple .json config files

So I have written an azure function that works locally just fine. I believe this is down to having the local.setting.json file. But when I publish it to azure the function does not work as it can't find the settings values that I had defined. Coming from a web app and console driven approach, we would have different config files that would be associated with each environment. How can I get this to work so I can have multiple settings.json files, e.g. one for dev, stag and prod environments? The end result is to get this deployed with octopus deploy, but at this point, if I cant even get it working with a publish then there is no chance of doing this.

I'm rather confused why this information is not easily available, as would presume it is a common thing to do?

like image 889
Andrew Avatar asked Jun 05 '19 08:06

Andrew


1 Answers

I would love to see functions support environment specific settings in the same way as asp.net core or console apps. In the meantime I am using below code, which is somewhat hacky (see comments).

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        // Get the path to the folder that has appsettings.json and other files.
        // Note that there is a better way to get this path: ExecutionContext.FunctionAppDirectory when running inside a function. But we don't have access to the ExecutionContext here.
        // Functions team should improve this in future. It will hopefully expose FunctionAppDirectory through some other way or env variable.
        string basePath = IsDevelopmentEnvironment() ?
            Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot") :
            $"{Environment.GetEnvironmentVariable("HOME")}\\site\\wwwroot";

        var config = new ConfigurationBuilder()
            .SetBasePath(basePath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)  // common settings go here.
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT")}.json", optional: false, reloadOnChange: false)  // environment specific settings go here
            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: false)  // secrets go here. This file is excluded from source control.
            .AddEnvironmentVariables()
            .Build();

        builder.Services.AddSingleton<IConfiguration>(config);
    }

    public bool IsDevelopmentEnvironment()
    {
        return "Development".Equals(Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT"), StringComparison.OrdinalIgnoreCase);
    }
}
like image 198
Turbo Avatar answered Sep 22 '22 10:09

Turbo