0

I want to list all VMs in a Scale Set and print the VM name, and private and public IP using the C# management SDK. Sofar I have the following code:

using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Compute;

var armClient = new ArmClient(new DefaultAzureCredential());
var scaleSet = armClient.GetVirtualMachineScaleSetResource("/long/id");

Console.WriteLine("vms:");
await foreach (var vm in ss.GetVirtualMachineScaleSetVms().GetAllAsync())
{
  Console.WriteLine($"  vm: {vm.Id.Name}");
}

The above code works and prints -- as expected -- the list of vms in my scaleset:

vms:
  vm: fleet-a_90f4de84
  vm: fleet-a_c439ee3c

However, I cannot figure out how to get the network information from here.

I expected to find it in vm.Data.NetworkProfile or vm.Data.NetworkInterfaceConfigurations[]. but even though vm.HasData is true, vm.Data has all fields set to null (and vm.Data.NetworkInterfaceConfigurations[] is empty):

vm.Data screenshot

mauve
  • 1,976
  • 12
  • 18

1 Answers1

1

Using ARM client methods, I have tried to reproduce the code to retrieve network interface ip configuration(private and public ips) for the VMs, but I could only fetch Network Interface.

By using ARM client classes in C# management SDK, as you are able to get the list of vms in your scale set, you can also fetch the Network Interface using the below code:

var networkInterfaceReference = vm.Data.NetworkProfile.NetworkInterfaces[0].Id.Name;

By using the list of VMs and Network Interface, you can use alternate method to fetch the ip details.

Thanks to @sridank. By referring to this SO thread, I have followed below alternative code to get the IP addresses of VMs programmatically.

Follow the below method to fetch ip details of vm:

  1. To establish the authentication:
var authContext = new AuthenticationContext("https://login.windows.net/{YourTenantId}");
var credential = new ClientCredential("{YourAppID}", "{YourAppSecret}");
var result = authContext.AcquireTokenAsync("https://management.core.windows.net/", credential);

result.Wait();
if (result.Result == null)
    throw new AuthenticationException("Failed to obtain the JWT token");

credentials = new TokenCredentials(result.Result.AccessToken);
  1. Code to get the ip details:
string subscriptionId = "XXXXXXXX";  
string resourceGroupName = "XXXXX";  
string vmName = "XXXXXXXXX";
using (var client = new ComputeManagementClient(credentials))  
{  
client.SubscriptionId = subscriptionId;
VirtualMachine vm = VirtualMachinesOperationsExtensions.Get(client.VirtualMachines, resourceGroup, vmName);
networkName = vm.NetworkProfile.NetworkInterfaces[0].Id.Split('/').Last();  
}
using (var client = new NetworkManagementClient(credentials))  
{  
client.SubscriptionId = subId;  
var network = NetworkInterfacesOperationsExtensions.Get(client.NetworkInterfaces, resourceGroupName, vmName);  
string ip = network.IpConfigurations[0].PrivateIPAddress;  
}
Pravallika KV
  • 2,415
  • 2
  • 2
  • 7