Yes, you can indeed combine the use of systemd units to mount a block device when detected with parameterized unit files. Systemd supports instantiating units, which allows you to pass parameters to unit files. This is particularly useful for mounting devices dynamically based on their UUID or any other identifying parameter. Here's how you can set this up:
-
Create a Parameterized Unit File: You need to create a systemd mount unit file that can take the UUID as a parameter. This file should be named following the pattern
extdrive@.mount
. Place this file under/etc/systemd/system/
.Here's an example of what the content might look like:
[Unit] Description=Mount External Drive at %i Requires=local-fs.target After=local-fs.target [Mount] What=/dev/disk/by-uuid/%i Where=/mnt/%i Type=auto Options=defaults [Install] WantedBy=multi-user.target
In this unit file,
%i
will be replaced by the parameter you pass when you start or enable the unit. This parameter should be the UUID of the device. -
Create a Path Unit to Monitor Device Connection: You might also want to create a systemd path unit to automatically mount the drive when it's connected. This can be achieved by creating a
.path
unit that monitors the appearance of the device node.Here's a simple path unit example that you could place alongside your mount unit in
/etc/systemd/system/
namedextdrive@.path
:[Unit] Description=Watch for External Drive at UUID %i [Path] PathExists=/dev/disk/by-uuid/%i Unit=extdrive@%i.mount [Install] WantedBy=multi-user.target
-
Enable and Start the Path Unit: Once these units are in place, you can enable the
.path
unit so that it starts at boot time and will start the.mount
unit whenever the drive is connected.sudo systemctl enable extdrive@2504a5a6-e006-4f96-a330-f432dc82b8be.path sudo systemctl start extdrive@2504a5a6-e006-4f96-a330-f432dc82b8be.path
-
Testing: After setting up the units, you can test by connecting the drive and checking if it mounts automatically. You can check the status of your units using:
sudo systemctl status extdrive@2504a5a6-e006-4f96-a330-f432dc82b8be.mount sudo systemctl status extdrive@2504a5a6-e006-4f96-a330-f432dc82b8be.path
This setup uses systemd's ability to create template units that are instantiated at runtime, providing a powerful and flexible way to handle dynamic system states such as device connections. This approach keeps your system configuration clean and avoids the need for custom scripts or manual intervention each time a new device is connected.
had a few times recently, when a drive that auto mounts in fstab wasn't present on reboot... causing a boot fail. This would get around it... and also auto mount after boot time...