Skip to content

Instantly share code, notes, and snippets.

@imksoo
Created April 5, 2017 06:27
Show Gist options
  • Save imksoo/91b02282b17b626fb942ab5a2c2e6349 to your computer and use it in GitHub Desktop.
Save imksoo/91b02282b17b626fb942ab5a2c2e6349 to your computer and use it in GitHub Desktop.
Itamaeで擬似的にEnvironmentを再現する

Itamaeで擬似的にEnvironmentを設ける時の書き方

Itamae実行時にノードアトリビュートを与えて実行する(itamae -y node.yaml recipe.rb or itamae -j node.json recipe.rb)が、 そのノードアトリビュート内部で擬似的にEnvironment変数を設定しておく。

# nodes/hogehoge-web-server.yaml
environment: development
cookbooks:
    - dnsmasq

次にEnvironment毎に値を変えたいレシピ側では attribute.rb をインクルードする。

# cookbooks/dnsmasq/default.rb
include_recipe './attribute.rb'

package 'dnsmasq' do
  action :install
end
...

attribute.rb の中では、node[:environment] 変数の中身に応じて node 変数を設定する。 Itamae の場合は、reverse_mergeを用いることでデフォルト値(ノードアトリビュートで設定済みの値)がない場合にのみ値を設定することが出来る。

# cookbooks/dnsmasq/attribute.rb
case node[:environment]
when 'development' then
  node.reverse_merge!(
    dnsmasq: {
      servers: [
        "10.1.1.1",
        "10.1.1.2",
      ]
    }
  )
when 'staging' then
  node.reverse_merge!(
    dnsmasq: {
      servers: [
        "10.10.1.1",
        "10.10.1.2",
      ]
    }
  )
when 'production' then
  node.reverse_merge!(
    dnsmasq: {
      servers: [
        "10.100.1.1",
        "10.100.1.2",
      ]
    }
  )
else
  node.reverse_merge!(
    dnsmasq: {
      servers: [
        "192.168.1.1",
      ]
    }
  )
end

後はテンプレートなりで値を読み出せば良い。

# cookbooks/dnsmasq/templates/dnsmasq.conf.erb
<% node[:dnsmasq][:servers].each do |srv| -%>
server=<%= srv.chomp %>
<% end -%>
# /etc/dnsmasq.conf
server=10.10.1.1
server=10.10.1.2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment