'Azure: Error while using Azure virtual network, It says subnet is not valid in virtual network

$rg1="firstyear-rg-01"
$loc="eastasia"

New-AzResourceGroup -name $rg1 -location $loc
$ec1 = New-AzVirtualNetworkSubnetConfig -Name "ec-lab-sn-01" -AddressPrefix "10.0.0.0/27"
$cs1 = New-AzVirtualNetworkSubnetConfig -Name "cs-lab-sn-01"  -AddressPrefix "10.0.1.0/27"
$it1 = New-AzVirtualNetworkSubnetConfig -Name "it-lab-sn-01" -AddressPrefix "10.0.2.0/27"
$mc1 = New-AzVirtualNetworkSubnetConfig -Name "mech-lab-sn-01"  -AddressPrefix "10.0.3.0/27"
$vn1 = New-AzVirtualNetwork -Name "firstyear-vn-01" -ResourceGroupName $rg1 -Location $loc -AddressPrefix "10.0.0.0/25" -Subnet $ec1,$cs1,$it1,$mc1

The above is the exact code I tried, but it gives error:

New-AzVirtualNetwork: Subnet 'cs-lab-sn-01' is not valid in virtual network 'firstyear-vn-01'. StatusCode: 400 ReasonPhrase: Bad Request ErrorCode: NetcfgInvalidSubnet ErrorMessage: Subnet 'cs-lab-sn-01' is not valid in virtual network 'firstyear-vn-01'. OperationID : c5bd59de-a637-45ec-99a7-358372184e98

What am I doing wrong?



Solution 1:[1]

If you are using a virtual network with an address range 10.0.0.0/25, the subnet AddressPrefix should be included in that virtual network. You can assign subnets to address prefixed like 10.0.0.0/27, 10.0.0.32/27, 10.0.0.64/27, 10.0.0.96/27 according to the IP Calculator.

enter image description here

Solution 2:[2]

I ran into this issue when setting up a subnet in Azure using Terraform.

When I run terraform apply, I get the error below:

module.subnet_private_1.azurerm_subnet.subnet: Creating...
?
? Error: creating Subnet: (Name "my-private-1-dev-subnet" / Virtual Network Name "my-dev-vnet" / Resource Group "MyDevRG"): network.SubnetsClient#CreateOrUpdate: Failure sending request: StatusCode=0 -- Original Error: Code="NetcfgInvalidSubnet" Message="Subnet 'my-private-1-dev-subnet' is not valid in virtual network 'my-dev-vnet'." Details=[]
? 
?   with module.subnet_private_1.azurerm_subnet.subnet,
?   on ../../../modules/azure/subnet/main.tf line 1, in resource "azurerm_subnet" "subnet":
?    1: resource "azurerm_subnet" "subnet" {

Here's how I fixed it:

The issue was that I was assignining subnet_address_prefixes that were already assinged to a subnet to the new subnet.

I had already assinged ["10.1.1.0/24"] to an already existing subnet, and I made a mistake in my module to assign it again to the new subnet that I was creating.

All I had to do was to use a different subnet_address_prefixes, which is ["10.1.2.0/24"] and everything worked fine.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nancy Xiong
Solution 2 halfer