I am writing a chef script to automate setting dev environments. I can get a database created and grant privileges but I am trying to find out a way to import a mysql dump file into the database that has just been created.
My code for granting the access is
ruby_block "Execute grants" do
block do
require 'rubygems'
Gem.clear_paths
require 'mysql'
m = Mysql.new('localhost', "root", node[:mysql][:server_root_password])
m.query("GRANT ALL ON *.* TO 'root'@'10.0.0.1' IDENTIFIED BY '#{node[:mysql][:server_root_password]}'")
m.query('FLUSH PRIVILEGES')
end
end
and I was hoping I would be able to do the following query
#m.query("-u root -p root db_name < /project/db/import.sql")
but is just gives me an error.
I haven't done much Ruby so finding it hard to figure out. Anybody know how I can do this?
If it's a file path error, and you're using chef solo, try using the path specified within solo.rb, like:
As a general note, consider using the database cookbook for mysql user and database management tasks. Once you setup the necessary cookbook dependencies, you can put code like this into your main recipe's default.rb:
Haven't tested that last one because storing a database file within the chef directory really slows things down.
See also: Import SQL file into mysql
I'm not really a Ruby guy, but I managed to get Chef to import a large
.sql
file by leveraging themysql
command line tool. Challenges I needed to solve:.sql
file in the 100's of MB range (YMMV if you need GBs or TBs).sql
file has changedFirst I created a
.my.cnf
file template to pass the credentials:templates/default/.my.cnf.erb
Then I added a resource to my recipe that would populate the template:
recipes/import-db.rb
(Where
node[:your_cookbook][:db][:root_password]
is an attribute that contains the MySQL root password)Security Note: for simplicity I'm doing the import as the
root
user. If the.sql
file to be imported is not from a trusted source, you will want to runmysql
as a limited user and connect to MySQL with a limited db user that only has access to the database in question.Finally, I added another resource to the recipe that actually executes the import:
(Where
node[:your_cookbook][:db][:name]
is the name of the MySQL database that will be restored.)You can create a backup from the MySQL command line client, but not from within a SQL query. You need to execute the command from the shell. I believe the
execute
resource might do the trick for you:http://wiki.opscode.com/display/chef/Resources#Resources-Execute