如何使用Azure SDK获得VM Public IP?

时间:2018-12-17 23:52:54

标签: c# azure

我正在使用Microsoft.Azure.Compute.Fluent sdk列出我的所有VM,并且工作正常,但我无法获得公共IP地址:

    IVirtualMachines _client = azure.VirtualMachines; 
    var list = await _client.ListAsync();

    foreach (var instance in list)
    {
        var name = instance.Name;
        var ip = instance.GetPrimaryPublicIPAddress().IPAddress;
        //ip = null here;
    }

好吧,我尝试了其他方法,但始终将公共IP设置为null。

如何正确检索公共IP?

1 个答案:

答案 0 :(得分:0)

如果我对您有误解,请纠正我:我找不到sdk Microsoft.Azure.Compute.Fluent (以下截图):

enter image description here

因此,我改用此sdk Microsoft.Azure.Management.Fluent official doc也使用它)。 ip可以在我这边获取,代码为打击:

using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using System;
using System.Threading.Tasks;

namespace myVMDotnetProject
{
    class Program
    {
        static void Main(string[] args)
        {
            GetVMInfo();

            Console.WriteLine("okok");
            Console.ReadLine();
        }


        static async Task  GetVMInfo()
        {
            var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION", EnvironmentVariableTarget.User));

            var azure = Azure
                .Configure()
                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                .Authenticate(credentials)
                .WithDefaultSubscription();

            IVirtualMachines _client = azure.VirtualMachines;
            var list = await _client.ListAsync();

            foreach (var instance in list)
            {
                var name = instance.Name;
                var ip = instance.GetPrimaryPublicIPAddress().IPAddress;
                Console.WriteLine("name: " + name + ", ip: " + ip);
            }
        }

    }
}

测试结果如下:

enter image description here