使用Ruby/Chef Recipe for Vagrant导入Mysql数据库 [英] Importing Mysql database using Ruby/Chef Recipe for Vagrant
问题描述
我正在编写一个厨师脚本来自动设置开发环境.我可以创建数据库并授予特权,但是我试图找到一种将mysql转储文件导入到刚刚创建的数据库中的方法.
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
,我希望我能够进行以下查询
#m.query("-u root -p root db_name < /project/db/import.sql")
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.
我没有做很多Ruby,所以很难弄清楚.有人知道我该怎么做吗?
I haven't done much Ruby so finding it hard to figure out. Anybody know how I can do this?
推荐答案
如果这是文件路径错误,并且您正在单独使用Chef,请尝试使用 solo.rb 中指定的路径:
If it's a file path error, and you're using chef solo, try using the path specified within solo.rb, like:
/tmp/chef-solo/site-cookbooks/path_to_file.sql
作为一般说明,请考虑使用数据库食谱来执行mysql用户和数据库管理任务.设置必要的食谱依赖关系后,您可以将这样的代码放入主配方的 default.rb :
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:
# externalize conection info in a ruby hash
mysql_connection_info = {
:host => "localhost",
:username => 'root',
:password => node['mysql']['server_root_password']
}
# drop if exists, then create a mysql database named DB_NAME
mysql_database 'DB_NAME' do
connection mysql_connection_info
action [:drop, :create]
end
# query a database from a sql script on disk
mysql_database "DB_NAME" do
connection mysql_connection_info
sql { ::File.open("/tmp/chef-solo/site-cookbooks/main/path/to/sql_script.sql").read }
action :query
end
#or import from a dump file
mysql_database "DB_NAME" do
connection mysql_connection_info
sql "source /tmp/chef-solo/site-cookbooks/main/path/to/sql_dump.sql;"
end
尚未测试最后一个,因为在Chef目录中存储数据库文件确实会使速度变慢.
Haven't tested that last one because storing a database file within the chef directory really slows things down.
另请参见:将SQL文件导入mysql
这篇关于使用Ruby/Chef Recipe for Vagrant导入Mysql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!