Tbpgr Blog

Recruiting Operations tbpgr(てぃーびー) のブログ

Chef | Templateで設定ファイルにNodeごとに異なる値を設定する

概要

Templateで設定ファイルにNodeごとに異なる値を設定する

詳細

Templateで設定ファイルにNodeごとに異なる値を設定します

サンプル

仕様

vagrantで作成したUbuntu1204環境内でlocalhostへのプロビジョニング
sublime_sunippetterのgemをインストールする
・/home/vagrant/sublime_snippetにSunippetdefineをTemplateを利用して配置

手順
# kitchenの作成
knife solo init sublime_snippet
cd sublime_snippet

# cookbookの作成
knife solo create sublime_snippet -o cookbook

# cookbook/sublime_snippet/recipe/default.rbの編集。詳細は後述
# cookbook/sublime_snippet/template/default/Sunippetdefineの編集。詳細は後述
# localhost.jsonの編集
# solo.rbの編集

# 実行
sudo chef-solo -c solo.rb -j ./localhost.json
cookbook/sublime_snippet/recipe/default.rb
gem_package "sublime_sunippetter" do
end

template "Sunippetdefine" do
  path "/home/vagrant/sublime_snippet/Sunippetdefine"
  source "Sunippetdefine.erb"
  owner "vagrant"
  group "vagrant"
  mode 0644
end

bash "generate snippet" do
  code <<-EOS
  cd /home/vagrant/sublime_snippet
  suni
  EOS
end
/home/vagrant/sublime_snippet/Sunippetdefine.erb
# encoding: utf-8

# set output path. default=current directory
output_path '/home/vagrant/sublime_snippet/snippet'

# set sunippet scope. default=source.ruby
scope "source.ruby"

# if two args method
add :<%=node['sublime_snippet']['field1']%>, :<%=node['sublime_snippet']['args1']%>, :<%=node['sublime_snippet']['args2']%>
# if no args method
add :<%=node['sublime_snippet']['field2']%>
localhost.json
{
  "sublime_snippet" : {
    "field1" : "append",
    "args1" : "name",
    "args2" : "path",
    "field2" : "remove"
  },
  "run_list" : [
    "sublime_snippet"
  ]
}

出力

tree
$ tree
.
├── append.sublime-snippet
└── remove.sublime-snippet
append.sublime-snippet
$ cat append.sublime-snippet 
<snippet>
  <content><![CDATA[
append ${1:name}, ${2:path}
]]></content>
  <tabTrigger>append</tabTrigger>
  <scope>source.ruby</scope>
  <description>append method</description>
</snippet>
remove.sublime-snippet
$ cat remove.sublime-snippet 
<snippet>
  <content><![CDATA[
remove
]]></content>
  <tabTrigger>remove</tabTrigger>
  <scope>source.ruby</scope>
  <description>remove method</description>
</snippet>