QM Create using the next available VMID? (CLI)

nmiller0113

Active Member
Aug 23, 2012
16
1
43
I do most of my creation/cloning of VMs from the CLI and with Ansible. I was wondering if there was a way to I don't have to explicitly define the new vmid. When working in the WebUI it will always suggest the next vmid to use, so I was wondering if there was a way to take advantage of that logic in the CLI and not have to define it each time I create/clone a VM? I'm hoping I'm just missing something and there is a way that to make it automatically use the next available from the CLI. Thanks!
 
  • Like
Reactions: nmiller0113
I use the following snippet to calculate the next available id:

# List all the existing VM IDs in-use
head="VMID"
idlist=$(qm list | awk '{print $1}' | awk -v val="$head" '$1 != val {print}' | sort)

# Query the last ID among these
lastid=$(echo ${idlist} | awk '{print $NF}')

# Increment it to get the next available ID
newid=$(expr ${lastid} \+ 1)

You may additionally check for boundaries (like $newid > 999999999).
 
Last edited:
# List all the existing VM IDs in-use
idlist=$(qm list | awk '{print $1}' | awk -v val="$head" '$1 != val {print}' | sort)
Keep in mind that qm will list VMs on the server you run the command on. Will not list VMs on other nodes of your cluster. IMHO, it's a lot easier to just use newId="$(pvesh get /cluster/nextid)" as it will check all IDs in the cluster.
 
If you just need what proxmox would give out next,
Code:
pvesh get /cluster/nextid
is fine.

I use this:
Code:
export NEXT_ID=$(( $(ls -1 /etc/pve/nodes/*/{qemu-server,lxc}/* 2>/dev/null \
  | sed 's#.*/##; s/\..*$//' \
  | sort -n \
  | tail -1 \
  || echo $(( $(pvesh get /cluster/nextid) - 1 )) ) + 1 ))

# After this, you can use $NEXT_ID in your script:
echo $NEXT_ID
because it will NOT fill in-between after you may have deleted a vm/lxc and an Id became available.
I want increasing Ids so I dont get ID collisions in my backup server.

This will always look for the highest id (lxc+vm) and add 1. If you dont have any vm/lxc it will fallback to get /cluster/nextid but will add 1 to it too. (for me 251000 is the defined prefix, so i want vms start with 251001 for example.

my code runs on single-nodes as on clusters.
 
Last edited: