Using autofs to mount ISO images

Why

I have a directory with many different ISO images for installation purposes. I want to store them as an ISO image to be more portable and flexible. However, on my PXE server, they must be unpacked or mounted. Keeping track of all these mounts can be a headache. Autofs comes to our aid.

I like the default behavior of /net. Once you point to a known NFS server, say /net/server, you will see its available resources and be able to drill deeper into them. I want to repeat the same with our ISO mounts.

How

Of course, install autofs first. For Fedora it will be:

# dnf install -y autofs

You can make changes directly to the /etc/auto.master file, but your changes may conflict with updates or with other projects. Therefore, we will use the /etc/auto.master.d drop-in directory, and the first file to place will be:

# /etc/auto.master.d/cdrom.autofs 
/cdrom  program:/etc/auto.master.d/auto.cdrom   -fstype=auto,ro,loop

/cdrom will be the base directory where all ISOs will be mounted. The second field is the autofs map, but in our case it is the program that generates the map as its output. The third field is optional and may be omitted.

And here is the essence of the whole trick:

#!/bin/bash
# /etc/auto.master.d/auto.cdrom
# Should be executable: chmod 755 /etc/auto.master.d/auto.cdrom

ISODIR=/export/iso
opts="-fstype=auto,ro,loop"

find $ISODIR -type f -name "*iso" -o -name "*ISO" | LC_ALL=C sort -u | \
        awk -v opts="$opts" -- '
        BEGIN   { ORS=""; first=1 }
                { if (first) { print opts; first=0 }; short=substr($1,length("'$ISODIR'")+1) ;  print " \\\n\t" short " :" $1 }
        END     { if (!first) print "\n"; else exit 1 }
        ' | sed 's/#/\\#/g'

This script was created by reverse engineering the existing /etc/auto.net script. Don't forget to make it executable as indicated by its title.

Check

Restart autofs, on Fedora this is:

# systemctl restart autofs
# mount | grep /cdrom
/etc/auto.master.d/auto.cdrom on /cdrom type autofs (rw,relatime,fd=7,pgrp=147337,timeout=300,minproto=5,maxproto=5,indirect,pipe_ino=671058)

Autofs has started serving the /cdrom directory. Look at directory's contents - it is empty. Exactly the same behavior as with the /net directory. Try to use any name to look deeper. For example, do ls /cdrom/iso/. Now you can see the content even with subdirectories, if any. Try to "cd" to any *iso directory. Yes, it automatically mounts:

# df | grep /cdrom
/dev/loop0                  12G   12G     0 100% /cdrom/iso/RHEL/rhel-8.8-x86_64-dvd.iso

NOTE: The script does not support non-English characters and any spaces in directory and file names!


Updated on Mon Aug 21 17:45:46 IDT 2023 More documentations here