autofs can be used to automatically mount file systems when they are accessed. autofs can either
- read mount pairs that are explicitly specified in
auto.XXXfiles that are added to theauto.masterfile, or - it can also execute a script that dynamically generates a mount command that is then executed by autofs.
The advantage of the latter is, that specified mount pairs do not need to be adapted each time the shares on the target change, but instead the script can read these changes automatically and feed them to autofs. Renaming a share on the target would then lead to a renamed mount point.
For automatically mounting CIFS shares this way, there is already a auto.smb script included in the autofs packages (at least on Ubuntu). However, for nfs I could not find such a script.
That is why I wrote it myself:
#!/bin/bash
key="$1"
opts="-defaults,fstype=nfs4"
for P in /bin /sbin /usr/bin /usr/sbin
do
if [ -x $P/showmount ]
then
SHOWMOUNT=$P/showmount
break
fi
done
[ -x $SHOWMOUNT ] || exit 1
$SHOWMOUNT -e "$key" 2>/dev/null | awk -v "key=$key" -v "opts=$opts" -F ' ' -- '
BEGIN { ORS=""; first=1 }
/\// {
if (first)
print opts; first=0
dir = $1
gsub(/.*\//, "/", dir)
loc = $1
# Enclose mount dir and location in quotes
print " \\\n\t \"" dir "\"", "\"" key ":" loc "\""
}
END { if (!first) print "\n"; else exit 1 }
'
The script takes one parameter (which is the hostname of the NFS server). It then uses the showmount command, to retrieve a list of NFS shares and formats them in a way, that autofs can understand.