Systemd is the init system used in Ubuntu and several other Linux distributions. It is used to bootstrap the user space and manage all subsequent processes. In addition to its primary function of initializing the system, systemd can also manage mounts and automounts of storage drives.
For a simple machine I normally use the shorter /etc/fstab method. This longer unit-based method remains useful when I want dependencies and lifecycle to be explicit.
Create a systemd Mount Unit
Systemd uses units to manage resources. A mount unit is named after its mount path; I let systemd escape that name instead of replacing slashes by hand:
sudo mkdir -p /mnt/documents
systemd-escape --path --suffix=mount /mnt/documents
# mnt-documents.mount
For SMB I create a root-only credential file:
sudo install -d -m 700 /etc/samba
sudoedit /etc/samba/documents.credentials
sudo chmod 600 /etc/samba/documents.credentials
username=my-user
password=replace-me
domain=WORKGROUP
Create the Mount Unit
/etc/systemd/system/mnt-documents.mount:
[Unit]
Description=Documents SMB share
Wants=network-online.target
After=network-online.target
[Mount]
What=//192.168.1.100/documents
Where=/mnt/documents
Type=cifs
Options=credentials=/etc/samba/documents.credentials,uid=1000,gid=1000
TimeoutSec=30
[Install]
WantedBy=multi-user.target
The unit’s Where= must match the path encoded in its file name. Network mount units automatically gain network ordering, but I keep the explicit relationship here because it documents why the mount waits. systemd.mount
Add On-Demand Automounting
/etc/systemd/system/mnt-documents.automount:
[Unit]
Description=Automount Documents
[Automount]
Where=/mnt/documents
TimeoutIdleSec=5min
[Install]
WantedBy=multi-user.target
With an automount I enable the .automount, not the .mount; first access starts the mount. systemd.automount
Verify and Start
sudo systemd-analyze verify /etc/systemd/system/mnt-documents.mount \
/etc/systemd/system/mnt-documents.automount
sudo systemctl daemon-reload
sudo systemctl enable --now mnt-documents.automount
ls /mnt/documents
findmnt /mnt/documents
systemctl status mnt-documents.mount mnt-documents.automount
Enabling a broken remote mount can delay access or boot. I verify the units and test them before closing my maintenance session.
Roll Back
sudo systemctl disable --now mnt-documents.automount
sudo systemctl stop mnt-documents.mount
sudo rm /etc/systemd/system/mnt-documents.mount \
/etc/systemd/system/mnt-documents.automount
sudo systemctl daemon-reload
sudo systemctl reset-failed
I remove the credential file separately only when no other mount uses it.
Buy Me a Coffee