To support our student workers in developing and testing solutions within the Azure environment, we will provide them with access to an Azure subscription.
To manage costs effectively and prevent unexpected expenses, I have been tasked with creating a budget and implementing controls to limit resource consumption.
This will be achieved through a custom Azure Policy that automatically restricts the creation of new resources once the defined budget limit is reached.
The following workflow outlines the implementation process.
To enforce budget constraints, I’ve configured a budget alert to trigger an Action Group. This Action Group, in turn, will execute a runbook within an Automation Account. The runbook will then assign a custom Azure Policy that restricts users from creating new resources within the subscription.
Detailed step-by-step instructions are provided below.
Azure Policy
- Go to Policy service.
- Create a new Policy definition as below.
{
"properties": {
"displayName": "Disallow any resource creation",
"policyType": "Custom",
"mode": "All",
"version": "1.0.0",
"parameters": {},
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"exists": "true"
}
]
},
"then": {
"effect": "deny"
}
},
"versions": [
"1.0.0"
]
}
}
Automation Account
- Create an Automation account in the subscription.
- Assign permissions to the System-assigned managed identity.
- Go to Identity under the Account Settings in the Automation account.
- On the System Assigned tab, click Azure role assignments.
- Assign the role of Resource Policy Contributor to the identity.
- Create a runbook
- Select PowerShell at the Runbook type.
- Runtime version: 7.2
- Add the following code to the runbook.
# Define variables
$subscriptionID = "your_subscriptionID"
$policyDefinitionID = "yourPolicyDefinitionID"
$subscription = Get-AzSubscription -SubscriptionID $subscriptionID
$policyDefinition = Get-AzPolicyDefinition -Id $policyDefinitionID
# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process | Out-Null
# Authenticate to Azure
Connect-AzAccount -Identity
# Set the subscription context
Set-AzContext -Subscription $subscriptionID
# Assign Azure Policy to the subscription
New-AzPolicyAssignment -Name "Disallow any resource creation" `
-PolicyDefinition $policyDefinition `
-Scope "/subscriptions/$subscriptionID"
Budget Alert
- Create a Budget for the subscription.
- Create an Action group.
- Add the Automation Runbook to the action in the Action group.
4. Add the Action group to the Alert conditions in the budget.
5. Test the action group or start the runbook manually. The Custom Azure Policy should be assigned to the subscription.
6. You should see the error message when creating a resource.