How to change media using virsh

If you booted a domain with a cdrom attached you may find that one day you want to change the image attached to this domain with out rebooting it. Libvirt provides a simple command called change-media to do this.

change-media Syntax

virsh # help change-media
  NAME
    change-media - Change media of CD or floppy drive
 
  SYNOPSIS
    change-media <domain> <path> [<source>] [--eject] [--insert] [--update] [--current] [--live] [--config] [--force]
 
  DESCRIPTION
    Change media of CD or floppy drive.
 
  OPTIONS
    [--domain] <string>  domain name, id or uuid
    [--path] <string>  Fully-qualified path or target of disk device
    [--source] <string>  source of the media
    --eject          Eject the media
    --insert         Insert the media
    --update         Update the media
    --current        can be either or both of --live and --config, depends on implementation of hypervisor driver
    --live           alter live configuration of running domain
    --config         alter persistent configuration, effect observed on next boot
    --force          force media insertion

Ejecting the existing media

First lets find the path to the cdrom drive

virsh # domblklist vm1
Target     Source
------------------------------------------------
hda        /dev/storage1/vm1_disk1
hdc        /var/lib/libvirt/images/cd1.iso

In our case the cdrom drive is hdc, now lets eject the ISO thats currently attached to it.

virsh # change-media vm1 hdc --eject
succeeded to complete action eject on media

Lets verify the ISO is no longer attached

virsh # domblklist vm1
Target     Source
------------------------------------------------
hda        /dev/storage1/vm1_disk1
hdc        -

Looks good, the Source for hdc no longer contains the path to the old ISO.

Insert new media

Now we need to insert a new ISO into our cdrom, in our case the cdrom is hdc which we found by running domblklist vm1.

virsh # change-media vm1 hdc /var/lib/libvirt/images/cd2.iso --insert
succeeded to complete action insert on media

And lets check to make sure it's attached

virsh # domblklist vm1
Target     Source
------------------------------------------------
hda        /dev/storage1/vm1_disk1
hdc        /var/lib/libvirt/images/cd2.iso

Success!