1

I need to check what environment, local or Azure, Azure Functions is running on.

Below is the code based on this and this

var isLocal = string.IsNullOrEmpty(GetEnvironmentVariable("WEBSITE_INSTANCE_ID")

Is this a documented feature, or stable feature?

If not, is there an alternative?

Azure function 2.x

VS 2017

Pingpong
  • 7,681
  • 21
  • 83
  • 209
  • Wouldn't the simplest thing be to set your own env variable? – James Mar 10 '19 at 23:42
  • Setting own env variable works, but if built-in feature supports it, it is better. – Pingpong Mar 10 '19 at 23:44
  • better how? Setting your own means you can guarantee no breaking changes – James Mar 10 '19 at 23:45
  • avoid reinventing the wheel – Pingpong Mar 10 '19 at 23:47
  • It's hardly re-inventing the wheel.... In fact, you aren't reinventing anything because there isn't (as far as I am aware) any environment variables set by Azure to explicitly indicate you are running in a host environment. – James Mar 10 '19 at 23:51
  • 1
    `WEBSITE_INSTANCE_ID` looks a fairly reliable option, however, the point still stands, it's not a guarantee. – James Mar 10 '19 at 23:57
  • 2
    It is practical reliable to use it to indicate that you are running in Azure env (not local). In fact, Kudu (Scm site) uses exactly that. See https://github.com/projectkudu/kudu/blob/f2f8e4c201682cd172c919c7c4e0c75dbca47833/Kudu.Core/Environment.cs#L369-L372 – Suwat Ch Mar 11 '19 at 05:36

1 Answers1

2

Azure App Service sets some environment variables with information about your Web App/Function App running on Azure.

  • WEBSITE_SITE_NAME - The name of the site.
  • WEBSITE_SKU - The sku of the site (Possible values: Free, Shared, Basic, Standard).
  • WEBSITE_COMPUTE_MODE - Specifies whether website is on a dedicated or shared VM/s (Possible values: Shared, Dedicated).
  • WEBSITE_HOSTNAME - The Azure Website's primary host name for the site (For example: site.azurewebsites.net). Note that custom hostnames are not accounted for here.
  • WEBSITE_INSTANCE_ID - The id representing the VM that the site is running on (If site runs on multiple instances, each instance will have a different id).
  • WEBSITE_NODE_DEFAULT_VERSION - The default node version this website is using.
  • WEBSOCKET_CONCURRENT_REQUEST_LIMIT - The limit for websocket's concurrent requests.

You can use WEBSITE_INSTANCE_ID to get the id of instance hosting your Function App

public static class TestFunction
    {
        [FunctionName("TestFunction")]
        public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation(Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID"));
        }
    }

Reference: https://github.com/projectkudu/kudu/wiki/Azure-runtime-environment#environment

Ketan
  • 1,530
  • 7
  • 16