Steve Childs Steve Childs - 1 year ago 36
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/"
else if (host == linux) then
config.vm.provision : shell, : inline => "/vagrant/provisioning/"
else if (host == osx) then
config.vm.provision : shell, : inline => "/vagrant/provisioning/"
end if

Thanks in advance.

Answer Source

Find out current OS inside Vagrantfile.

Add this into your Vagrantfile:

module OS
        (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil

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

    def OS.unix?

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

Then you can use it as you like.

if [then]

Edit: was missing the ? on if condition.

Example used to test:

is_windows_host = "#{}"
puts "is_windows_host: #{}"
    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."
    puts "Vagrant launched from unknown platform."


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