Automating Azure Web App Shutdown When Budget Exceeds a Threshold
Managing cloud costs is crucial, and Azure provides tools to automate actions when your budget reaches a predefined threshold. In this guide, I’ll walk through how I automated the shutdown of my Azure web app when my budget hit a certain limit.
Step 1: Create an Automation Runbook
Azure Automation Runbooks allow us to execute scripts automatically. We will create a Runbook that stops the web app.
- Click the menu (☰) in the Azure Portal.
- Select Create a Resource.
- Search for Automation Accounts and create one.
- Navigate to the newly created Automation Account.
- On the left panel, select Process Automation > Runbooks.
- Click Create a Runbook.
- Choose Powershell as the runtime version and click create.
- Add the following script to the Runbook.
param (
[string]$ResourceGroupName = "ResourceGroupName",
[string]$WebAppName = "WebAppName"
)
Connect-AzAccount -Identity
Stop-AzWebApp -ResourceGroupName $ResourceGroupName -Name $WebAppName
- Replace the $ResourceGroupName and WebAppName values with your actual resource details.
- Click Publish to finalize the Runbook.
Step 2: Create an Action Group
An Action Group defines what happens when an alert is triggered.
- Click the menu (☰) and go to Monitor.
- Navigate to Alerts.
- Select Create Action Group.
- Fill in the required information.
- In the Actions tab:
- Set Action Type to Automation Runbook.
- Runbook > Enabled
- Runbook Source > User
- Choose your subscription, Automation account, and Runbook.
- Click OK, then Create.
Step 3: Set Up a Budget
Now, lets create a budget and configure it to trigger our Action Group.
- Click the menu (☰) and navigate to Cost Management + Billing.
- Click on Cost Management > Budgets.
- Important: Change the scope to your Subscription.
- Click Add and configure the budget according to your needs.
- In the Set Alerts tab, ensure you select your Action Group.
Step 4: Grant Permissions to the Automation Account
For the Runbook to execute properly, it needs permission to manage resources
- Go to either your Web App or Resource Group.
- Click IAM (Identity and Access Management).
- Select Add Role Assignment.
- Choose the Contributor role.
- Set Assign Access To as Managed Identity.
- Select your Automation Account.
- Click Review and Assign.
Summary
With this setup:
- The budget alert triggers the Action Group.
- The Action Group runs the Automation Runbook.
- The Runbook executes a script that stops the web app when the budget threshold is met.
This automation ensures your Azure costs stay under control without manual intervention. Hope this guide helps you implement a similar solution!
Enjoy Reading This Article?
Here are some more articles you might like to read next: