针对特定的虚拟机,我希望能够检索公共 IP 地址。
我知道如何获取资源组中所有公共 IP 地址,也知道如何获取特定虚拟机的 nic-id,但是我无法将两者连接起来。
这是我的代码:
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);
}
这使我得到类似于这样的东西:
要获取资源组的所有公共IP,我可以这样做:/subscriptions/[guid]/resourceGroups/My-Resource-Group/providers/Microsoft.Network/networkInterfaces/myvm123
using (var client = new NetworkManagementClient(credential))
{
client.SubscriptionId = subscriptionId;
foreach (var publicIpAddress in client.PublicIPAddresses.ListAll())
{
Console.WriteLine(publicIpAddress.IpAddress);
}
}
然而,检查nic-id和public ip对象的属性,没有明显的方法可以从一个对象获取另一个对象。
问题:
如何从nic-id字符串获取到VM/nic的实际公共IP地址?
辅助函数:
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;
}