31

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?

Avinash patil
  • 1,689
  • 4
  • 17
  • 39
  • RoleEnvironment is only available for Cloud Services. One thing you could try to do is add a reference for `Microsoft.WindowsAzure.ServiceRuntime` in your functions project. – Gaurav Mantri Jul 11 '17 at 05:47
  • @GauravMantri: this is not working it throws error : `the role environment has not been initialized` – Avinash patil Jul 11 '17 at 05:55
  • That's what I feared. I think only way you could do it would be to refactor the code and pass this as a parameter to your method. From the function code, you will pass false. From cloud services code, you will pass the actual value of RoleEnvironment member value. – Gaurav Mantri Jul 11 '17 at 05:58
  • 1
    but what about other properties, like `RoleEnvironment.CurrentRoleInstance.Id, RoleEnvironment.IsActive` etc. i need an alternative `RoleEnvironment` or way to initialize `RoleEnvironment ` in azure functions. – Avinash patil Jul 11 '17 at 06:06
  • do you find any solution? – Pingpong Mar 10 '19 at 23:46

4 Answers4

20

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);
        }
    }
}
AntoineC
  • 460
  • 4
  • 11
19

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).

Saeb Amini
  • 23,054
  • 9
  • 78
  • 76
  • This solution works well for me in Python (`os.getenv("AZURE_FUNCTIONS_ENVIRONMENT") == 'Development'` means local) -- while WEBSITE_INSTANCE_ID does not appear to be set when running Python – Daniel Schneider Jan 27 '20 at 01:30
  • when running locally it says `Development` but while published it says nothing at all. what am i doing wrong? – Ramon Dias Jul 06 '20 at 15:17
  • I have experienced that `AZURE_FUNCTIONS_ENVIRONMENT` cannot be relied upon. There are multiple errors in Azure that can set it to Development e.g. when docs clearly says it should be Production. I have found there is relatively simple way of achieving it: https://stackoverflow.com/a/66209057/1671558 – Ilya Chernomordik Jul 02 '21 at 07:02
  • @IlyaChernomordik as mentioned in the answer, it's not automatically set in Azure - it needs to be set explicitly. – Saeb Amini Jul 02 '21 at 08:00
  • Even that does not always work unfortunately due to some bugs. So you can set the variable explicitly and it will generally work, but there are scenarios when it stops working. Like disabling/enabling, redeploying. They are clearly bugs, but they exist nonetheless... E.g. here: https://github.com/Azure/azure-functions-host/issues/6239 – Ilya Chernomordik Jul 02 '21 at 08:40
15

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.

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
  • Yup, `AZURE_FUNCTIONS_ENVIRONMENT` has issues: https://github.com/Azure/azure-functions-host/issues/6239 – alhazen Jul 01 '21 at 18:06
  • Another workaround approach is preprocessor directives – noontz Feb 07 '23 at 12:48
  • Per my understanding the documentation does make it clear that the value for `AZURE_FUNCTIONS_ENVIRONMENT` is "Development" when running locally with core tools. Otherwise the value can be "Staging" or "Producion". Apparently there are issues in that you cannot override this value and that Microsoft allows only these three environments, but for to original question on finding out whether running locally or in the cloud, this seems to be the solution. If you need more control, then using a custom var is probably needed. – kaskelotti Jul 04 '23 at 08:02
  • The problem is that while your understanding is probably correct, the reality of Azure Functions is often such that it is not the same as documentation. I.e. it is either a bug in the functions runtime or documentation, which leads to me not trusting this exact part anyway. I do not know what leads to it, but sometimes it just happens – Ilya Chernomordik Jul 04 '23 at 09:02
  • I see. And I just tested that on local env the variable is "Developmet", but at least on one of my Azure envs it undefined. Basically this functionality suits me well, but I'll have to consider whether this is reliable or not as stated by you and others. – kaskelotti Jul 04 '23 at 09:08
5

You can use an approach similar to what the actual runtime uses to identify whether it is running on Azure: https://github.com/Azure/azure-webjobs-sdk-script/blob/efb55da/src/WebJobs.Script/Config/ScriptSettingsManager.cs#L25

In this case, the runtime checks for the presence of an app setting named WEBSITE_INSTANCE_ID

Community
  • 1
  • 1
Fabio Cavalcante
  • 12,328
  • 3
  • 35
  • 43
  • To give a bit more detail: !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID")) – Ryanman Mar 06 '18 at 20:39
  • Does not work when debugging using Azure Function Tools locally. – Imre Pühvel Nov 07 '18 at 15:58
  • do you find any solution? – Pingpong Mar 10 '19 at 23:46
  • 1
    AntoineC's answer is apparently the best solution possible. Check if this `WEBSITE_INSTANCE_ID` is empty, if it is, you are in **dev environment**... Now, it's only me or sometimes Microsoft lacks of standards with Azure Functions? I mean, why there isn't a simple way to do a simple thing like this? – Ramon Dias Jul 06 '20 at 15:46