Add Azure Function key using PowerShell

In today’s article I want to show you how to add Azure Function key using PowerShell.

Azure Function keys allows to authorize and authenticate at the level of the entire application or a single function using keys.
In my script I’ve added only option to set same key for all of the functions in application.
All input parameters are mandatory, so remember to fill them all.


function Add-AzureFunctionKey {


    $AzureContext = Get-AzureRmContext
        Write-Output "Please login to your Azure Account"
    $SubscriptionId = (Get-AzureRmSubscription | select Name, State, SubscriptionId, TenantId | Out-GridView -Title "Azure Subscription Selector" -PassThru).SubscriptionId
    Get-AzureRmSubscription -SubscriptionId $SubscriptionId | Select-AzureRmSubscription
    $PublishingProfile = (Get-AzureRmWebAppPublishingProfile -ResourceGroupName $resourceGroup -Name $appName)
    $user = (Select-Xml -Xml $PublishingProfile -XPath "//publishData/publishProfile[contains(@profileName,'Web Deploy')]/@userName").Node.Value
    $pass = (Select-Xml -Xml $PublishingProfile -XPath "//publishData/publishProfile[contains(@profileName,'Web Deploy')]/@userPWD").Node.Value

    $pair = "$($user):$($pass)"
    $kuduCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))

    $authToken = Invoke-RestMethod -Uri "https://$" -Headers @{Authorization = ("Basic {0}" -f $kuduCredentials)} -Method GET

    $Functions = Invoke-RestMethod -Method GET -Headers @{Authorization = ("Bearer {0}" -f $authToken)} -Uri "https://$"
    $Functions = $Functions.Name
    ForEach ($functionName in $Functions) {
        $data = @{ 
            "name"  = "$funcKeyName"
            "value" = "$funcKeyValue"
        $json = $data | ConvertTo-Json;

        $keys = Invoke-RestMethod -Method PUT -Headers @{Authorization = ("Bearer {0}" -f $authToken)} -ContentType "application/json" -Uri "https://$$functionName/keys/$funcKeyName" -body $json
        Write-Output "Function $FunctionName Key updated $keys"

If you will have issue with add Azure Function key, ensure that you have at least write permission on application which you want to add key.

I hope it will be usefull for some of you 😉

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.