LoginSignup
3
5

More than 5 years have passed since last update.

VagrantfileでOSを判断する方法

Last updated at Posted at 2017-07-19

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
3
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5