How to check Azure function is running on local environment? `RoleEnvironment` is not working in Azure Functions

Viewed 10837

I have a condition in code where i need to check if current environment is not local.i have used !RoleEnvironment.IsEmulated, now this is not working in Azure functions but works in Cloud service. Same code is Shared in Cloud service also, so solution should work with cloud service and azure functions.

how can i check current environment is local not hosted/deployed?

4 Answers

Based on answer by Fabio Cavalcante, here is a working Azure function that checks the current running environment (local or hosted):

using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System;

namespace AzureFunctionTests
{
    public static class WhereAmIRunning
    {
        [FunctionName("whereamirunning")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            bool isLocal = string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID"));

            string response = isLocal ? "Function is running on local environment." : "Function is running on Azure.";

            return req.CreateResponse(HttpStatusCode.OK, response);
        }
    }
}

You can use the AZURE_FUNCTIONS_ENVIRONMENT environment variable, which is set automatically in local development:

Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT"); // set to "Development" locally

Note that when deployed/published (i.e. Azure), you'd need to set the environment variable yourself (e.g. function app settings in Azure).

I am not sure it is a good idea to be dependent on some internal implementation like e.g. WEBSITE_INSTANCE_ID advised in the other answers.

I have just used a very simple approach by defining my own environment variable via local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "IS_RUNNING_LOCALLY": true
  }
}

then I just check like that:

bool isLocal = Environment.GetEnvironmentVariable("IS_RUNNING_LOCALLY") == "true";

It is a workaround, but it's easy and intuitive and should be rather safe.

I tried with AZURE_FUNCTIONS_ENVIRONMENT, but one cannot set it in the local file as the runtime complains that it already exists, which seems like very stupid as one could have just set environment to "Local" e.g.

P.S. It seems that relying on e.g. default Environment is risky since there are multiple bugs related to it and you are not quite guaranteed for it to be "Production" as the documentation claims. See e.g. here.

Related