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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With