Search code examples
rubychef-infrarbenv

How to run a ruby script by using chef with rbenv?


I want to run a ruby script by chef's execute resource like this.

execute "my_prog deamon" do
  command  %Q{bash -c 'export PATH="/usr/local/rbenv/bin:$PATH"; eval "$(rbenv init -)"; cd /opt/my_prog; ruby /opt/my_prog/my_prog_deamon.rb start'}
end

And I got error message like this.

---- Begin output of bash -c 'export PATH="/usr/local/rbenv/bin:$PATH"; eval "$(rbenv init -)"; cd /opt/my_prog; ruby /opt/my_prog/my_prog_deamon.rb start' ----
STDOUT:
STDERR: /opt/chef/embedded/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- daemons (LoadError)
    from /opt/chef/embedded/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /opt/my_prog/my_prog_deamon.rb:2:in `<main>'
---- End output of bash -c 'export PATH="/usr/local/rbenv/bin:$PATH"; eval "$(rbenv init -)"; cd /opt/my_prog; ruby /opt/my_prog/my_prog_deamon.rb start' ----

It looks like the error happens because ruby from chef is called instead of ruby from rbenv.

I rewrote ruby to /usr/local/rbenv/shims/ruby in recipe, but I got same error.

How can I run a ruby script by using chef? The rbenv is installed system wide.


Solution

  • The error seems to be originating from your custom script, with the error indicating that a requirement (in this case, the daemons gem) cannot be loaded.

    Either the ruby version you are using hasn't installed the correct dependencies, or the $GEM_PATH is incorrect and thus it can't find the required dependencies.

    If you only run this script from your Chef recipes, I would recommend looking at the resource_script provider, provided by Chef by default, in your case specifically the resource_ruby provider:

    ruby 'my_prog_deamon' do
      ...
    end
    

    If this isn't an option, I would run the script through the Chef ruby, and use chef_gem to install the required dependencies:

    chef_gem('daemons') do
      version 'x.y.z'
    end
    

    Then, when calling the script with the Chef gem, you can be sure the dependency is installed.