How can I use LVM snapshots in Ubuntu?
Note: all commands should be done from sudo
First, reduce size of your root volume to make some room for a snapshot volume
- Boot from Live CD
-
fdisk -l
to see name of your device.Device Start End Sectors Size Type /dev/sda1 2048 1050623 1048576 512M EFI System /dev/sda2 1050624 2050047 999424 488M Linux filesystem /dev/sda3 2050048 500117503 498067456 237.5G Linux filesystem
/dev/sda3
in my case -
cryptsetup luksOpen /dev/sda3 crypt1
to decrypt your volume -
vgscan --mknodes
to find all volume groupsReading all physical volumes. This may take a while... Found volume group "ubuntu-vg" using metadata type lvm2
-
vgchange -ay
to activate all your volume groups2 logical volume(s) in volume group "ubuntu-vg" now active
-
lvreduce -r -L -20G /dev/ubuntu-vg/root
to reduce size of your root volume by 20 Gb. This may take a while (it took ~4 min for me).
That space will later be used to create LVM snapshots. -
vgs
to see that you actually got 20G of free spaceVG #PV #LV #SN Attr VSize VFree ubuntu-vg 1 2 0 wz--n- 230.44g 20.01g
-
reboot
and remove Live CD
Create a snapshot (i.e., activate "experimentation" mode)
Now whenever you want to do something risky with your system, run the following command
-
lvcreate -s -n snap -L 20G /dev/ubuntu-vg/root
Note:/dev/ubuntu-vg/root
is a logical volume that you want to have a snapshot of -
lvs
to see that the volume has been createdLV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert root ubuntu-vg owi-aos--- 201.59g snap ubuntu-vg swi-a-s--- 20.00g root 0.00 swap_1 ubuntu-vg -wi-ao---- 15.90g
The snapshot is active from the moment you runlvcreate
. You can now start experimenting with new things.
Scenario #1: You want to revert changes
-
lvconvert --merge /dev/mapper/ubuntu--vg-snap
Logical volume ubuntu-vg/root contains a filesystem in use. Can't merge over open origin volume. Merging of snapshot ubuntu-vg/snap will occur on next activation of ubuntu-vg/root.
reboot
Scenario #2: You want to persist changes
lvremove /dev/mapper/ubuntu--vg-snap
In Conclusion
You basically have to run lvcreate
to start the process and then either run lvconvert --merge
or lvremove
to end it.
Keep in mind that when the snapshot is active, due to Copy-On-Write strategy all the changes are saved to those 20Gb of space (or whatever value you set).
One way of checking the remaining capacity is to look at Data% column of lvs
command.