Powered by Microsoft Azure

Auto Clean Azure Resources – Using Azure Automation

azure, cybersecurity, IT

Auto Clean Azure Resources – Using Azure Automation

Here’s an easy way to clean up Azure Subscription and delete all resource groups, plus resources to save some credits.

Step 1 is to create a resource group named ‘automation’ (or change the name in the script below) and create an automation account. Ensure that the “System Assigned” identity is checked while account creation.

Step 2, go to Subscription and enable contributor access for the automation account.

Step 3, Go to the Automation account and click on runbook and create a new account.

Step 4, paste the PowerShell script here and hit Save, followed by Publish

Step 5, click on start to test the script or in case you want to schedule it, click on Schedules inside the runbook and add a schedule as per your requirement.

The automation account has contributor access on the Sub., so when the runbook will trigger at a specific time, it will clean off all resource groups and resources.


# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process

# Connect to Azure with system-assigned managed identity
$AzureContext = (Connect-AzAccount -Identity).context

# set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext

Write-Output "Using system-assigned managed identity"

#Get Azure Resource Groups
$allresourcegroups = Get-AzResourceGroup | Where-Object ResourceGroupName -NotLike '*automation*' ##exception is set here
        Write-Output "No resource groups found";
        Write-Output "Starting the cleanup process";
            foreach($resourceGroup in $allresourcegroups){

                $rgname = $resourceGroup.ResourceGroupName

                    Write-Host "Deleting $($resource.ResourceGroupName)..."
                    Remove-AzResourceGroup -Name $rgname -Force
        Write-Output "Cleanup Completed";

Leave a Reply

Your email address will not be published.