Best place to store environment variables for Azure Function

后端 未结 4 1780
旧时难觅i
旧时难觅i 2021-02-03 23:14

I\'m testing an azure function locally with several api keys. Whats the best place to store environment variables and how do I access them? I tried

System.Enviro         


        
4条回答
  •  萌比男神i
    2021-02-03 23:47

    In Azure Functions 2, we moved to ASP.NET Core configuration, and ConfigurationManager is no longer supported. This remains true in 3.

    I have seen many articles where people are spraining themselves getting ConfigurationBuilder setups working. The problem is that once you start doing DI, which was recently added, some annoying scenarios arise caused by not having access to a Context parameter (1). It is much cleaner to just use Environment.GetEnvironmentVariable.

    This maps perfectly to the configuration model of Azure Functions: in dev, it picks up items in the local.settings.json > Values array, and in production it picks up your environment variables. It just works.

    I see no downside other than it's different than what we do in MVC. But this is not MVC, it is Functions, and until MS brings these platforms into better alignment, we should open our minds to what is best in Functions rather than forcing a different paradigm to work here.

    Your local.settings.json might look like this:

    {
        "IsEncrypted": false,
        "Values": {
            "KeystoneDB": "[CONNECTION STRING HERE]"
            "FUNCTIONS_WORKER_RUNTIME": "dotnet"
        }
    }
    

    And in production, you set the environment variables in the portal.

    (1) There's no other clean way to satisfy ConfigurationBuilder().SetBasePath that I'm aware of. See: Get root directory of Azure Function App v2

提交回复
热议问题