Automount usb devices with systemd
Ever since udisk-glue was obsoleted with udisk (the first generation), I’ve been struggling to find a solution to automatically mount a usb drive when such a device is connected to a kodi based home cinema PC. I wanted to avoid writing dedicated scripts or udev rules. Systemd is quite powerful and I thought that a simple solution should be possible using systemd configuration.
Actually, auto-mount notion covers 2 scenario :
- A device is mounted after being plugged in
- An already available device is mounted when a process accesses its mount point
The first case is the one that is needed with Kodi. The second may be usefull so is also documented in this post.
For the first case, add a line like the following in /etc/fstab:
/dev/sr0 /mnt/br auto defaults,noatime,auto,nofail 0 2
and reload systemd configuration:
sudo systemctl daemon-reload
The important parameters are “auto” and “nofail”: with “auto”, systemd mounts the filesystem as soon as the device is available. This behavior is different from sysvinit where “auto” is taken into account only when “mount -a” is run by init scripts. “nofail” ensures that boot does not fail when the device is not available.
The second case is handled by a line like the following one (even if the line is split here to improve readability):
/dev/sr0 /mnt/br auto defaults,x-systemd.automount,\ x-systemd.device-timeout=5,noatime,noauto 0 2
With the line above in /etc/fstab, the file system is mounted when user does (for instance) “ls /mnt/br” (actually, the first “ls” fails and triggers the mount. A second “ls” gives the expected result. There’s probably a way to improve this behavior, but I’ve not found it…)
“x-systemd.*” parameters are documented in systemd.mount(5).
Last but not least, using a plain device file (like /dev/sr0) works fine to automount optical devices. But it is difficult to predict the name of a device file created for a usb drive, so a LABEL or a UUID should be used in /etc/fstab instead of a plain device file. I.e. something like:
LABEL=my_usb_drive /mnt/my-drive auto defaults,auto,nofail 0 2
All the best