shell

Executing script on the host when running Vagrant commands

When running Vagrant commands there might be the need to execute something on the host as a pre setup requirement.

Since Vagrant is built with ruby it is possible to execute a shell script utilizing the system utility

system("script.sh")  

In some cases you might want to run a script only in a certain command of Vagrant, for example, when reloading the Vagrant box you might need to check if your host has all gateway routes configured or any other pre setup task.

system("  
  if [ #{ARGV[0]} = 'reload' ]; then
    echo 'Setting up routes on the host when reloading Vagrant box'
    ./set-up-routes.sh
  fi
")

Bash script to check if route exists with netstat and grep

Recently while crafting a Vagrantfile I came across the need of checking if I had already added a route to my host when reload the vagrant box.

Listing routes
netstat -nr  
  • -r shows the routing table
  • -n shows the network addresses as number
Matching the pattern
grep -co '172.17 *192.168.14.10'  
  • -c writes the number of matches to stdout
  • -o prints only the matching part of the line

Putting both commands together

if [ $(netstat -nr | grep -co '172.17 *192.168.14.10') = 0 ]; then  
        echo 'Adding gateway route for docker0 network'
        sudo route -n add 172.17.0.0/16 " + $vb_ip_address + "
    fi