Get Azure Function host key in an ARM deployment template
I am currently working in a IoT project where we aim at enabling LoRaWan devices to communicate directly with Azure. The payload of these devices are typically encoded very differently depending on payload type, manufacturer,… And therefore we needed to provide a plug-and-play mechanism enabling our code to call different decoding methods using same authentication key.
We decided to use Azure Function to implement those decoders due to the Serverless aspect of it (we don’t need always a given decoder running). Function are typically protected by a key that you can either give as a query string (e.g. https://FUNCTION_NAME.azurewebsites.net/api/functionname?code=YOUR_CODE or as a header (x-functions-key : YOUR_CODE).
There are four different key authentication methods:
- Anonymous : Anyone can call the given function.
- Function key : A key used to authenticate at a function level.
- Host key : A key shared by all the functions hosted on a given function app.
- Master key : This key provide administrative access to the runtime API.
Given our current problem, Only the Host key or the Master key can be used to get authentication across the full function application. However, the documentation don’t advice to use the Master key as it provides a very high administrative power (and as one said : with great power comes great responsibilities).
For all the reasons above we used the Host key as authentication method. However another problem rose when we had to build an ARM template to deploy our infrastructure to Azure. Indeed there are currently no way an ARM template can get the Host keys at deployment time, it is currently only possible to get keys at a function level and this was not an option for us.
We then used the pattern I described in a previous blog post to call a function from a linked template to resolve the master key programmatically using the KUDU API. You need to authenticate by providing your deployment credentials, which you have access in your arm template and therefore can provide as argument to your function. Here is the function code, largely inspired from this great Stackoverflow answer and only adapted to get the input from the ARM template.
You will be able to use the function host key within your function code, but moreover the function will output your function key as an ARM template compatible string, so you will be able to reference it inside your main ARM template. As you can see in the ARM snippet below, the initial function call is secured as I am using the getKeys function key, So I make sure a third party can’t call this function without having access to my function key.
You can find the full code of this project here : http://www.github.com/mandur/Kainuu with a demo template outputting you the host key in your main arm template deployment.
