Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Chef | resources | Executeで任意のスクリプトをroot権限で実行

概要

Executeで任意のスクリプトをroot権限で実行

詳細

Executeで任意のスクリプトをroot権限で実行します。
※他のリソースで可能なことは他のリソースで行うこと。
executeやbashコマンドは何でも出来る反面、冪統性の保証を自分で行う必要がある。

execute "some execute name" do
  # options
end

詳細については公式サイトリンクを参照。
http://docs.opscode.com/chef/resources.html#execute

サンプル

コード

/home/vagrant/workにexecute.txtをvagrant userで出力します

execute "sample_execute" do
  not_if "cat /home/vagrant/work/execute.txt"

  user "vagrant"
  group "vagrant"
  cwd "/home/vagrant/work"
  command "echo execute!!!!! >> execute.txt"
  action :run
end

複数行の処理を実行したい場合はcommand部でヒアドキュメントを使用する

実行結果確認
$ pwd
/home/vagrant/work
$ cat execute.txt
execute!!!!!

# 再度プロビジョニング実行

$ pwd
/home/vagrant/work
$ cat execute.txt
execute!!!!!

# ↑ not_ifの指定により冪統性が保たれている(not_ifがなければ上記が2行になってしまう)