GitHub Actions Workflow to Delete Multi-Session Host Pool VMs Running an Old Image

This workflow can be used to delete old image version session hosts.

The script will do the following:

• Checks if the VM is deallocated or running. If deallocated, the script will delete the VM.
• If the VM is running, the script will check for active or disconnected sessions, and if any exists the script will skip these.
• If the VM is running but has no active or disconnected sessions, then it will stop/deallocate the VM and delete it.

name: Multi-Session OLD VM Image Cleanup
on:
  workflow_dispatch:
    inputs:
      environment:
        description: Subscription
        required: true
        default: PROD
        type: choice
        options:
          - PROD
          - NonProd
          - Test
      HostpoolName:
        description: Host Pool Name
        required: true
        default: 'AVD-CIN' 
        type: choice
        options:
          - AVD-CIN
          - AVD-SIN
          - AVD-EUS
          - AVD-WEU
          - AVD-WUS
      ResourceGroupName:
        description: Host Pool ResourceGroupName
        required: true
        default: 'rg-cin' 
        type: choice
        options:
          - rg-cin
          - rg-sin
          - rg-eus
          - rg-weu
          - rg-wus

jobs:
  Check_Host_Pools_Image_Versions:
    runs-on: ubuntu-latest
    environment: 
      name: ${{ github.event.inputs.environment}}
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Login to Azure
        uses: azure/login@v1
        with:
          creds: '${{secrets.A}}'
          enable-AzPSSession: true
      - name: Find Old Session Host Images
        id: task-old-image
        uses: azure/powershell@v1
        with:
          azPSVersion: latest
          inlineScript: |
                Install-Module -Name Az.AVD -RequiredVersion 3.0.0 -Force
                Import-Module Az.AVD
                $subscriptionid = ""
                $Tenantid = '${{secrets.}}'
                $clientID = '${{secrets.}}'
                $ClientSecret = '${{secrets.}}'
                Connect-Avd -ClientID $clientID -ClientSecret $ClientSecret -TenantID $Tenantid - 
                SubscriptionId $SubscriptionId
                $HostPoolName = "${{ github.event.inputs.HostpoolName }}"
                $ResourceGroupName = "${{ github.event.inputs.ResourceGroupName }}"
                $SessionHosts = Get-AvdImageVersionStatus -HostpoolName $HostPoolName -ResourceGroupName 
                $ResourceGroupName -NotLatest

                foreach ($sessionHost in $SessionHosts) {
                    Write-Output "Checking VM: $($sessionHost.sessionHostName)"

                    $hostname = $sessionHost.sessionHostName.Split("/")[-1]
                    $shortHostname = $hostname.Replace('.domain.com','')

                    $hostSessions = Get-AzWvdUserSession -ResourceGroupName $ResourceGroupName - 
                    HostPoolName $HostPoolName -SessionHostName $hostname

                    $activeOrDisconnectedSessions = $hostSessions | Where-Object {$_.SessionState -in 
                    @('Active', 'Disconnected')}

                    if ($activeOrDisconnectedSessions) {
                        Write-Output "Active or disconnected sessions found on VM: $hostname. Skipping..."
                        continue
                    }

                    $powerState = (Get-AvdSessionHostPowerState -HostpoolName $HostPoolName - 
                    ResourceGroupName $ResourceGroupName -Name $hostname).powerstate

                    if ($powerState -eq 'Running') {
                        Write-Output "No active or disconnected sessions found on VM: $hostname. VM is 
                        running. Attempting to stop and deallocate VM: $shortHostname"

                        $stopOperation = Stop-AzVM -ResourceGroupName $ResourceGroupName -Name 
                        $shortHostname -Force
                        if ($stopOperation.Status -eq 'Succeeded') {
                            Write-Output "VM: $shortHostname has been stopped and deallocated 
                            successfully."
                        }
                        else {
                            Write-Output "Failed to stop and deallocate VM: $shortHostname. Reason: 
                            $($stopOperation.Error)"
                        }

                        # Check the power state again after the operation
                        $powerStateAfter = (Get-AvdSessionHostPowerState -HostpoolName $HostPoolName - 
                        ResourceGroupName $ResourceGroupName -Name $hostname).powerstate
                        if ($powerStateAfter -eq 'Deallocated') {
                            Write-Output "$hostname is deallocated"
                            Remove-AvdSessionHost -HostpoolName $HostPoolName -ResourceGroupName 
                            $ResourceGroupName -Name $hostname -DeleteAssociated
                        }
                        else {
                            Write-Output "$hostname is still running"
                        }
                    }
                    elseif ($powerState -eq 'Deallocated') {
                        Write-Output "$hostname is already deallocated"
                        Remove-AvdSessionHost -HostpoolName $HostPoolName -ResourceGroupName 
                        $ResourceGroupName -Name $hostname -DeleteAssociated
                    }
                    else {
                        Write-Output "Unrecognized power state for VM: $hostname"
                    }
                }
Share or Save this:
Share