I followed the exact Microsoft Documentation to attach a Nat Gateway to a subnet however, it does not set it as expected.
$pip = New-AzPublicIpAddress -Name "pip" -ResourceGroupName "natgateway_test" -Location "eastus2" -Sku "Standard" -IdleTimeoutInMinutes 4 -AllocationMethod "static"
$natGateway = New-AzNatGateway -ResourceGroupName "natgateway_test" -Name "nat_gateway" -IdleTimeoutInMinutes 4 -Sku "Standard" -Location "eastus2" -PublicIpAddress $pip
$frontendSubnet = New-AzVirtualNetworkSubnetConfig -Name frontendSubnet -AddressPrefix "10.0.1.0/24"
$virtualNetwork = New-AzVirtualNetwork -Name MyVirtualNetwork -ResourceGroupName TestResourceGroup -Location centralus -AddressPrefix "10.0.0.0/16" -Subnet $frontendSubnet
Set-AzVirtualNetworkSubnetConfig -Name frontendSubnet -VirtualNetwork $virtualNetwork -InputObject $natGateway
$virtualNetwork | Set-AzVirtualNetwork
Link To Microsoft Documentation
is there a workaround for this?. how can I get my existing subnet attached to my Nat Gateway successfully?.
In the command Set-AzVirtualNetworkSubnetConfig -Name frontendSubnet -VirtualNetwork $virtualNetwork -InputObject $natGateway
, the -InputObject
parameter expects a subnet configuration object, not a NAT Gateway object. Passing a NAT Gateway object does not update the subnet’s NatGateway
property and will not attach the NAT Gateway to the subnet.
I followed the approach below and was able to attach the NAT Gateway to the subnet.
# Create Public IP
$pip = New-AzPublicIpAddress -Name "<Public ip name>" `
-ResourceGroupName "<Resource group name>" `
-Location "<Region name>" `
-Sku "Standard" `
-IdleTimeoutInMinutes 4 `
-AllocationMethod "Static"
# Create NAT Gateway
$natGateway = New-AzNatGateway -ResourceGroupName "<Resource group name>" `
-Name "nat_gateway" `
-IdleTimeoutInMinutes 4 `
-Sku "Standard" `
-Location "<Region name>" `
-PublicIpAddress $pip
# Get the existing VNet and Subnet
$virtualNetwork = Get-AzVirtualNetwork -Name "<VNET name>" -ResourceGroupName "<Resource group name>"
$subnet = Get-AzVirtualNetworkSubnetConfig -Name "<Subnet name>" -VirtualNetwork $virtualNetwork
# Attach NAT Gateway to the subnet
$subnet.NatGateway = $natGateway
# Replace the subnet in the VNet's subnet collection
for ($i = 0; $i -lt $virtualNetwork.Subnets.Count; $i++) {
if ($virtualNetwork.Subnets[$i].Name -eq "<Name of sunet>") {
$virtualNetwork.Subnets[$i] = $subnet
}
}
# Push the updated VNet to Azure
Set-AzVirtualNetwork -VirtualNetwork $virtualNetwork
# Output the NAT Gateway ID attached to the subnet
(Get-AzVirtualNetworkSubnetConfig -Name "<Name of sunet>" -VirtualNetwork $virtualNetwork).NatGateway.Id
Output: