我正在研究如何使用 Azure .NET SDK 从属于 Azure 虚拟机的网络接口中分离出一个公有 IP 对象的例子。
我们的想法是在虚拟机被deallocated时删除公有IP,这样我们就不会不必要地消耗公有IP配额。
Azure网络接口有一些IP配置。每个IP配置都有一个公共IP地址。所以,如果我们想从Azure网络接口中脱离公有IP,我们只需要从IP配置中删除公有IP即可。详情请参考 文件
关于如何在Net中实现,我们可以使用sdk .NET的Azure管理库. 具体步骤如下
a. 创建一个服务委托人(我使用Azure CLI来做)。
az login
az account set --subscription "<your subscription id>"
# the sp will have Azure Contributor role
az ad sp create-for-rbac -n "readMetric"
AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
clientId, // the sp appId
clientSecret, // the sp password
tenantId, // the sp tenant
AzureEnvironment.AzureGlobalCloud);
var azure = Microsoft.Azure.Management.Fluent.Azure.Configure()
.Authenticate(credentials)
.WithSubscription(subscriptionId);// the subscription you use
var resourceGroupName = "testapi06"; // the vm resource group name
var vmName = "testvs";// the vm name
//get the Azure VM
var vm =await azure.VirtualMachines.GetByResourceGroupAsync(resourceGroupName, vmName);
// get Azure VM's network interfaces
foreach (var nicId in vm.NetworkInterfaceIds) {
var nic = await azure.NetworkInterfaces.GetByIdAsync(nicId);
// get network interface's ip configurations
foreach (var r in nic.IPConfigurations)
{
var ipConfigNmae = r.Key;
// detach a Public IP object from network interface
await nic.Update().UpdateIPConfiguration(ipConfigNmae)
.WithoutPublicIPAddress()
.Parent()
.ApplyAsync();
// delete public ip
var publicIpId = r.Value.GetPublicIPAddress().Id;
await azure.PublicIPAddresses.DeleteByIdAsync(publicIpId);
};
};