Calling an Azure Functions Function from the command line
Problem Statement
During a recent project I developed a solution that contains Azure Functions, that are deployed through a Azure DevOps Pipeline right after the infrastructure is created with bicep. For the final test in an Azure DevOps Pipeline/GitHub Actions, I aim to execute one of the newly installed Azure Functions to validate the installed/updated solution. If it runs successful, the deployment is validated and the pipeline can continue to run.
Because all names are dynamically created through bicep, the path/name of the functions and all keys are also dynamic and randomized, and only available as bicep outputs.
Solution
To obtain the URL and key of the Azure Functions Methods for testing purposes, I need to utilize the Azure CLI. The process involves retrieving the URL and key of the specific function to be called.
The following PowerShell script streamlines this task:
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[Alias('g')]
[string]$resourceGroup,
[Parameter(Mandatory=$true)]
[Alias('fan')]
[string]$functionAppName,
[Parameter(Mandatory=$true)]
[Alias('fn')]
[string]$functionName
)
Write-Host "Test Solution"
Write-Host "- resourceGroup : $resourceGroup"
Write-Host "- functionAppName : $functionAppName"
Write-Host "- functionName : $functionName"
# Get Url
$jsonResponse=az functionapp function show `
--name $functionAppName `
--resource-group $resourceGroup `
--function-name $functionName
$decodedObject = $jsonResponse | ConvertFrom-Json
$url = $decodedObject.invokeUrlTemplate
# Get Key
$jsonResponse=az functionapp function keys list `
--name $functionAppName `
--resource-group $resourceGroup `
--function-name $functionName
$decodedObject = $jsonResponse | ConvertFrom-Json
$key = $decodedObject.default
# Invoke
$invokeUrl=$url+"?code="+$key
$response = Invoke-RestMethod -Uri $invokeUrl -Method Post
Write-Host $response
Write-Host $response.StatusCode
return $response
Invoke this function in PowerShell using:
.\Test-Azure-Function.ps1 `
-resourceGroup <myresourcegroup> `
-functionAppName <myfunctionapp> `
-functionName <myfunction>
This script enables me to check the solution by calling the an Azure Function that runs some internal checks. Hope that helps you.
About the Author / Oliver Scheer
Meet Oliver, a Principal Software Engineer at Medialesson, boasting over 25 years of software development expertise across real and challenging customer projects. With 17 years of experience at Microsoft as both an Evangelist and Software Engineer, Oliver's focus lies in .NET, DevOps, Developer Experiences, and Cloud technologies. For more about Oliver, visit his website or LinkedIn profile.