LoginSignup
13
13

More than 5 years have passed since last update.

itamaeでホームディレクトリにrbenv環境を構築する

Last updated at Posted at 2015-12-04

itamaeでホームディレクトリにrbenv環境を構築する事例がウェブに見当たらなかったので、サロン当日予約アプリPopcorn で採用した方法をご紹介します。

なお、環境は Ubuntu 14.04 ですが、どの OS でも大丈夫なはずです(たぶん)。

完成したレシピ

# cookbooks/ruby/default.rb

include_recipe './attributes/default.rb'

rbenv_dir          = node['rbenv']['root_dir']
rbenv_versions     = node['rbenv']['versions']
rbenv_version      = node['rbenv']['version']
rbenv_owner        = node['rbenv']['owner']
rbenv_group        = node['rbenv']['group']
sudo               = "sudo -u #{rbenv_owner} -i"

git rbenv_dir do
  repository 'git://github.com/sstephenson/rbenv.git'
end

directory "#{rbenv_dir}/plugins" do
  not_if "test -d #{rbenv_dir}/plugins"
end

git "#{rbenv_dir}/plugins/ruby-build" do
  repository "git://github.com/sstephenson/ruby-build.git"
end

execute "chown #{rbenv_dir}" do
  command "chown -R #{rbenv_owner}:#{rbenv_group} #{rbenv_dir}"
end

rbenv_versions.each do |version|
  execute "rbenv install #{version}" do
    command "#{sudo} rbenv install #{version}"
    not_if  "#{sudo} rbenv versions | grep #{version}"
  end
end

execute "rbenv local #{rbenv_version}" do
  command "#{sudo} rbenv local #{rbenv_version}"
end

execute "rbenv global #{rbenv_version}" do
  command "#{sudo} rbenv global #{rbenv_version}"
end

execute "gem install bundler" do
  command "#{sudo} gem install bundler"
  not_if  "#{sudo} gem list | grep bundler"
end

工夫したポイントをいくつかご紹介します。

node attributes

node.reverse_merge! を使って、デフォルトを設定しています。

node.reverse_merge!(
  rbenv: {
    root_dir: '/home/kotaroito/.rbenv',
    owner: 'kotaroito',
    group: 'kotaroito',
    versions: %w(2.1.4),
    version: '2.1.4'
  }
)

詳しくは、itamae作者の荒井さんが http://gihyo.jp/admin/serial/01/itamae/0003 にて説明してくださっています。

sudo

sudo = "sudo -u #{rbenv_owner} -i"

sudo で -u と -i オプションを指定しています。

-i, --login

 Run the shell specified by the target user's password database entry as a login shell. This means that login-specific resource files such as .profile or .login will be read by the shell.  If a command is specified, it is passed to the shell for execution via the shell's -c option.....
-u user, --user=user

  Run the command as a user other than the default target user (usually root )....

これらオプションによって、~/.bash_profile を読み込んでくれるので、rbenv install や gem install bundler を node attributes で指定したユーザで実行することができます。

以上です。

13
13
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
13
13