Automating disk cleanup in Azure is essential for cost efficiency. This guide introduces the new LastOwnershipUpdateTime property for tracking disk state changes. It explains how to identify unattached disks older than 60 days using PowerShell and Azure Resource Graph, and provides a step-by-step process to automate their deletion.2.

“`html
Automating Disk Cleanup in Azure: A Game Changer
Managing resources in Azure is essential for optimizing costs and enhancing operational efficiency. Recently, Microsoft introduced a new property called LastOwnershipUpdateTime for Azure disks. This feature tracks the last state change of a disk, making it easier to manage resources effectively.
What’s New?
The introduction of the LastOwnershipUpdateTime property allows users to identify unattached disks that haven’t been updated in over 60 days. This new feature simplifies the process of automating disk cleanup using PowerShell and Azure Resource Graph queries.
“Automating the cleanup of unattached disks older than 60 days helps optimize resource usage and reduce costs.”
Major Updates: Step-by-Step Guide
To automate disk cleanup, follow these steps:
1. Update Azure PowerShell Modules
Ensure you have the latest version of the Azure PowerShell module. Use the following commands:
# Check for existing Az modules
get-module -ListAvailable -Name Az* | Select-Object Name, Version
# Uninstall old versions
Get-Module -ListAvailable Az* | foreach { Uninstall-Module -Name $_.Name -RequiredVersion $_.Version }
# Install the latest Az module
Install-Module -Name Az -AllowClobber -Scope CurrentUser
# Verify the installation
Get-Module -ListAvailable -Name Az* | Select-Object Name, Version
2. Write the Azure Resource Graph Query
This query identifies disks that haven’t had ownership updates in the last 60 days:
$disksToBeRemoved = Search-AzGraph -Query '
resources
| where type == "microsoft.compute/disks"
| where todatetime(properties.LastOwnershipUpdateTime) < ago(60d)
| project name, diskState = properties.diskState, lastUpdateTime = format_datetime(todatetime(properties.LastOwnershipUpdateTime), "dd-MM-yyyy")
'
3. Automate Disk Deletion
Once identified, automate the deletion of these disks:
foreach ($disk in $disksToBeRemoved) {
Write-Output "Disk: $($disk.name), Last Update: $($disk.lastUpdateTime)"
Remove-AzDisk -Name $disk.name
}
What's Important to Know?
Implementing this automation can significantly streamline Azure resource management. It helps ensure that you only retain necessary resources, thus minimizing costs. However, always verify the disks before deletion to avoid accidental data loss.
"By following this guide, you can implement a similar solution in your Azure environment."
Conclusion
Automating disk cleanup is a straightforward yet powerful way to enhance your Azure management strategy. For any questions or feedback, feel free to leave a comment below!
```From the Core Infrastructure and Security Blog