Create NEW VM on EXISTING Subnet with Azure CLI

A common mistake I see with sysadmins trying to create new VMs on existing subnets from the Azure CLI. One would think that specifying the existing VNET name and subnet name, as shown below, would do the job.

az vm create -n MyVm /
-g MyResourceGroup /
--image debian /
--vnet-name MyVnet /
--subnet subnet1

While it seems logical this should work, it actually results in a new VNET and subnet being created along with the new VM! Unfortunately, the Azure CLI documentation does not make this clear enough for many new users.

How to get it done

If you want to attach a VM to an existing subnet, you need to pass the subnet ID to the –subnet parameter. Begin by retrieving the ID of the existing subnet and assign to a variable.

In this sample, the subnet is named ‘default’, and represented by the –name parameter, and SUBNETID is the name of the variable.

export SUBNETID=$(az network vnet subnet show /
--resource-group 'MyRG' --name default /
--vnet-name 'Existing-VNET' --query id -o tsv)

Then, when you create the VM, you’ll notice that for the –subnet parameter, we specify the variable that holds the subnet ID (line 5 below). The VNET is not mentioned, as it’s contained within the subnet ID.

az vm create /
--resource-group "$RES_GRP" /
--name "$SVR_NAME" /
--image "$SKU" /
--subnet "$SUBNETID" /
--data-disk-sizes-gb 10 10 /
--public-ip-address-dns-name "$SVR_NAME" /
--admin-username "$ADMIN_USER" /
--admin-password "$ADMIN_PW"

I hope this helps. You can find Azure CLI documentation, including syntax and examples at https://docs.microsoft.com/en-us/cli/azure/vm?view=azure-cli-latest#az-vm-create.

Print Friendly, PDF & Email

Leave a Reply