teamdever
teamdever

Reputation: 372

Automation to delete unused VMs and their resources in Azure by last power on date

I need to create an automation that will delete VMs that were not started in the last two weeks and their associated resources (for example a Network interface or a Disk etc..) inside a single resource group. I thought about using a Powershell runbook in an automation account but I have some problems with that, I couldn't find a Powershell command to check last start date of all VMs in a resource group or a Powershell command to delete a VM and all its' associated resources. If I had these two I could make a Powershell runbook that will check last start time of a VM and if the date exceeds two weeks it'd automatically delete it and its' associated resources. Anyone knows how to accomplish these two things or maybe knows a different way to do this?

Upvotes: 0

Views: 2265

Answers (2)

teamdever
teamdever

Reputation: 372

I went through some searching on this and ended up creating this script that does the job:


$rgName = "resource group name"
$VMs = Get-AzVM -ResourceGroupName $rgName | ? {$_.Tags.Keys -notcontains "DontDelete"}

#$VMs = $VMs | ? {$_.Name -eq 'ePO'}

foreach ($VM in $VMs)
{
    $vmName = $VM.Name
    $vmID = $VM.Id

    Get-AzVM -VMName $vmName | Stop-AzVM -Force

    #################################################################################### 
    $nicID = $VM.NetworkProfile.NetworkInterfaces.id   

    ####################################################################################    
    $diskID = $VM.StorageProfile.OsDisk.ManagedDisk.Id

    $snapshotConfig = New-AzSnapshotConfig -SourceUri $diskID -Location $VM.Location -CreateOption copy
    $snapshot = New-AzSnapshot -Snapshot $snapshotConfig -SnapshotName "$vmName-snapshot" -ResourceGroupName $VM.ResourceGroupName

    ####################################################################################
    Remove-AzResource -ResourceId $vmID -Force
    Remove-AzResource -ResourceId $nicID -Force
    Remove-AzResource -ResourceId $diskID -Force
}

Decided that instead of last powered on date I'll use a "DontDelete" tag for the VMs I don't want to delete and the rest will be deleted as well as their associated resources. I added this script to a runbook in an automation account and ran it and it works perfectly.

Upvotes: 0

4c74356b41
4c74356b41

Reputation: 72176

there is no easy way to do that (so no cmdlet that would do either of things you require). You'd need to script those 2 operations.

You'd probably need to use Get-AzVm and parse the output to figure out when was it powered on (not sure this is even exposed in the api) along with something like this https://adamtheautomator.com/remove-azure-virtual-machine-powershell/

Upvotes: 1

Related Questions