When creating Azure Virtual Network with PowerShell, a subnet is not created in the same step and requires an additional command to be executed separately.
Adding a subnet with PowerShell
Getting ready
Before creating a subnet, we need to collect information about the virtual network that the new subnet will be associated with. The parameters that need to be provided are the name of the virtual network and the resource group that the virtual network is located in:
$VirtualNetwork = Get-AzureRmVirtualNetwork -Name 'Packt-Script' -ResourceGroupName 'Packt-Networking-Script'
How to do it...
- To add a subnet to the virtual network, we need to execute a command and provide the name and address prefix. The address prefix is again in CIDR format:
Add-AzureRmVirtualNetworkSubnetConfig -Name FrontEnd -AddressPrefix 10.11.0.0/24 -VirtualNetwork $VirtualNetwork
- We need to confirm these changes by executing the following:
$VirtualNetwork | Set-AzureRmVirtualNetwork
- We can add an additional subnet by running all commands in a single step, as follows:
$VirtualNetwork = Get-AzureRmVirtualNetwork -Name 'Packt-Script' -ResourceGroupName 'Packt-Networking-Script'
Add-AzureRmVirtualNetworkSubnetConfig -Name BackEnd -AddressPrefix 10.11.1.0/24 -VirtualNetwork $VirtualNetwork
$VirtualNetwork | Set-AzureRmVirtualNetwork
How it works...
The subnet is created and added to the virtual network, but we need to confirm the changes before they can become effective. All the rules when creating or adding subnet size using the Azure portal apply here as well; the subnet must be within the virtual network's address space and cannot overlap with other subnets in the virtual network. The smallest subnet allowed is /29, and the largest is /8.
There's more...
We can create and add multiple subnets in a single script, as follows:
$VirtualNetwork = Get-AzureRmVirtualNetwork -Name 'Packt-Script' -ResourceGroupName 'Packt-Networking-Script'
$FrontEnd = Add-AzureRmVirtualNetworkSubnetConfig -Name FrontEnd -AddressPrefix 10.11.0.0/24 -VirtualNetwork $VirtualNetwork
$BackEnd = Add-AzureRmVirtualNetworkSubnetConfig -Name BackEnd -AddressPrefix 10.11.1.0/24 -VirtualNetwork $VirtualNetwork
$VirtualNetwork | Set-AzureRmVirtualNetwork