I am attempting to get a list of VMSS that have a specific tag and are still powered/allocated and then deallocate those VMSS.
I have not seen a property in Get-AzVmss
that shows the allocation or power state of the VMSS.
I did however find if I dig in to the instances themselves I can get the powerstate of them using Get-AzVmssVM
I am able to successfully get this to occur at the instance level and power the instances off, but I would like to deallocate the VMSS itself.
This will be part of a DevOps deployment pipeline so I need to ensure it's reliable and consistent. It will be run as an Azure Powershell Task.
Anyone able to assist in what I am missing here? I would love to do this a layer up and not even get in to the instances, but I could not see how to do that (assuming it is possible).
Here is the code I have so far:
$RedTagValue = "Red"
$RGName = "test-rg"
$Resources = Get-AzVmss -ResourceGroupName $RGName | Where-Object { $_.Tags.Values -eq $RedTagValue }
foreach ($Resource in $Resources) {
$vmss = Get-AzVmssVM -ResourceGroupName $RGName -VMScaleSetName $Resource.Name
foreach ($vm in $vmss) {
$instances = Get-AzVmssVM -ResourceGroupName $RGName -VMScaleSetName $Resource.Name -InstanceId $vm.InstanceId -InstanceView
if ($instances.Statuses[1].Code -notcontains "PowerState/deallocated") {
Write-Output "Turning off" #Need some code here to output the VMSS that are being turned off and also some logic to turn them off
}
else {
Write-Output "No Machines to turn Off"
}
}
}
CodePudding user response:
Stop-AzVmss -ResourceGroupName $RGName -VMScaleSetName $Resource.Name -InstanceId $vm.InstanceId -Force
You need add the above stop-azvmss
cmdlet in the If
block in your script to stop a particular vmss instance.
Instead of Hardcoding the ResourcegroupName in your script, we have made some changes to it.
This new Script will validate the instance status whether are running or not. if instance are in running state then the script will trigger stop-azvmss
cmdlets to deallocate those instance.
Here is the Modified PowerShell Script :
$RedTagValue = "Red"
$Resources = Get-AzVmss| Where-Object { $_.Tags.Values -eq $RedTagValue }
foreach ($Resource in $Resources) {
$vmss = Get-AzVmssVM -ResourceGroupName $Resources.ResourceGroupName -VMScaleSetName $Resource.Name
foreach($vm in $vmss){
$instanceId=Get-AzVmssVM -ResourceGroupName $Resources.ResourceGroupName -VMScaleSetName $Resource.Name -InstanceId $vm.InstanceId -InstanceView
if($instanceId.Statuses[1].Code -eq 'PowerState/running'){
Write-Host "Turnning OFF","$($vm.Name)"
Stop-AzVmss -ResourceGroupName $Resources.ResourceGroupName -VMScaleSetName $Resource.Name -InstanceId $vm.InstanceId -Force
}
else {
Write-Host "$($Resource.Name)","Virtual Machines are already turned off"
}
}
}
Here is the sample Output for reference: