Among the many functions that systemd provides, there is one that is unfairly forgotten. This is an automount feature. When setting up an automount, the specified directory will be mounted only after the first access to it (more precisely, right on time).
NFS over VPN
A specific example: I have a remote server that has a directory of interest to me. I want to have this directory locally on my machine. The access protocol is nfs. Since it does not have encryption, then the reasonable solution is to use a vpn channel to the server.
At the same time, I want to mount it on the go and unmount it after a while, so as not to experience strange difficulties due to the blunt nfs while the network is down. The mount timeout is a much more humane error than the nfs timeout on ls.
')
How it works
Systemd has a special form of automount-units, which allow you to automatically mount the specified directory.
Important: automount units are not “mount units with automount”, they cannot have mount options in themselves. Instead, they (when accessing the directory) just call the mount-unit for the specified directory.
Accordingly, with the configuration:
- Mount options, device (or server in case of NFS) are specified in mount-unit
- Dependencies and install section are specified in automount unit
- Svzyak automount-unit and mount-unit occurs by the parameter where
The same can be seen in the structure of the units themselves. A mount unit has a [Mount] section in which there can be many parameters. An automount unit should not have such a section, and instead there is a [Automount] section, which can have only a few parameters: Where, DirectoryMode, and TimeoutIdleSec.
Practical example
/etc/systemd/system/media-nfs.mount
:
[Unit]
Description = NFS share
[Mount]
What = server.url.example.com: / srv / nfs_share
Where = / media / nfs
Type = nfs4
Options = rw
DirectoryMode = 0755
/etc/systemd/system/media-nfs.automount
:
[Unit]
Description = NFS share
Requires=openvpn@vpn.service
Requires = network-online.target
[Automount]
Where = / media / nfs
TimeoutIdleSec = 301
[Install]
WantedBy = graphical.target
Observation: despite the fact that for a mount unit the normal state is active (mounted), then for automount it is active (running), as for a service.
If automount has not happened yet, then the status will be “active (waiting)”.
After configuring automount, you need to do (sudo) systemctl daemon-reload, and do ls / media / nfs (for example above) - after some delay in mounting nfs, we will see the contents of the files on the remote server.