gpt4 book ai didi

mysql - 使用 Ruby/Chef Recipe for Vagrant 导入 Mysql 数据库

转载 作者:可可西里 更新时间:2023-11-01 06:36:48 24 4
gpt4 key购买 nike

我正在编写一个 chef 脚本来自动设置开发环境。我可以创建一个数据库并授予权限,但我正在尝试找到一种方法将 mysql 转储文件导入到刚刚创建的数据库中。

我授予访问权限的代码是

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")

但这只是给我一个错误。

我对 Ruby 的了解不多,所以很难理解。有人知道我该怎么做吗?

最佳答案

如果是文件路径错误,并且您正在使用 chef solo,请尝试使用 solo.rb 中指定的路径,例如:

/tmp/chef-solo/site-cookbooks/path_to_file.sql

作为一般说明,请考虑使用 database cookbook用于 mysql 用户和数据库管理任务。一旦设置了必要的 Recipe 依赖项,就可以将这样的代码放入主 Recipe 的 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 目录中存储数据库文件确实会减慢速度。

另请参阅:Import SQL file into mysql

关于mysql - 使用 Ruby/Chef Recipe for Vagrant 导入 Mysql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6009328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com