Ubuntu – How to automatically create a Btrfs Snapshot before updating the system

automationbtrfsscriptssnapshotupdates

I've installed Ubuntu 20.04 on a Btrfs root-partition for its snapshot functionality.

To keep it as simple as possible, I would like to integrate the creation of a Btrfs snapshot into my upgrade-alias command, which currently looks like this:

sudo apt update && sudo apt upgrade -y && sudo flatpak update -y && sudo snap refresh

How would I best add a snapshot before the updates so I can roll back if anything goes wrong?

Is there also a possiblity to remove older snapshots at the same time? (My root-partition is filled less than 10%, so I could copy my entire system multiple times, but I suppose it will fill up quickly with weekly updates?)

Best Answer

It is quite easy to make a snapshot in btrfs.

First mount your partitition containing the btrfs filesystem to e.g. /mnt. We are assuming it is /dev/sda1.

sudo mount /dev/sda1 /mnt
cd /mnt

If you have a standard Ubuntu install with / at @ and /home at @home, running ls will show two items: @ and @home.

Also if you previosly created snapshots, they will be shown there too.

To create snapshots of your / and /home , run the command:

sudo btrfs sub snap @ @-BACKUP && sudo btrfs sub snap @home @home-BACKUP

If you want to remove existing backups before you create a new one the command will be:

sudo btrfs sub del @-BACKUP && sudo btrfs sub del @home-BACKUP

As simple as that.

After you finish with that unmount your partition from /mnt by:

sudo umount /mnt

In addition I can add that you can create snapshots with timestamp or do incremental backups. But it is a bit out of scope of the question.

You can combine these commands into a text file like backup.sh.

Example:

#!/bin/sh
mount /dev/sda1 /mnt
cd /mnt
[ -d @-BACKUP ] && sudo btrfs sub del @-BACKUP #Checks is backup exists and deletes it
[ -d @home-BACKUP ] && sudo btrfs sub del @home-BACKUP
btrfs sub snap @ @-BACKUP
btrfs sub snap @home @home-BACKUP
cd /
umount /mnt

The script should be run with sudo.

Related Question