Run all sql files with Chef

落花浮王杯 提交于 2019-12-01 10:58:45

There is a misconception here about how Chef compiles resources. You are expecting Chef to execute the command 15 times, but that's not how Chef operates. Chef runs in two phases - the execution phase, and the compilation phase. During the compilation phase (which runs first), the Ruby is evaluated and resources are added to the resource collection. With some exceptions, this phase does not alter the state of the system. So given your recipe:

execute "Run_SQL_Files" do
  dirResults = Dir.glob("/tmp/sql_dumps/*.sql") 
  var = 0
  while var < 15 do
    var = var + 1 
    command "mysql --user=root --password=toomba source" + dirResults[var]
    # Already tried this also
    # command "mysql --user=root --password=toomba < "  dirResults[var]
    puts dirResults[var]
  end
end

That is functionally equivalent to a recipe that was written like this (after the compilation phase completes)"

execute "Run_SQL_Files" do
  command "mysql --user=root --password=toomba source /tmp/sql_dumps/15.sql"
end

Notice that Chef is only going to utilize the last value for the command attribute. That is because Chef executes in two phases (as already mentioned).

Using conditional logic and loops inside of a resource definition is almost always going to cause problems. In this example, you need to compile the command outside of the execute resource. Each SQL command you want to execute needs to have it's own execute block. Here's a simple, refactored example:

Dir["/tmp/sql_dumps/*.sql"].each do |path|
  execute "run_sql_#{path}" do
    command "mysql --user=root --password=toomba < #{path}"
  end
end

This will put 15 (assumption from OP) execute resources in the resource collection, and execute them in order.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!