Automate the Creation of an Azure Function with an Event Grid Subscription in PowerShell

****This blog is out of date due to the new Eventgrid and functions integrations******

My colleague, Sangita Bhor, was recently working on a case where we needed to automate the deployment of an Azure Function and Event Grid Subscription. The difficulty here is that there isn’t an API from functions to get the web hook needed on the Event Grid Subscription side. The script below shows you how to get the get the Master Key for the function, then the System Key, and finally create the Event Grid resource with the function app web hook. Full credit goes to Sangita for creating the whole script.

#Event Grid Subscription

# Deployment creadentials

$user = ‘<user_name>’

$pass = ‘<Pwd>’

$pair = “$($user):$($pass)”

$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))

$basicAuthValue = “Basic $encodedCreds”

$Headers = @{

Authorization = $basicAuthValue

}

#get the Masterkey of the function app which is needed to get the System Key which is used in the Event Grid webhook

$master_key_Content=Invoke-WebRequest -Uri ‘https://<Function_name>.scm.azurewebsites.net/api/functions/admin/masterkey’ -Headers $Headers | select -Expand Content | ConvertFrom-Json

$master_key=$master_key_Content.masterKey.ToString()

$master_key

#Invoke the System key for the Event grid subscription->Endpoint URL

$content=Invoke-WebRequest “http://<Function_Name>.azurewebsites.net/admin/host/systemkeys/eventgridextensionconfig_extension?code=$master_key”| select -Expand Content | ConvertFrom-Json

$c=$content.value.ToString()

$myTopic = “<name_of_event_grid_topic>”

# Create custom topic(It will create the Event Grid Topic)

New-AzureRmEventGridTopic -ResourceGroupName MyTestApp -Location centralUS -Name $myTopic

# Retrieve endpoint and key to use when publishing to the topic(Which is not exactly needed for Azure subscription)

$endpoint = (Get-AzureRmEventGridTopic -ResourceGroupName MyTestApp -Name $myTopic).Endpoint

$key = (Get-AzureRmEventGridTopicKey -ResourceGroupName MyTestApp -Name $myTopic).Key1

New-AzureRmEventGridSubscription -EventSubscriptionName sampleeventwithpowershell -Endpoint “https://<Function_Name>.azurewebsites.net/admin/extensions/EventGridExtensionConfig?functionName=<Function_Name>&code=$c” -ResourceGroupName <Name_of_Resource_group> -TopicName $myTopic