I've been building an application using Azure Functions with F# as the API backend. The Azure Functions access data in Azure Storage to return to a single page web application. For development purposes, I've had the connection string hard-coded in the F# files that needed it. I'm at a point where I need to start deploying this app in a production manner, so I need to get the connection strings out of my code. The documentation for Azure Functions recommends using environment variables in production, and the local.settings.json file for development. Reading these values should have been trivial, but wasn't. This post documents how I was finally able to read data from environment variables.
Most of the documentation that I was able to find online pointed to using the Environment.GetEnvironmentVariable("myData") syntax. I was absolutely unable to get this call to work for me in my F# function. Fortunately I'm a member of the F# Slack community. I reached out for help on this issue, and Zaid Ajaj gave me a few things to try. This experimentation led to the solution below:
In the function above, I create a new ConfigurationBuilder instance and configure it for my app. To properly configure it, I needed to include another parameter for the function call, (context: ExecutionContext). This parameter gives me access to the runtime directory with the property context.FunctionAppDirectory. This allows me to then inject the local.settings.json file. (Note the boolean value true in the call to AddJsonFile. This true indicates that this file is optional, which is necessary in a production setting when this file will not exist.). Once I build the ConfigurationBuilder, I'm able to access local settings and environment variables using the array accessor syntax, config.["BoogyMan"].
I'm not sure if this is the "approved" Microsoft way or the best way to read environment values in an F# Azure Function, but it does work. If there is a better way to to this, I would love to see it.