Importing Mysql database using Ruby/Chef Recipe for Vagrant

后端 未结 3 811
夕颜
夕颜 2021-02-03 13:29

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

3条回答
  •  时光说笑
    2021-02-03 13:32

    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
    

    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
    

    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

提交回复
热议问题