LoginSignup
42
43

More than 5 years have passed since last update.

初めてchef recipeを書く人向け、優しいrecipeの書き方。

Posted at

こんにちは、貴子です。

最近は一ヶ月の半分くらいchefのresipeを書いていたので、
よく使ったrecipeの書き方をまとめて紹介します。

Install

package インストール

recipe
package "curl-devel" do
  action :install
end

gem インストール

gem_binaryはインストールに使うgemの場所を指定しています。
rbenv等で複数のrubyを使い分けている方は利用してください。

recipe
gem_package mackerel-client do
  gem_binary("/root/.rbenv/shims/gem")
  action :install
end

rpm インストール

rpmでのnginxのインストールrecipeです。
まずnot_ifで既にインストールされているか確認して、されてなければremote_fileでrepositoryを取ってきています。
その後rpm_packageでインストールを行います。

recipe
# install repo
  remote_file "#{Chef::Config[:file_cache_path]}/nginx-release-rhel-6-0.el6.ngx.noarch.rpm" do
    source "http://nginx.org/packages/rhel/6/noarch/RPMS/nginx-release-rhel-6-0.el6.ngx.noarch.rpm"
    not_if "rpm -qa | grep -q '^nginx-release'"
    action :create
    notifies :install, "rpm_package[nginx-release]", :immediately
  end

 rpm_package "nginx-release" do
    source "#{Chef::Config[:file_cache_path]}/nginx-release-rhel-6-0.el6.ngx.noarch.rpm"
    action :nothing
  end

template

テンプレートを置いて、更新があったらnotifiesで指定したServiceをrestartします。

recipe
template "/etc/td-agent/td-agent.conf" do
  mode "0644"
  source td-agent.conf
  notifies :restart, 'service[td-agent]', :delayed
end

# Service restart
service "td-agent"

Download

wgetコマンドでtomcat7を取ってきているところのrecipeです。
tomcat7.tar.gzがpackage_pathにない場合のみ、ダウンロードを実行してもってきます。

recipe
package_name = "tomcat-#{tomcat_version}"
package_path = "#{Chef::Config[:file_cache_path]}/#{package_name}.tar.gz"
source_url = "http://archive.apache.org/dist/tomcat/tomcat-#{major_version}/v#{tomcat_version}/bin/apache-tomcat-#{tomcat_version}.tar.gz"

# Download
remote_file package_path do
  source source_url
  not_if { File.exist?(package_path) }
end

attribute

attributeから変数を引き継ぎます。
ruby:attribute
default["app-base"]["template_name"] = "app-base.conf.erb"

ruby:recipe
app-base_conf = node["app-base"]["template_name"]

配列

パッケージのインストールをまとめて実行することもできます。

recipe
# install basic rpms
%w{ntp wget git screen dstat vim-enhanced tar gzip}.each do |pkg|
  package pkg do
    action :install
  end
end

attributeで変数を持たせる場合はこう書きます。

attribute
default['app-base']['plugins'] = ["ntp","wget","git","dstat","vim-enhanced","tar","gzip"]
recipe
node['app-base']['plugins'].each do |plugin|
  package plugin do
    action :install
  end
end

crontab

crontabの設定方法です。

recipe
cron "logManager.sh" do
    minute "00"
    hour "01"
    user "root"
    command "/data/shell/logManager.sh"
end

こんな感じにcronが設定されます。

crontab
# Chef Name: logManager.sh
00 01 * * * /data/shell/logManager.sh
42
43
0

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
42
43