chef-zeroでRailsが動きそうな環境を構築する


やること

vagrantで立てたubuntuサーバにchef-zeroを使って、postgresqlやrbenvをインストールする


準備


vagrantでプロビジョニング対象を構築する

$ vagrant init bento/ubuntu-14.04
$ vim Vagrantfile
# コメントアウトを外す
#  config.vm.network "private_network", ip: “192.168.33.10"
$ vagrant up
$ vagrant ssh
$ ssh-add ~/.vagrant.d/insecure_private_key
$ ssh [email protected]

chefのインストール

chef-dkをインストールする

knife-zeroをインストールする

$ sudo chef gem install knife-zero

構成


プロビジョニングしてみる


repoを作る

$ chef generate repo chef-repo
$ cd chef-repo
$ mkdir .chef

knifeの設定ファイルを作成する

.chef/knife.rb
local_mode true
knife[:automatic_attribute_whitelist] = []
cookbook_path [
  './cookbooks',
  './site-cookbooks'
]

# knife[:ssh_password] = 'vagrant'

bootstrapする

$ chef exec knife zero bootstrap 192.168.33.10 -x vagrant --sudo
$ chef exec knife node list

利用するcookbookを宣言する

Berksfile
source "https://supermarket.chef.io"

cookbook 'postgresql', '~> 4.0.6'
cookbook 'database', '~> 5.1.2'
cookbook 'rbenv', '~> 1.7.1'
cookbook 'imagemagick', '~> 0.2.3'

Chef Supermarket
先人の皆様が作ってくれたcookbookが公開されている


cookbookをダウンロードしてくる

$ chef exec berks vendor cookbooks
$ chef exec knife cookbook list

cookbookを作る

supermarketから持ってきたcookbookを組み合わせて用途に合わせたcookbookを作る。
今回はRailsが動きそうな環境。

$ mkdir site-cookbooks
$ chef exec knife cookbook create app -o site-cookbooks
$ cd site-cookbooks/app

依存するcookbookを書く

site-cookbooks/app/metadata.rb
...

depends 'postgresql'
depends 'database'
depends 'rbenv'
depends 'imagemagick'

サーバの構成を定義する
※現状、database_userが動かない...

site-cookbooks/app/recipes/default.rb
include_recipe 'apt'
include_recipe 'postgresql::client'
include_recipe 'postgresql::server'
include_recipe 'postgresql::contrib'
include_recipe "database::postgresql"

include_recipe 'rbenv::default'
include_recipe 'rbenv::ruby_build'
include_recipe 'imagemagick::default'

# create postgres user
postgresql_connection_info = {
  :host     => '127.0.0.1',
  :port     => node['postgresql']['config']['port'],
  :username => 'postgres',
  :password => node['postgresql']['password']['postgres']
}

postgresql_database_user 'sample-user' do
  connection postgresql_connection_info
  password   'ultra_secret'
  action     :create
end

# install ruby
rbenv_ruby "2.3.1"
rbenv_gem "bundler" do
  ruby_version "2.3.1"
end

# libmagickwand-dev
package 'libmagickwand-dev' do
  action :install
end

run_listを編集

対象のサーバに対してどのrecipeを適用するか指定する。

$ cd [chef-repo-root]
$ EDITOR=vim knife node edit vagrant.vm
...
"run_list": [
  "recipe[app::default]"
]
...

cookbookを適用

$ chef exec knife zero converge name:vagrant.vm --attribute knife_zero.host  -x vagrant --sudo

確認

$ ssh [email protected]

$ psql
$ rbenv versions

🎉


参考