headless SSD automount

Posted on | 248 words | ~2mins

I have a backup SSD that I keep on my person (even when I don’t have my laptop). This is essentially my use-case for when the laptop dies.

Recently, I’ve moved my restic backups from locally connected to the laptop, to connected via SFTP across to a raspberry pi. This presents an interesting challenge:

backup script:

add it to cron, something like once every */3 hours

#!/bin/bash
source some_env
echo "backup ssd on $(date)" | tee -a restic.log
if [[ -f .lockbackups ]]; then
	echo "not running - locked by other cron" | tee -a restic.log
	exit
fi
# magic folder check:
if ssh user@server '[ ! -d /mnt/ssd/path_to_backup ]'; then
#if [[ ! -d $RESTIC_REPOSITORY ]]; then
	echo "SSD not present" | tee -a restic.log
	exit
fi
touch .lockbackups
restic backup --exclude-if-present .nobackup --exclude-file /etc/restic-exclude / | tee -a restic.log
rm .lockbackups

/etc/systemd/system/mnt-ssd.mount

where $USB is your drive’s name. UUID=$(sudo blkid $(sudo blkid --label $USB) -s UUID -o value)

[Unit]
Description=Automount external SSD

[Mount]
What=/dev/disk/by-uuid/$UUID
Where=/mnt/ssd
Type=auto
Options=defaults,x-systemd.idle-timout=2 # this umounts after 2 minutes
[Install]
WantedBy=multi-user.target

/etc/systemd/system/mnt-ssd.automount

this thing mounts if you use the directory

[Unit]
Description=Automount SSD

[Automount]
Where=/mnt/ssd

[Install]
WantedBy=multi-user.target

/etc/udev/rules.d/99-com.rules

This is done to kill the automount (otherwise systemd will struggle with the drive suddenly missing, or wait for the drive to exist).

KERNEL=="sd[a-z][0-9]", SUBSYSTEMS=="usb", ACTION=="add", RUN+="/bin/systemctl enable --now mnt-ssd.mount mnt-ssd.automount"

KERNEL=="sd[a-z][0-9]", SUBSYSTEMS=="usb", ACTION=="remove", RUN+="/bin/systemctl disable --now mnt-ssd.mount mnt-ssd.automount"

refresh rules

sudo systemctl daemon-reload
sudo systemctl enable mnt-ssd.mount mount-ssd.automount
sudo udevadm control --reload-rules

There.