Rico Suter's blog.

For a recent project I dynamically create new Azure Functions in an Azure DevOps release pipeline. One of the requirements was to automatically update each default Host Key to a given value so that it’s easier to access the newly created HTTP functions.

Because there is no easy out-of-the-box API in Azure CLI or Azure PowerShell, I wanted to share the final solution here.

To update the default Azure Function Host Key in an Azure PowerShell build/release task, just follow these steps:

1. Create a new “Azure PowerShell” task in your Azure DevOps build or release pipeline

2. Choose an “Azure Subscription” which has privileges to access the resource

3. Under “Azure PowerShell Version” use the “Latest installed version”

4. Use “Inline Script” and insert the following script:

$functionName = "my-azure-function";
$resourceGroup = "my-azure-function-resource-group";
$functionHostKey = "my-new-function-host-key";

$publishingCredentials = Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroup -ResourceType "Microsoft.Web/sites/config" -ResourceName "$functionName/publishingcredentials" -Action list -ApiVersion 2015-08-01 -Force
$authorization = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $publishingCredentials.Properties.PublishingUserName, $publishingCredentials.Properties.PublishingPassword)))
$accessToken = Invoke-RestMethod -Uri "https://$functionName.scm.azurewebsites.net/api/functions/admin/token" -Headers @{Authorization=("Basic {0}" -f $authorization)} -Method GET

$data = @{
"name" = "default"
"value" = "$functionHostKey"
} | ConvertTo-Json;

$response = Invoke-RestMethod -Method PUT -Headers @{Authorization = ("Bearer {0}" -f $accessToken)} -ContentType "application/json" -Uri "https://$functionName.azurewebsites.net/admin/host/keys/default" -body $data

Update the variables $functionName, $resourceGroup and $functionHostKey to your liking - you can also use build variables, e.g. $(Build.BuildNumber):

As you can see, this script retrieves the Kudu credentials from your App Service to retrieve an access token. With this access token it then calls the Azure Function’s key management API to update the default host key.