如何在 Azure 负载均衡器入站 NAT 规则上替换目标 VM 和 NIC

How to replace target VM and NIC on Azure Load Balancer Inbound NAT Rule

我有一个具有入站 NAT 规则的现有 Azure 前端负载均衡器。我想把那些 NAT 规则的 target/destination 批量更改到新的目标服务器。

我目前构建了一个脚本,它从 LB 获取所有 NAT 规则,然后遍历它们并尝试将它们添加到新服务器的 NIC。我尝试过使用和不使用从旧服务器的 NIC 中删除 NAT 规则。无论哪种方式,方法 returns false 并且不应用任何更改。

#Set Variables
#subscription ID
$subscription = "value"
#the name of the old NIC that has the LB rules
$OldNicName = "old_nic"
#the name of the NIC to be attached to the LB rules
$NewNicName = "new_nic"
#name of the loadbalancer
$lbname = "my_lb"

#Set Active Subscription
Set-AzContext -SubscriptionId $subscription

#Get the loadbalancer
$lb = Get-AzLoadBalancer -Name $lbname

#Get the old firewall interface/NIC
$OldNic = Get-AzNetworkInterface -Name $OldNicName

#Get the target firewall interface/NIC
$NewNic = Get-AzNetworkInterface -Name $NewNicName

#Attach NAT rules to the NIC
$lb.InboundNatRules | ForEach-Object -Process {$OldNic.IpConfigurations[0].LoadBalancerInboundNatRules.Remove($_); $NewNic.IpConfigurations[0].LoadBalancerInboundNatRules.Add($_)}

#Apply the configuration and reload the NIC
$OldNic | Set-AzNetworkInterface
$NewNic | Set-AzNetworkInterface

我希望每个入站 NAT 规则现在都关联到新的 NIC/VM,但目前上面的 Remove() 和 Add() 函数都返回 FALSE。

对于您的问题,您想将这些 NAT 规则的 target/destination 批量更改为新的目标服务器。与 VM 网络接口关联并在接口 IP 配置中设置的 NAT 规则。所以你需要使用Set-AzNetworkInterfaceIpConfigSet-AzNetworkInterface这两个PowerShell命令来达到你的目的。脚本如下:

# Set Variables
# subscription ID
$subscription = "value"
# the name of the old NIC that has the LB rules
$OldNicName = "old_nic"
# the name of the NIC to be attached to the LB rules
$NewNicName = "new_nic"
# name of the loadbalancer
$lbname = "my_lb"
# assume all the resources in the same group
$groupname = "group_name"

Set-AzContext -SubscriptionId $subscription

# remove the NAT rules from the old NIC
$oldNic = Get-AzNetworkInterface -ResourceGroupName $groupname -Name $OldNicName
$list = @()       # this is a empty array
Set-AzNetworkInterfaceIpConfig -Name ipconfig1 -NetworkInterface $oldNic -LoadBalancerInboundNatRule $list 
$oldNic | Set-AzNetworkInterface

# associate the NAT rules to the new NIC

$newNic = Get-AzNetworkInterface -ResourceGroupName $groupname -Name $NewNicName
$lb = Get-AzLoadBalancer -ResourceGroupName $groupname -Name $lbname
$NatRules = Get-AzLoadBalancerInboundNatRuleConfig -LoadBalancer $lb
Set-AzNetworkInterfaceIpConfig -Name ipconfig1 -NetworkInterface $newNic -LoadBalancerInboundNatRule $NatRules
$newNic | Set-AzNetworkInterface