Azure PowerShell VM Visualization demo
A Notebook mixing Azure PowerShell and Plotly
Install-Module Az.Compute,Az.Resources -Force
Connect-AzAccount
(Optional) If your account contains more than one active subscription the first one will be selected for further use. To select another subscription, use Set-AzContext.
Set-AzContext -Subscription "My Subscription"
# IMPORTANT VARIABLES
$RESOURCE_GROUP_NAME = 'VMVisDemo'
$LOCATION = 'East US 2'
$NUM_OF_VMs = 10
$USER_CREDENTIAL = Get-Credential
Write-Host "Creting resource group."
New-AzResourceGroup -Name $RESOURCE_GROUP_NAME -Location $LOCATION | Out-Null
Write-Host "Creting VMs."
$jobs = 1..$NUM_OF_VMs | ForEach-Object {
$splat = @{
Image = "UbuntuLTS"
Location = $LOCATION
Name = "MyVM-$_"
ResourceGroupName = $RESOURCE_GROUP_NAME
Credential = $USER_CREDENTIAL
AsJob = $true
}
New-AzVM @splat
}
# Wait for them to all be created
Wait-Job $jobs | Out-Null
"Done!"
Now we need to randomly stop a number of them so that the graph below has some variance.
$numOfVMsToStop = Get-Random -Minimum 2 -Maximum $NUM_OF_VMs
Write-Host "Randomly stoping $numOfVMsToStop VMs."
$vms = Get-AzVM -ResourceGroupName $RESOURCE_GROUP_NAME
$jobs = for ($i = 0; $i -lt $numOfVMsToStop; $i++) {
$vms | Get-Random | Stop-AzVM -Force -AsJob
}
Wait-Job $jobs | Out-Null
Write-Host "Done!"
Cleanup - If you wanna clean up these test VMs. Run this:
Note: This can take a LONG time.
Write-Host "Deleting VMs."
$jobs = Get-AzVM -ResourceGroupName $RESOURCE_GROUP_NAME | Remove-AzVM -AsJob -Force
Wait-Job $jobs | Out-Null
Write-Host "Deleting resource group."
Remove-AzResourceGroup -ResourceGroupName $RESOURCE_GROUP_NAME -Force | Out-Null
Write-Host "Done!"
$vms = Get-AzVM -Status
$data = $vms.PowerState
$groupedData = $data | Group-Object
$groupedData
Now we can render that data into a Pie graph and plot it in a chart:
$trace = [Graph.Pie]@{
name = "VM PowerState"
labels = $groupedData.Name
values = [int[]]($groupedData | % Count)
}
New-PlotlyChart -Title "VM Status" -Trace $trace | Out-Display