LoginSignup
0

More than 5 years have passed since last update.

Chefのテンプレート(erb)をfileリソースで使う

Last updated at Posted at 2018-10-16

概要

Chefでtemplateリソースを用いてファイルを作成する場合、レシピとtemplates下のerbファイルの2つで管理する必要がある。
レシピでerbを使うことで1つのファイルで管理可能とできる。

レシピ例

recipes/default.rb

node.default['erb']['user'] = {
  'usr1' => {
    'uid' => 1000,
    'home' => '/home/usr1',
    'shell' => '/bin/bash',
    'comment' => 'foo',
  },
  'usr2' => {
    'uid' => 1001,
    'home' => '/home/usr2',
    'shell' => '/bin/bash',
  },
}

########

require 'erb'

file '/tmp/test.txt' do
  content ERB.new(<<~'EOC', nil, '-').result(binding)

    ユーザー情報

    <% node['erb']['user'].each do |u_name,u_attr| -%>
    user : <%= u_name %>
      uid     : <%= u_attr['uid'] %>
      home    : <%= u_attr['home'] %>
      shell   : <%= u_attr['shell'] %>
    <% if u_attr['comment'] -%>
      comment : <%= u_attr['comment'] %>
    <% end -%>

    <% end -%>
    EOC
end
  • fileリソースのcontentに対して、rubyのERBリソースを使用する。
  • ERBのソースは、ヒアドキュメントとして、<<~'EOC'の次の行からEOCの前の行までを指定。<<~を使用することで、全体をインデント可能としている。出力はインデントされない。'EOC'とシングルクォートで括ることで、バックスラッシュを含めてそのまま評価せずに使用可能としている。
  • ERB.newへの第3引数である'-'は、trim_modeの指定。この指定により、-%>で改行させないことが可能になる。制御系の<%の最後を-%>としているのは、その箇所に不要な改行を入れないため。
  • <% %>や<%= %>の内部ではそのままRubyの変数が使用可能
  • if文の箇所は以下の様にも書ける。ここでは、表示しない場合に改行させない為に-%>で終了させ、かつ表示させる場合には改行させる為に+ "\n"を行なっている。
    <%= "  comment : " + u_attr['comment'] + "\n" if u_attr['comment'] -%>

出力例

         * file[/tmp/test.txt] action create
           - create new file /tmp/test.txt
           - update content in file /tmp/test.txt from none to 5f5248
           --- /tmp/test.txt    2018-10-16 11:16:06.727526733 +0000
           +++ /tmp/.chef-test20181016-4802-10u25k4.txt 2018-10-16 11:16:06.727526733 +0000
           @@ -1 +1,15 @@
           +
           +ユーザー情報
           +
           +user : usr1
           +  uid     : 1000
           +  home    : /home/usr1
           +  shell   : /bin/bash
           +  comment : foo
           +
           +user : usr2
           +  uid     : 1001
           +  home    : /home/usr2
           +  shell   : /bin/bash
           +
           - restore selinux security context

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
0