Introduction

esxcli is a command line tool that can be used to manage VMware ESXi host. In my opinion it’s a good way to learn more about the inner workings of ESXi and can be used in scripts for automating tasks. In this blog post, I will show you how to use esxcli to add portgroups and vlans to vSwitch0 of an ESXi host.

Configuring Port Groups and VLANs

Let’s take a hypothetical scenario where we have to add approximately 1000 VLANs on vSwitch0. One could use a bash for loop similar to one below in order to create them using esxcli. The for loop would need to be executed from within ESXi server console and will require SSH to be enabled on the ESXi host.

#Loop through 2 to 1001, which will give us VLAN number 2 through 1001
for i in {2..1001}
  do
   # Add a portgroup, with the name pgVLANNUMBER on vSwitch0
   esxcli network vswitch standard portgroup add --portgroup-name=pg$i --vswitch-name=vSwitch0
   # Set the portgroups VLAN to VLAN Number
   esxcli network vswitch standard portgroup set -p pg$i --vlan-id $i
done

If your ESXi server is not fast enough or if you are trying to do this in nested virtualization environment, I have found that you will need to add a sleep between commands so that port groups can be added. Addition to the for loop are highlighted below.

#Loop through 2 to 1001, which will give us VLAN number 2 through 1001
for i in {2..1001}
  do
   # Add a portgroup, with the name pgVLANNUMBER on vSwitch0
   esxcli network vswitch standard portgroup add --portgroup-name=pg$i --vswitch-name=vSwitch0
   # Set the portgroups VLAN to VLAN Number
   esxcli network vswitch standard portgroup set -p pg$i --vlan-id $i
   # Add a sleep of three seconds
   sleep 3
done
print