Briefly, this post will provide you a step to step guidance with sample code on how to leverage Azure PowerShell Function App to manage Azure resources and use managed identity for authentication to simplify the workflow.
Azure PowerShell is a set of cmdlets for managing Azure resources directly from the PowerShell command line. Azure PowerShell is designed to make it easy to learn and get started with, but provides powerful features for automation.
Azure Functions is a cloud service available on-demand that provides all the continually updated infrastructure and resources needed to run your applications. You focus on the pieces of code that matter most to you, and Functions handles the rest. Functions provides serverless compute for Azure. You can use Functions to build web APIs, respond to database changes, process IoT streams, manage message queues, and more.
When we combine the Azure PowerShell and Azure Function App, it could make a magic. For example, we can make it automatic to restart a Virtual Machine(s) on schedule. Or update a rule in network security group with a HTTP request.
In this post, we will take restoring Azure Web App from Snapshot regularly as an example to demonstrate the idea. The general workflow is as follow:
Create PowerShell Function App -> Enable Managed identity -> Grant related resource permissions to the identity(Function App) -> Integrate Az module in functions -> Test and Run
The topology is as below, we will grant role permission to Function App from source web app and Destination Web App. Then manage them from the function app.
Steps:
{second} {minute} {hour} {day} {month} {day-of-week}
Sample Code:
Replace the source and destination web app, resource groups with yours.
# Input bindings are passed in via param block.
param($Timer)
# Get the current universal time in the default string format.
$currentUTCtime = (Get-Date).ToUniversalTime()
# The 'IsPastDue' property is 'true' when the current function invocation is later than scheduled.
if ($Timer.IsPastDue) {
Write-Host "PowerShell timer is running late!"
}
$srcWebappname = "SourceWebApp"
$srcResourceGroupName = "SourceGroup"
$dstWebappname = "DestinationWebApp"
$dstResourceGroupName = "DestinationGroup"
$snapshot = (Get-AzWebAppSnapshot -ResourceGroupName $srcResourceGroupName -Name $srcWebappname)[0]
Write-Host "Start restoring Snapshot from $srcWebappname to $dstWebappname"
Restore-AzWebAppSnapshot -ResourceGroupName $dstResourceGroupName -Name $dstWebappname -InputObject $snapshot -RecoverConfiguration -Force
Write-Host "Done"
# Write an information log with the current time.
Write-Host "PowerShell timer trigger function ran! TIME: $currentUTCtime"
Test and Run:
When we manually trigger it, it should be shown like as below:
All done. Thanks for reading! I hope you have fun in it!
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.