I'm new in ruby and chef. I built up a chef server and bootstrap a node successfully. I want to access Mysql on node through my cookbook without Mysql and database cookbook. I used ruby/mysql API. It worked well when was programmed in a single ruby file. The code is as follows.
require "rubygems"
require "mysql"
begin
con = Mysql.new("localhost", "root", "123")
res = con.query("create database abc")
rescue Mysql::Error => e
puts e.errno
puts e.error
ensure
con.close if con
end
But when I added this code to a ruby_block in my cookbook and chef-client it, I got the error on node.
================================================================================
Error executing action `run` on resource 'ruby_block[test1]'
================================================================================
LoadError
---------
cannot load such file -- mysql
Cookbook Trace:
---------------
/var/chef/cache/cookbooks/db_test/recipes/default.rb:14:in `block (2 levels) in from_file'
Resource Declaration:
---------------------
# In /var/chef/cache/cookbooks/db_test/recipes/default.rb
11: ruby_block "test1" do
12: block do
13: require "rubygems"
14: require "mysql"
15:
16: begin
17: con = Mysql.new("localhost", "root", "123")
18: res = con.query("create database abc")
19: rescue Mysql::Error => e
20: puts e.errno
21: puts e.error
22: ensure
23: con.close if con
24: end
25: end
26: # action :run
Compiled Resource:
------------------
# Declared in /var/chef/cache/cookbooks/db_test/recipes/default.rb:11:in `from_file'
ruby_block("test1") do
action "run"
retries 0
retry_delay 2
default_guard_interpreter :default
block_name "test1"
declared_type :ruby_block
cookbook_name "db_test"
recipe_name "default"
block #<Proc:0x000000051907a8@/var/chef/cache/cookbooks/db_test/recipes/default.rb:12>
end
Running handlers:
[2015-04-07T22:14:12-04:00] ERROR: Running exception handlers
Running handlers complete
[2015-04-07T22:14:12-04:00] ERROR: Exception handlers complete
[2015-04-07T22:14:12-04:00] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out
Chef Client failed. 0 resources updated in 0.962999999 seconds
[2015-04-07T22:14:12-04:00] ERROR: ruby_block[test1] (db_test::default line 11) had an error: LoadError: cannot load such file -- mysql
[2015-04-07T22:14:12-04:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)
I couldn't figure out when the problem is. Could anyone help this?
Chef runs in its own ruby instance (assuming you've installed using omnibus). You'll need to install the mysql gem into the Chef ruby using a chef_gem resource. Then you should be able to load the mysql ruby