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
I'm not really a Ruby guy, but I managed to get Chef to import a large .sql file by leveraging the mysql 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:
[client]
host=<%= @host %>
user=<%= @user %>
password="<%= @password %>"
Then I added a resource to my recipe that would populate the template:
template '/root/.my.cnf' do
mode 0600
variables({
:host => 'localhost',
:user => 'root',
:password => node[:your_cookbook][:db][:root_password],
})
end
(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 run mysql 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:
backup_sql = '/path/to/the/db-backup.sql'
db_last_modified = "/etc/db-#{node[:your_cookbook][:db][:name]}.lastmodified"
execute 'restore backup' do
command "mysql #{node[:your_cookbook][:db][:name]} <'#{backup_sql}' && touch '#{db_last_modified}'"
not_if { FileUtils.uptodate?(db_last_modified, [backup_sql]) }
end
(Where node[:your_cookbook][:db][:name] is the name of the MySQL database that will be restored.)