9
10

More than 5 years have passed since last update.

Vagrant で外部設定ファイルを扱う

Last updated at Posted at 2014-08-26

プライベートネットワーク設定の IP アドレスを設定として外出ししたい !!
こういうファイルを読み込ませたいわけですよ主に。

conf.yml
---
ip_address: 192.168.50.120

Vagrantfile = Ruby script

じゃあ Ruby で書けばいいじゃない。

Vagrantfile
require 'yaml'

begin
  conf = YAML.load_file(File.join(File.dirname(__FILE__), 'conf.yml'))
rescue Errno::ENOENT
  # default settings
  conf = {
    'ip_address' => '192.168.50.100'
  }
end


VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  # snip

  config.vm.network "private_network", ip: conf['ip_address']
end

どうやら yaml モジュールは Ruby 標準なのでいろいろ心配する必要はないらしい。

rescue 節にデフォルト設定をつっこんでおけばファイルがなくても動くようにできる。

ファイルがあることを強制したい場合は以下のように rescue 節でゴニョゴニョすればいいんじゃないでしょうか。

require-conf.rb
require 'yaml'

begin
  conf = YAML.load_file(File.join(File.dirname(__FILE__), 'conf.yml'))
rescue Errno::ENOENT => ex
  STDERR.puts ex
  STDERR.puts 'Create conf.yml at the same dir with Vagrantfile'
  exit(false)
end
9
10
0

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
9
10