如何使用Azure SDK获取Azure VM的公共IP [英] How to get public IP of Azure VM using Azure SDK

查看:74
本文介绍了如何使用Azure SDK获取Azure VM的公共IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于特定的VM,我希望能够检索公共IP地址.

For a specific VM, I want to be able to retrieve the public IP address.

我知道如何获取资源组的所有公共IP地址,我也知道如何获取特定VM的nic-id-但我不知道如何连接两者.

I know how to get all public IP addresses for a resource group, I also know how to get a nic-id for a specific VM - but I can't figure out how to connect the two.

这就是我所拥有的:

var resourceGroupName = "My-Resource-Group";
var vmName = "MyVM";
var subscriptionId = "bzz-bzz-bzz-bzz-bzz-bzz";

var tenantId = "bar-bar-bar-bar-bar-bar";

string clientId = "foo-foo-foo-foo-foo-foo";
string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        
var token = GetAccessTokenAsync(tenantId, clientId, clientSecret);
var credential = new TokenCredentials(token.Result.AccessToken);

var computeManagementClient = new ComputeManagementClient(credential) { SubscriptionId = subscriptionId };

var vmResult = await computeManagementClient.VirtualMachines.GetAsync(resourceGroupName, vmName, InstanceViewTypes.InstanceView);

//Get the NIC ID for the VM: 

foreach (NetworkInterfaceReference nic in vmResult.NetworkProfile.NetworkInterfaces)
        {
            Console.WriteLine("  networkInterface id: " + nic.Id);
        }    

这给了我类似的东西:

/subscriptions/[guid]/resourceGroups/My-Resource-Group/providers/Microsoft.Network/networkInterfaces/myvm123

/subscriptions/[guid]/resourceGroups/My-Resource-Group/providers/Microsoft.Network/networkInterfaces/myvm123

要获取资源组的所有公共IP,我可以这样做:

To get all public IPs for the resource group, I can do this:

using (var client = new NetworkManagementClient(credential))
        {
            client.SubscriptionId = subscriptionId;
            foreach (var publicIpAddress in client.PublicIPAddresses.ListAll())
            {
                Console.WriteLine(publicIpAddress.IpAddress);
            }
}

...但是,检查nic-id和公共ip对象的属性,并没有明显的方法.

...But inspecting the properties of the nic-id and the public ip object, there are no obvious ways to get from one to the other.

如何从nic-id字符串获取该VM/nic的实际公共IP地址?

How do I get from the nic-id string, to the actual public IP address for that VM/nic?

private static async Task<AuthenticationResult> GetAccessTokenAsync(string tenantId, string clientId, string clientSecret)
    {
        var cc = new ClientCredential(clientId, clientSecret);
        var context = new AuthenticationContext($"https://login.windows.net/{tenantId}");
        var token = context.AcquireToken("https://management.azure.com/", cc);

        if (token == null)
        {
            throw new InvalidOperationException("Could not get the token");
        }
        return token;
    }

推荐答案

我找到了一种解决方法.不漂亮,但是可以.

I found a workaround. Not pretty, but it works.

假定您已经从以下对象获得了Microsoft.Azure.Management.Compute.Models.VirtualMachine对象:

It assumes you already have a Microsoft.Azure.Management.Compute.Models.VirtualMachine object from something like this:

VirtualMachine vmResult = await computeManagementClient.VirtualMachines.GetAsync(resourceGroupName, vmName, InstanceViewTypes.InstanceView);

然后,您可以获取第一个NIC,并将其后半部分作为ID:

Then you can take the first NIC, get the last part of that as an ID:

        var firstNic = vmResult.NetworkProfile.NetworkInterfaces.First();

        var nicNameParts = firstNic.Id.Split('/');
        string networkIntefaceName = nicNameParts.Last();

        using (var client = new NetworkManagementClient(credential))
        {
            client.SubscriptionId = subscriptionId;

            string publicNicId = string.Empty;

            //Query ALL Networkinterfaces in the client, and find the one with the matching NIC-name

            var nic = client.NetworkInterfaces.ListAll().FirstOrDefault(x => x.Name == networkIntefaceName);

            if (nic != null)
            {
                //If we find that, we can now use that to find the ID of the PublicIPAddress for said NIC

                publicNicId = nic.IpConfigurations[0].PublicIPAddress.Id;
                //...And when we have that, we can now query all public IP addresses for that specific public Nic ID
                var publicIp = client.PublicIPAddresses.ListAll().FirstOrDefault(x => x.Id == publicNicId);
                if (publicIp != null)
                {
                    vmInfo.PublicIP = publicIp.IpAddress;
                    Console.WriteLine("  public ip: " + publicIp.IpAddress);
                }
                else
                {
                    Console.WriteLine("  public ip: unknown");
                }
            }
        }

是的,它不是超级优雅,可以进行优化等-但它可以工作,所以这是一个开始.:)

Yes, it is not super elegant, it can be optimized etc - but it works, so that's a start. :)

这篇关于如何使用Azure SDK获取Azure VM的公共IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆