未加星标

Clean up orphaned Azure resource manager disks

字体大小 | |
[系统(windows) 所属分类 系统(windows) | 发布者 店小二05 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

Firstly, let me apologise, this post isn’t about automatically cleaning up disks in Azure Resource Manager storage accounts, instead it’s about obtaining the information which you can use to understand which disks are orphaned and can or should be deleted.

When deleting a virtual machine on its own, I’m sure you’re aware that the disks are not automatically deleted as part of that process. The recommended best practice is to put every resource that shares the same lifecycle in to the same resource group which can then be deleted as a single entity, removing virtual machines, storage accounts, NICs, load balancers etc in one hit.

In some cases, there are occasions where it’s preferable to delete a single virtual machine on its own doing this leaves orphaned disks behind in your storage accounts, gathering dust (and costing money!) unless you manually delete the disks yourself. We all know that as we stand up and delete VMs in Azure, there are occasions where cleaning up just isn’t convenient and the disks get left and forgotten about. Many moons later we decide it’s a good time to clean up those orphaned disks but finding them manually or using Storage Explorer is a painful process when there’s potentially hundreds of storage accounts in a subscription.

Now that Managed Disks have gone Generally Available , this problem will occur less and less for people using those but for now, most people would benefit from understanding their VHD/storage account layout and usage.

I wrote the following PowerShell script to iterate over all (or some of the) storage accounts in a subscription, pulling out the details of any “blob” in any container, ending with .vhd. Rather than trying to identify unleased blobs and automatically deleting them (which is very dangerous when you have Azure Site Recovery protected objects) I chose to simply generate an object containing the information of every blob (ending with .vhd). For those of us happy using Powershell for filtering, we can then filter the object as we see fit or just output to CSV and filter in Excel for example.

You can target this to all storage accounts, some (via a regex match or like condition) or a specific account by adjusting the Get-AzureRmStorageAccount switches which act as the primary filtering mechanism. This script is non-destructive, it DOES NOT delete anything.

<# Three options for using this script. 1. Filter by storage account, specifying the RG and SA name - quick 2. Filter using a match in a Where clause - moderate 3. No filter. Gets all VHDs in all storage accounts in the subscription - slow #> Login-AzureRmAccount # You may need or want to Select-AzureRmSubscription # Everything - SLOW $AllStorageAccounts = Get-AzureRmStorageAccount # Filter using a match (or a like) - MODERATE $AllStorageAccounts = Get-AzureRmStorageAccount | Where {$_.StorageAccountName -match '(accounts)'} # Filter by single SA - QUICK $AllStorageAccounts = Get-AzureRmStorageAccount -ResourceGroupName 'myresourcegroup' -Name 'mystorageaccount' $AllVHDs = $AllStorageAccounts | Get-AzureStorageContainer | Get-AzureStorageBlob | Where {$_.Name -like '*.vhd'} $Uri = foreach ($VHD in $AllVHDs) { $StorageAccountName = if ($VHD.ICloudBlob.Parent.Uri.Host -match '([a-z0-9A-Z]*)(?=\.blob\.core\.windows\.net)') {$Matches[0]} $StorageAccount = $AllStorageAccounts | Where { $_.StorageAccountName -eq $StorageAccountName } $Property = [ordered]@{ Uri = $VHD.ICloudBlob.Uri.AbsoluteUri; AttachedToVMName = $VHD.ICloudBlob.Metadata.MicrosoftAzureCompute_VMName LeaseStatus = $VHD.ICloudBlob.Properties.LeaseStatus; LeaseState = $VHD.ICloudBlob.Properties.LeaseState; StorageType = $StorageAccount.Sku.Name; StorageTier = $StorageAccount.Sku.Tier; StorageAccountName = $StorageAccountName; StorageAccountResourceGroup = $StorageAccount.ResourceGroupName } New-Object -TypeName PSObject -Property $Property } $Uri | Export-Csv -Path '.\DiskLeaseInformation.csv' -NoTypeInformation

In my own tests, operating against ~90 storage accounts in a single subscription, retrieving data on ~600 VHD objects, the information was populated in to the object and a CSV created in ~50 seconds. You can of course include additional information in the object by adjusting the object properties accordingly but I would highly recommend that you do not use any cmdlets inside the foreach loop, instead get the source information outside of the loop and then filter for that information from the object inside the foreach, like I do with $StorageAccount.

You can use the CSV to identify objects that are surplus to requirements, badly named, in the wrong account/type and act on the information as you desire, but don’t be tempted to auto-delete anything from its output unless you’re supremely confident you know what you’re doing and especially not if you use Azure Site Recovery to protect on-premises machines…doing so is a Bad Idea

Before I disappear, in my quest to gather this information elegantly, and before I properly investigated the ICloudBlob object’s properties, I also put together the following Function which, given an HTTPS endpoint and the storage account key, uses the Azure Storage API to get the properties of a blob as response headers from an HTTP request. If nothing else it shows how to interact with the Storage API via WebRequests in PowerShell and construct an authenticated request.

Function Get-AzureRmBlobProperties { # See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/get-blob-properties param( [parameter(Mandatory=$true)][uri] $Url, [parameter(Mandatory=$true)] [ValidateScript({ Try { [System.Convert]::FromBase64String($_) } Catch [FormatException] { Throw 'Possible bad storage account key specified. '+$_} })] [string] $StorageAccountKey ) $Method = "HEAD" $APIDate = '2014-02-14' $Headers = @{} $Headers.Add("x-ms-version",$APIDate) $Headers.Add("x-ms-date",$((Get-Date -Format r).ToString())) $StorageAccountName = If ($Url -match '([a-z0-9A-Z]*)(?=\.blob\.core\.windows\.net)') {$Matches[0]} Else {Throw 'Unparseable storage account name in the provided Url.'} $authString = "$Method$([char]10)$([char]10)$([char]10)$([char]10)$([char]10)$([char]10)$([char]10)$([char]10)$([char]10)$([char]10)$([char]10)$([char]10)" $authString += "x-ms-date:" + $Headers["x-ms-date"] + "$([char]10)" $authString += "x-ms-version:" + $Headers["x-ms-version"] + "$([char]10)" $authString += "/" + $StorageAccountName + $Url.AbsolutePath $HMAC = New-Object System.Security.Cryptography.HMACSHA256((,[System.Convert]::FromBase64String($StorageAccountKey))) $Signature = [System.Convert]::ToBase64String($HMAC.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($authString))) $Headers.Add("Authorization", "SharedKey " + $StorageAccountName + ":" + $Signature); Return (Invoke-WebRequest -Uri $Url -Method $Method -Headers $Headers).Headers } Get-AzureRmBlobProperties -Url 'https://mystorageaccount.blob.core.windows.net/vhds/mydisk.vhd' -StorageAccountKey 'xxxxxx=='

-Lewis

本文系统(windows)相关术语:三级网络技术 计算机三级网络技术 网络技术基础 计算机网络技术

主题: PowerShellHeadUTUICExcelDOE
分页:12
转载请注明
本文标题:Clean up orphaned Azure resource manager disks
本站链接:http://www.codesec.net/view/535076.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 系统(windows) | 评论(0) | 阅读(39)