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

May 24, 2018 0 By JeremyBrooks

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>’ -Headers $Headers | select -Expand Content | ConvertFrom-Json





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


$content=Invoke-WebRequest “http://<Function_Name>$master_key”| select -Expand Content | ConvertFrom-Json



$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><Function_Name>&code=$c” -ResourceGroupName <Name_of_Resource_group> -TopicName $myTopic