Search code examples
powershellazureazure-storageazure-blob-storageazure-diagnostics

How to remove "bootdiagnostics" container from storage blob when deleting Azure VM?


I'm tasked with automating the creation of Azure VM's, and naturally I do a number of more or less broken iterations of trying to deploy a VM image.

I just discovered that my storage account's blob service is collecting a looong list of containers for boot diagnostics.

Because I've deleted many of the VM's these belong to, these containers are all useless to me, and in the portal they crowd out the few useful folders I do want. In fact, I have a script to destroy VM's (which removes the resources, VHD, and so on); I want this script to also kill these diagnostics containers.

But the containers have very awkward names -- and only contain part of the hostname ...

  • How can I, from Powershell, identify the diagnostics container belonging to a specific VM, so that I can delete it along with the other resources?
  • Why does Azure not handle this more elegantly, why do I have to "discover" that diagnostics containers and VHD's are not removed when you remove a VM? Is there simply yet another button or screen that I'm not aware of?

enter image description here


Solution

  • I found that the UUID is part of the name of the "status" file (which I have no idea what does) that lives alongside the OS VHD file!

    function getUUID([string] $vmname) {
        $storageContext = (Get-AzureRmStorageAccount | Where-Object{$_.StorageAccountName -match $azureStorage}).Context
        $storageBlob = Get-AzureStorageBlob -Context $storageContext -Container "vhds"
        $vhdList = $storageBlob | Where-Object{$_.Name -match "$vmname"} | Where-Object{$_.Name -match "^$hostname.*\.status$"}
        $uuid = $vhdList.Name # Get name including UUID
        $uuid = $uuid -replace "\.status","" # Remove suffix (".status")
        $uuid = $uuid -replace ".*?\.","" # Remove prefix ("bootdiagnostics-$vmname.")
        return $uuid
    }