chefのレシピを読み書きするときに知っておくと便利なこと1

only_if

only_ifは評価結果がtrue(return値が0)の時に実行。

ruby_block

ruby_blockを使うと、rubyのコードが記述可能になる。

ruby_block "{リソース名}" do
 block do
  Rubyのコードを記述
  :
 end
 action {:createRubyのコードを実行する)|:nothing(何もしない)}
end

actionとかは省略が可能。subscribes も指定可能。
actionを省略した場合は、createになる。

provider(LWRPs)

providerを使うことで、新規に自作のリソースを定義できる。
Custom Lightweight Resources — Chef Single-page Topics を見ると、providers の下に定義したproviderはRubyのソースの名前でそのまま使えるように見える。
実際にrecipeで利用する時は、cookbook名_Rubyのソースの名になる。
cookbook名に『-』が入っている時には、『_』を利用するようになる。

notifies

変更時に処理を指定する際に "notifies" を使いますが、notifies のデフォルトは delayed となり、キューに貯められて Chef の処理の最後にまとめて実行されます。
今回は、処理がひとつしかないので特に困りませんが、依存関係のある複数の処理が走る場合に、即時実行したい場合は、:immediately を指定しましょう。
るびま Chef でサーバ管理を楽チンにしよう! (第 2 回)

service "apache2" do
  case node['platform_family']
  when "rhel", "fedora", "suse"
    service_name "httpd"
    # If restarted/reloaded too quickly httpd has a habit of failing.
    # This may happen with multiple recipes notifying apache to restart - like
    # during the initial bootstrap.
    restart_command "/sbin/service httpd restart && sleep 1"
    reload_command "/sbin/service httpd reload && sleep 1"
  when "debian"
    service_name "apache2"
    restart_command "/usr/sbin/invoke-rc.d apache2 restart && sleep 1"
    reload_command "/usr/sbin/invoke-rc.d apache2 reload && sleep 1"
  when "arch"
    service_name "httpd"
  when "freebsd"
    service_name "apache22"
  end
  supports [:restart, :reload, :status]
  action :enable
end

template "/etc/sysconfig/httpd" do
  source "etc-sysconfig-httpd.erb"
  owner "root"
  group node['apache']['root_group']
  mode 00644
  notifies :restart, "service[apache2]"
  only_if { platform_family?("rhel", "fedora") }
end

とすると、templateを実行しnotifiesから呼ばれた時(package実行時)にapacheをrestartする。

subscribes

template "/tmp/somefile" do
  mode "0644"
  source "somefile.erb"
end

service "apache" do
  supports :restart => true, :reload => true
  action :enable
  subscribes :reload, resources("template[/tmp/somefile]"), :immediately
end

Notifications for Recipes and Resourcesのレシピを参照

notifiesとは逆で、他のリソースが変更された時に実行される。
設定ファイルの更新処理をsubscribes して、サービスのrestartを実行する。というように書かれていること多い。
opscodeのサンプルのレシピでも、そのように書かれている。
シンタックスは、下記の通り。

resource "name" do
  subscribes :action, "resource_type[resource_name]", :notification_timing
end