Chef Chef は、Ruby と Erlang で開発された Infrastructure as Code (IaC) を実現する代表的なサーバー構成管理・自動化フレームワークです。
インストールとスタンドアロン実行 (chef-solo)
公式 Omnitruck スクリプトを使用して対象ノードに Chef クライアントを導入:
# Chef クライアントのインストール
curl -L https://omnitruck.chef.io/install.sh | sudo bash
# インストールバージョンの確認
chef-solo -v
スタンドアロン環境で Cookbook を実行:
chef-solo -c solo.rb -j node.json
Knife CLI コマンド集
# 公式 Supermarket レジストリを検索
knife supermarket search mysql
# Cookbook アーカイブをローカルへダウンロード
knife supermarket download nginx
# SSH 経由でリモートサーバーを Chef 管理対象として初期セットアップ
knife bootstrap 192.168.1.50 -x root -P 'password' -N web01
主要な Recipe DSL リソース構文
パッケージの導入とサービス管理
package 'nginx' do
action :install
end
service 'nginx' do
action [:enable, :start]
supports status: true, restart: true, reload: true
end
リモートファイルのダウンロード
remote_file '/usr/local/src/node.tar.gz' do
source 'https://nodejs.org/dist/v18.0.0/node-v18.0.0.tar.gz'
checksum 'sha256checksumhere...'
mode '0644'
action :create_if_missing
end
Shell コマンドの直接実行
execute 'compile_app' do
command './configure && make && make install'
cwd '/usr/local/src/app'
environment 'PATH' => "/usr/local/bin:#{ENV['PATH']}"
creates '/usr/local/bin/app' # ガード句:ファイルが存在しない場合のみ実行
end
条件付きガード句 (only_if と not_if)
execute 'migrate_database' do
command 'rails db:migrate'
cwd '/var/www/app/current'
only_if { File.exist?('/var/www/app/current/Rakefile') }
not_if 'pg_isready -h localhost'
end