How to set environment variables for use with an Azure Function

There are many ways to pass variables into an Azure Function.

In this quick blog post I will show you how you can test the Azure Function locally with local settings and then use app settings from the Azure Portal and then also use values stored within Azure KeyVault incase we need to store and retrive secrets.

Ok, so to run our Azure Function locally I prefer to use C# Azure Functions, they just work, I can debug them in VS Code or Visual Studio – I am a dinosaur and been using Visual Studio since it first came out so I tend to stick with using that over VS Code, yes I am that old.

Moving on lets show how we can make use of variables whilst debugging locally, for this we just need to create a local.settings.json file like the one below:-

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "DemoUsername": "azuregreg",
    "DemoPassword": "letmein"
  }
}

So our code can now use a stored username and password to test with locally – we don’t check this file in as its only for testing locally (add a .gitignore file).

Ok so we can test our Azure Function with code that accesses the local variable and away we go.

So our function now outputs the following (remember this is from local settings) :-

this is gregors demo function - the username is azuregreg and the password is letmein


Now the interesting part next is how do we store variables in Azure and make use of them.

So, we have some options available to us, for things like username and password we can store them in Azure KeyVault, if they are simple settings then we can store them in appsettings within the Azure Portal.

Let’s take a look at storing these variable in the App Settings section of the Azure Portal for our Azure Functions.

In the screen shot above we are in the Azure Portal and clicked into our Azure Function app and then click on Configuration and then + New application setting

Now we can add configuration values to our code, we can store setting here but sometimes we need to store secrets and for this we use Azure KeyVault, which we will return to shortly.

So lets add the username and password settings into the application settings and see how we can use them first of all.

So I went ahead and added them into the application settings section like so:-

In the screen shot above I clicked Show Values so that I can show you, the reader, the values I set exactly the same properties in the local.settings.json file when debugging locally – click Save.

Ok, so now we have added in some application settings, how does the code need to change to pick up these values from this area in the Portal? – well the good answer is we don’t need to change our code, it works exactly the same way as whilst using the local.settings.json file.

So the above works, but I hate when people say yeah but it works, yeah it works but can we make it better should always be the question – getting things working and making it as secure as it can be are different things altogether.

So why would we want to perhaps store the username and password in KeyVault? – glad you asked.

Maybe there is a username and password which you don’t want everyone to know, so you can add these values to KeyVault and not give anyone access to read the values for the password for example, but your application can read and use the value from the keyvault without anyone being able to see the password in plain text – sounds good to me so lets go set this up.

If you want to test this out I created a C# Azure Function which is basically just the following code, reminder the local.settings.json is at the start of the blog post.

C# Azure function code below.

[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string username = Environment.GetEnvironmentVariable("DemoUsername");
    string password = Environment.GetEnvironmentVariable("DemoPassword");

    string responseMessage = "this is gregors demo function";

    return new OkObjectResult(responseMessage);
}

First we need to create a KeyVault and one you’ve done that, locate it and click on Secrets and create 2 new secrets, lets call then username and password for simplicity – set the values like so:-

username: azuregregviaappsettings
password: letmeinviaappsettings

When we run our Azure HTTP Function this time it picks up the values from the appsettings we just updated in the app settings section of the Azure function in the portal.

So our function now outputs:-

this is gregors demo function - the username is azuregregviaappsettings and the password is letmeinviaappsettings

Lets now change our existing app settings so that we get the details from KeyVault rather than just simply storing them in our app settings (where anyone can see them) – only people with the correct RBAC user rights can see our KeyVault secrets.

Ok now that we have our 2 secrets lets try to access them from the appsettings section of our Azure Function. Go back to the Azure Function and then click on Configuration and then we will be back at the screen that shows us our current applications settings.

Now lets edit the existing app setting called DemoUsername by finding the row and selecting the edit button as below :-

Lets past in the following
@Microsoft.KeyVault(SecretUri=https://<your keyvault name>.vault.azure.net/secrets/username) replacing <your keyvault name> with the name of your KeyVault like below.

Once you’ve done this for the username and password we can now use the values from our Azure Function.

Before this works we need to do a couple more steps – we need to create a managed identity and then also create an access policy within KeyVault.

To create a managed identity go to your Azure Function and then under Settings, select Identity. Change the status to On and click Save, also take a copy of the Object ID as we will need this later on.

Next we need to create an access policy within Kay Vault, so go into you’re KeyVault and select Access Policies, and then choose the + Add Access Policy link. Where it says Select principal, click the words none selected and then paste in the Object ID we took a note of above and then select it. Then within the Secret permission drop down select Get and List and then click Add.

Now go back to your Azure Function and select Configuration and then edit both your DemoUsername and DemoPassword app settings and then click save, They should now look like this:-

Notice in the screen shot above the Green Tick next to the words Key vault Reference, if this is red then check your steps with the managed identity, and creating the access policy above.

So our function now outputs:- 

this is gregors demo function - the username is azuregregfromkeyvault and the password is letmeinviakeyvault

And that is how you can run and test or function locally, using local.settings.json but also stored environment variables in app settings but also store them in KeyVault if they are secrets.

Don’t forget to subscribe to my YouTube Channel.