27

How can I rename a VM on KVM+libvirt?

I would like it to change the name in the 'inventory' as well as change the name of the storage etc.

Arthur Ulfeldt
  • 3,219
  • 9
  • 31
  • 40

5 Answers5

20

run

virsh dumpxml name_of_vm > name_of_vm.xml

Undefine the old vm to prevent an error because of an duplicate UUID.

virsh undefine name-of-vm

Edit the xml file then import it.

virsh define name_of_vm.xml

Of course you will have to stop and start the vm for the changes to take effect

virsh destroy name_of_vm
virsh start name_of_vm
Nebel54
  • 103
  • 3
topdog
  • 3,490
  • 16
  • 13
16
virsh dumpxml myvm > foo.xml
<edit foo.xml, change the name, move storage>
virsh undefine myvm
virsh define foo.xml

Source: https://www.redhat.com/archives/libvirt-users/2010-October/msg00072.html

blueyed
  • 723
  • 8
  • 13
15

virsh implemented domrename in release 1.2.19: Sep 02 2015. So the current best practice is just:

 virsh domrename oldname newname

As you might expect, thedomain must be stopped, but also it cannot have any snapshots.

reedstrm
  • 251
  • 2
  • 5
  • +1 - you can `virsh edit newname` and change the file path and `mv oldname newname` to rename the directory if you want everything to match. – Dennis Williamson Oct 26 '16 at 18:36
  • in other words, you also have to 1) rename /var/lib/libvirt/images/oldname.qcow2 in /var/lib/libvirt/images/newname.qcow2 ; and 2) edit /etc/libvirt/qemu/newname.xml to set the correct source file balise – MaxiReglisse Jun 28 '19 at 13:44
  • but only if you need the filenames to match the domainnames (which I admit, is convenient) - this avoids a destroy/create cycle, though still requires a stop (and no snapshots) – reedstrm Jul 01 '19 at 20:24
5

To change many machines you can use this:

virsh shutdown old-name

Wait for above to finish and run:

virsh dumpxml old-name > old-name.xml
virsh undefine old-name

Wait for above to finish and run:

sed -i 's/<name>old-name<\/name>/<name>new-name<\/name>/g' old-name.xml
virsh define old-name.xml

Run this one-by-one for each machine. You can use this RegExp if you have a list containing old-name new-name:

([^\r\n]+?)[ \t]+([^\r\n]+)
virsh shutdown $1\n#WAIT!\nvirsh dumpxml $1 > $1.xml\nvirsh undefine $1\n\#WAIT!\nsed -i 's/<name>$1<\\/name>/<name>$2<\\/name>/g' $1.xml\nvirsh define $1.xml\n
Nux
  • 541
  • 3
  • 12
  • 21
0

I do it little differently and may be un-recommended method (not sure).

virsh destroy old-vm virsh edit old-vm

In the XML change

  1. domain name old-vm to new-vm
  2. change a char/digit in UUID save and exit.

virsh list --all

1 old-vm shut-off

2 new-vm shut-off

Now undefine the old-vm

virsh undefine old-vm

Jay
  • 101
  • 1