websites/ewintr.nl/content/2025/til-one-can-automatically-m...

37 lines
2.7 KiB
Markdown

+++
title = "TIL one can automatically mount NFS shares with systemd"
date = 2025-01-15
+++
This might have been be obvious to some, but sometimes you don't learn about better ways to do something, just because the existing solution is not bad enough to spur you into action.
Today, I learned that you can add a line to `/etc/fstab` and let `systemd` take care of how and when a network share should be mounted:
```
192.168.1.35:/volume1/notes /mnt/nas/notes nfs defaults,x-systemd.automount,vers=4 0 0
```
The magic happens by adding `x-systemd.automount` to the options. This will leave the share unmounted until you access it.
To make it effective, reload the `systemd` configuration with:
```bash
$ sudo systemctl daemon-reload
```
And you're done. At least that is what everyone on the internet says. I needed to reboot before the change took effect. This also assumes that you have taken care of all other NFS related stuff, like installing `nfs-common` etc.
## Backstory
Sometimes you don't want to mount the share at boot. I have bad memories of when a share would somehow not be reachable over the network and some headless computer, of course stowed somewhere way back in an attic, would refuse to start because of that. And then I had to dig it out, attach a keyboard and a monitor to remove the line from `/etc/fstab` to get it working again.
Other times you have a laptop and the share is simply not accessible.
In the past, I used [autofs](https://help.ubuntu.com/community/Autofs) to cover situations like this. `autofs` also only mounts the share when it is accessed, but it has the ability to run a script first.
This was helpful when I had a NAS that would regularly go to sleep to save power. One can write a script that pings your NAS, and sends a [WoL](https://en.wikipedia.org/wiki/Wake-on-LAN) packet to wake it up if it doesn't respond. This is an example of a script that implements that: [gist](https://gist.github.com/dj-mcculloch/9e097535ea35df8e2ec1e6e32f7f73ac)
This was not perfect, though. Because even when the NAS was awake and ready, it could take seconds before I could access it. Not sure what caused it, but annoying it was. Even more so because often file managers and other apps in your desktop environment will try to inspect the contents of your directories in the background, over and over again, for all sorts of reasons. Sometimes I had to wait 10 seconds before I could open a directory, even when it was readily available.
These days, my NAS has more duties to fulfil and is always on. This has been the case for months. But I was still waiting for `autofs` every day. Until I installed a new computer and thought: oh, might as well put it directly in `/etc/fstab`, and asked an LLM to help me with the config.