Vagrant - how to have host platform specific provisioning steps Vagrant - how to have host platform specific provisioning steps ruby ruby

Vagrant - how to have host platform specific provisioning steps


Note that Vagrant itself, in the Vagrant::Util::Platform class already implements a more advanced version of the platform checking logic in the answer by BernardoSilva.

So in a Vagrantfile, you can simply use the following:

if Vagrant::Util::Platform.windows? then    myHomeDir = ENV["USERPROFILE"]else    myHomeDir = "~"end


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?    endend

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 provisionis_windows_host: falseVagrant launched from mac.


Here is a version using the Vagrant utils that checks for mac and windows:

    if Vagrant::Util::Platform.windows?        # is windows    elsif Vagrant::Util::Platform.darwin?        # is mac    else        # is linux or some other OS    end