I recently discovered how to do this for a JASMIN thing, and figured it may be useful.
I would like this script/binary to be run automatically whenever a certain filesystem is mounted.
Use cases:
- You want a quotacheck to be run to create the
aquota.userfile every time a tmpfs is mounted - You want to do something to a block device before it is mounted (e.g mkfs, fsck, unlock with some encryption key)
- ...?
I'm not sure how this would be done without Systemd, perhaps with a very frequent periodic Cron to test if the filesystem is mounted and then execute a thing?
- Configure your mount as normal in fstab, trust that systemd will turn it into an implicit
.mountunit viasystemd-fstab-generator(it just happens with all mounts) - Add the script wherever, probably
/usr/local/sbinor bin. - Add a systemd unit like
do-test-mount.service, see the attached file - this should be installed in /etc/systemd/system - Run
systemctl enable do-test-mount.serviceto have the service linked in the right place (no need to "start" it, because this will be done when the filesystem is mounted)
When you refer to a path/mountpoint in a systemd unit, you have to "escape" it, because you can't have a service named e.g "/var/testmount.service". In that case, you want to use systemd-escape:
- To escape a "path" (like a mountpoint), run
systemd-escape -p /var/testmount, and you will getvar-testmount- this is what you should use in the systemd service unit - To escape something else, drop the
-p(that isn't needed here).
Note that when you refer to var-testmount.mount in the systemd service shown here, the path will always match the mountpoint, it's non-negotiable.
It is possible (albeit optional) to have the filesystem unmounted if the service fails, this relationship is referred to in systemd terms as the mount being "bound by" the the service.
Due to the way systemd ordering works, it is not possible to configure the "bound by" relationship from the mount unit to the service inside the service unit (as you can with the RequiredBy relationship), but you can easily configure it in the .mount unit by creating a file at /etc/systemd/system/var-testmount.mount.d/override.conf using the contents of override.conf in this gist.