繁体   English   中英

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

[英]How to get vm public ip with azure sdk?

我使用Microsoft.Azure.Compute.Fluent sdk列出了我所有的虚拟机,并且工作正常,但我无法获得公共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?

如果我误解了您,请纠正我:我找不到sdk Microsoft.Azure.Compute.Fluent (如下图所示):

在此处输入图片说明

所以我改为使用此sdk Microsoft.Azure.Management.Fluent官方文档也使用它)。 可以在我这边获取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);
            }
        }

    }
}

测试结果如下:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM