Steve Childs Steve Childs - 4 months ago 7
Ruby Question

Vagrant - how to have host platform specific provisioning steps

We've got a diverse dev team, one on Windows, another on Ubuntu and another on OSX. Being windows boy, I setup the first version of the vagrant setup script which works fabulously ;)

However, when running it on the Ubuntu host, the first time it gets to a provision step that calls a bash script, it fails due to permissions.

On windows, this doesn't matter as the samba share automatically has sufficient permissions to run the bash script (which resides within the project hierarchy, so is present in the /vagrant share on the VM), but with ubuntu I need to set the permissions on this file in the provision script before I call it.

This isn't the problem and to be honest I suspect even with the extra "chmod" step it would still work fine under windows, but, is there a way in the vagrant file to flag certain provisioning steps as 'Windows Only', 'Linux Only' or 'Mac Only'?

i.e. in pseduo code, something like.

.
.
if (host == windows) then
config.vm.provision : shell, : inline => "/vagrant/provisioning/only_run_this_on_windows.sh"
else if (host == linux) then
config.vm.provision : shell, : inline => "/vagrant/provisioning/only_run_this_on_linux.sh"
else if (host == osx) then
config.vm.provision : shell, : inline => "/vagrant/provisioning/only_run_this_on_osx.sh"
end if
.
.


Thanks in advance.

Answer

Find out current OS inside Vagrantfile.

Add this into your Vagrantfile:

module OS
    def OS.windows?
        (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil
    end

    def OS.mac?
        (/darwin/ =~ RUBY_PLATFORM) != nil
    end

    def OS.unix?
        !OS.windows?
    end

    def OS.linux?
        OS.unix? and not OS.mac?
    end
end

Then you can use it as you like.

if OS.windows? [then]
    code...
end

Edit: was missing the ? on if condition.

Example used to test:

is_windows_host = "#{OS.windows?}"
puts "is_windows_host: #{OS.windows?}"
if OS.windows?
    puts "Vagrant launched from windows."
elsif OS.mac?
    puts "Vagrant launched from mac."
elsif OS.unix?
    puts "Vagrant launched from unix."
elsif OS.linux?
    puts "Vagrant launched from linux."
else
    puts "Vagrant launched from unknown platform."
end

Execute:

# Ran provision to call Vagrantfile.
$ vagrant provision
is_windows_host: false
Vagrant launched from mac.