How to mount WebDAV share using systemd

You can check my earlier blog post on how to mount WebDAV share using command-line or fstab (file systems table), but you are not limited to these two options as you can use systemd to take care of the whole process and automount WebDAV resource on demand.

Install davfs2 package to mount WebDAV resource as regular file system.

$ sudo apt-get install davfs2

There is no need to allow unprivileged users to mount WebDAV resources during configuration phase.

Store username and password for the remote WebDAV share.

$ cat << EOF | sudo tee -a /etc/davfs2/secrets

# personal webdav, application password
/mnt/dav milosz mypassword
# older versions used URL, it is equivalent for compatibility reasons
#https://nextcloud.example.com/remote.php/webdav/ milosz mypassword
EOF

Create systemd mount unit configuration.

$ cat << EOF | sudo tee /etc/systemd/system/mnt-dav.mount
[Unit]
Description=Mount personal Nextcloud WebDAV
After=network-online.target
Wants=network-online.target

[Mount]
What=https://nextcloud.example.com/remote.php/webdav/
Where=/mnt/dav
Options=noauto,user,uid=milosz,gid=milosz
Type=davfs
TimeoutSec=60

[Install]
WantedBy=remote-fs.target
EOF

Create systemd automount unit configuration and define idle timeout (i.e. unmount or after specified period of inactivity), which is a really cool feature.

$ cat << EOF | sudo tee /etc/systemd/system/mnt-dav.automount
[Unit]
Description=Mount personal Nextcloud WebDAV automount
After=network-online.target
Wants=network-online.target

[Automount]
Where=/mnt/dav
TimeoutIdleSec=300

[Install]
WantedBy=remote-fs.target
EOF

Reload systemd manager configuration.

$ sudo systemctl daemon-reload

Enable automount service at boot time.

$ sudo systemctl enable mnt-dav.automount

Start the automount service right away.

$ sudo systemctl enable mnt-dav.automount

Additional information

You can create fstab entry to achieve the same results, but it is too easy to mess up everything.
I really mean it.

Remember, mount units must be named after the mount point directories they control. You can easily identify this problem by spotting the following log entry.

Where= setting doesn't match unit name. Refusing.

References

Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland https://sleeplessbeastie.eu