Automatically start Virtual Machine and auto-mount

I love Virtual Machines, they are useful and with them you can do whatever you want without cluttering your main system.

I like to keep my main os as simple as possible, if I want some server software I usually create a Virtual Machine for that.

My workflow to start working with web development was something like this:

  1. Open VirtualBox
  2. Start the virtual machine
  3. Mount the /var/www in the Host OS with SSHFS
  4. Open VIM and start working

I had an alias to mount the /var/www directory but that isn't enough, I still had to open VirtualBox, start the virtual machine and I had to keep the Virtual Machine window open.

I made a simple script to automate that, plus the VM runs in headless mode, all you need is VirtualBox, a virtual machine and SSHFS.

The script:

#! /bin/sh

ACTION=$1
VM_NAME=$2;

if [ "$ACTION" == "start" ]; then
    VM_USER=$3;
    VM_IP=$4;
    VM_PATH=$5;
    LOCAL_PATH=$6;
    PASSWORD=$7;
    BOOT_WAIT=$8;

    VBoxManage startvm "$VM_NAME" --type headless
    sleep $BOOT_WAIT
    echo "$PASSWORD" | sshfs $VM_USER@$VM_IP:$VM_PATH $LOCAL_PATH -o password_stdin
    echo "DONE"
    exit
fi;

if [ "$ACTION" == "stop" ]; then
    LOCAL_PATH=$3;
    fusermount -u $LOCAL_PATH
    VBoxManage controlvm "$VM_NAME" acpipowerbutton
    echo "DONE"
    exit
fi;

# no action provided or invalid, show usage
echo "Start Virtual Machine and automount"
echo "Usage: vm_mount.sh <action> <vm_name> <vm_user> <vm_ip> <vm_addr> <local_mountpoint> <vm_password> <wait_for_boot_time_in_seconds>"
echo "Examples:"
echo '  vm_mount.sh start "TURNKEY LAMP" root vmlamp.local /var/www ~/vmwww password 10'
echo '  vm_mount.sh stop "TURNKEY LAMP" ~/vmwww'

You can download with curl using:

curl ix.io/1Lbu > vm_start.sh && chmod +x vm_start.sh

The usage of this script is very simple, just call ./vm_mount.sh --help and it will print some examples.

Tip: Create an alias for each of your virtual machines, this way you don't need to type all those arguments. You can do that in .bashrc or .zshrc, (...) depending of your shell.

By the way, ix.io is a great tool, you should take a look at it.

As always you can contact me if you have some suggestions. Thank you for reading.

Comments

This section is still in development.

If you want to share any thoughts drop me a line at bruno.fl.jesus@gmail.com