Vagrantfileを書いているときにOSによって処理を変えたい場合があります。
たとえばsynced_folderのtypeをwindowsの場合だけ変更したいときが
それに該当します。
こういった場合には、Vagrantfileの先頭にメソッドを追加することで、
そのメソッドを利用して、Vagrantfile内でOSの判断が出来るようになります。
Vagrantfileの作成
Vagrantfileはrubyのスクリプトなので、Vagrantfileの先頭に以下のような
記述を追加します。
Vagrantfile
module OS
def OS.windows?
Vagrant::Util::Platform.windows?
end
def OS.mac?
(/darwin/ =~ Vagrant::Util::Platform.platform) != nil
end
def OS.unix?
!Vagrant::Util::Platform.platform
end
def OS.linux?
OS.unix? and not OS.mac?
end
end
あとは、Vagrant,configureのブロックの中でそのメソッドを使うことで
OSによって処理を切り分けることが出来ます。以下の例ではOSによって
synced_folderの方法を変えています。
Vagrantfile
module OS
def OS.windows?
(/mingw/ =~ RUBY_PLATFORM) != nil
end
...
中略
...
end
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.network "private_network", type: "dhcp"
if OS.windows?
config.winnfsd.uid = 1000
config.winnfsd.gid = 1000
config.vm.synced_folder ".", "/vagrant", type: "nfs"
elsif OS.mac?
config.vm.synced_folder ".", "/vagrant"
else
config.vm.synced_folder ".", "/vagrant", type: "nfs"
end
end
ファイルの分割
Vagrantfileの先頭にmoduleがあると、Vagrantの設定の内容が見づらくなって
しまうので、moduleの部分を別のファイルに切り出して、Vagrantfileと
同じ階層に置きます。
あとはVagrantfileの先頭でそのファイルを読み込むことで、moduleのメソッド
が使えるようになります。
Vagrantfile
load File.expand_path("os.rb") if File.exists?("os.rb")
Vagrant.configure("2") do |config|
...
中略
...
end