I want to get the PowerState (on/off/restarting, etc.) of a known Azure VM instance in a C#/dotnet application using Azure.ResourceManager (not PowerShell, not CLI, not REST, not using any deprecated Fluent approach).
I can do it successfully with REST so I know the underlying VM InstanceView data exists, but for this application REST will not pass muster.
I am using the following code; vm.Data.Name comes back as expected, but am getting null responses from InstanceView.Statuses.
I haven’t been able to find any helpful MSFT documentation, except for old, deprecated approaches.
Does anyone know how to get PowerState via Azure.ResourceManager, or why I am getting NULL back?
Thanks!!
[code sample updated below on 1/16/23, changed auth approach, InstanceView still returning NULL]
using Azure;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Compute;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Resources;
namespace Test
{
public class Program
{
public static async Task ListAllVms()
{
ArmClient armClient = new ArmClient(new DefaultAzureCredential());
SubscriptionResource subscription = await armClient.GetDefaultSubscriptionAsync();
string rgName = "redacted";
ResourceGroupResource resourceGroup = await subscription.GetResourceGroups().GetAsync(rgName);
VirtualMachineCollection vmCollection = resourceGroup.GetVirtualMachines();
AsyncPageable<VirtualMachineResource> response = vmCollection.GetAllAsync();
await foreach (VirtualMachineResource vm in response)
{
Console.WriteLine(vm.Data.Name);
foreach (InstanceViewStatus istat in vm.Data.InstanceView.Statuses)
{
Console.WriteLine("n code: " + istat.Code);
Console.WriteLine(" level: " + istat.Level);
Console.WriteLine(" displayStatus: " + istat.DisplayStatus);
}
}
}
public static async Task Main(string[] args)
{
await ListAllVms();
}
}
}
2
Answers
After reproducing from my end, I could able to achieve this using
vm.Get().Value.InstanceView().Value.Statuses[1].DisplayStatus
. Below is the complete code that worked for me where I list all the vm present in my resource group and get the statuses of it.output:
Accepted answer above was almost there but for me I had to change the code to:
vm.Get(InstanceViewType.InstanceView).Value.Data.InstanceView.Statuses[1].DisplayStatus
Hope that helps someone.