Monday, May 16, 2016

How to mount VirtualBox shared folders at boot

I'm setting up a network install server on a VirtualBox VM, and I didn't want to copy the contents of the iso images of the distros going to be available through PXE to avoid having a huge VM. Worse if I also included other repos like epel or centosplus, or updates, so I created a VirtualBox shared folder pointing to the directory containing the iso images. After having created the shared folder, you can mount it like this:

sudo mount -t vboxsf -o uid=$UID,gid=$(id -g) share ~/host

To avoid having to manually mount the share each time the VM boots , the shared mount needs to be added to /etc/fstab, but there's a catch: the vboxsf kernel module, needed to mount the shared folder, isn't available when mounting all filesystems during the boot process. So, to fix this we need to make sure the vboxsf module is loaded before the filesystems mount at boot.

On CentOS 7, create a file on /etc/sysconfig/modules directory ending in .modules and add this to load VirtualBox kernel module before filesystems are mounted:

#!/bin/sh

    lsmod |grep vboxsf >/dev/null 2>&1
    if [ $? -gt 0 ] ; then
      exec /sbin/modprobe vboxsf >/dev/null 2>&1
    fi

On Ubuntu/Debian, add the module name to /etc/modules. Now we need to add the shared mount to /etc/fstab. In my case, my shared folder is called isos, so I added the following line:

isos    /isos   vboxsf  defaults        0 0

After adding this line you can reboot the server/vm and see if it mounted correctly at boot.

If you want to mount the iso images too at boot, add a line like this one to /etc/fstab, for each iso to mount:

/isos/CentOS/CentOS-7-x86_64-DVD-1511.iso /distros/centos7 iso9660 loop 0 0

Remember to adjust loopback device limits if you plan to mount more than 8 or 10 images (don't remember right now the limit).