为什么厨师食谱中的最后一个命令首先执行?

Why last command in chef recipe executing first?

i 运行 它在 kitchen vagrant centos-72 Chef 12.19.36

在metadata.rb depends 'rabbitmq', '~> 3.0'

run_list 我试试

 "recipe[rabbitmq]",
 "recipe[rabbitmq::mgmt_console]",
 "recipe[rabbitmq::user_management]",
 "recipe[mycookbook::myrecipe]"

我的食谱是

chef_gem 'rabbitmq_http_api_client' do
  version                    '1.8.0'
  action                     :install
end

require "rabbitmq/http/client"
endpoint = "http://127.0.0.1:15672"
client = RabbitMQ::HTTP::Client.new(endpoint, :username => "user", :password => "321")
client.declare_exchange("myvhost", "myexchange", durable: true, type: "direct")

没有我的食谱一切都好。 但是,如果我将 myrecipe 添加到 运行 列表的末尾,那么它的内容将在其余食谱之前开始 运行,当然,还有一个 get Failed to open TCP connection to 127.0.0.1:15672 (Connection refused - connect(2) for "127.0.0.1" port 15672)

现在我用这段代码解决了这个问题,但我不喜欢这个,也不明白为什么 declare_exchange 运行 在安装 rabbitmq 之前

include_recipe 'rabbitmq'

rabbitmq_plugin 'rabbitmq_management' do
  action :enable
end

rabbitmq_user 'user' do
  password "321"
  action :add
end

rabbitmq_vhost 'myvhost' do
  action :add
end

rabbitmq_user 'user' do
  vhost 'myvhost'
  permissions ".* .* .*"
  action :set_permissions
end


rabbitmq_user 'user' do
  tag 'administrator'
  action :set_tags
end

rabbitmq_user "guest" do
  action :delete
  notifies :run, 'ruby_block[declare_rmq_exchange]'
end

chef_gem 'rabbitmq_http_api_client' do
  version                    '1.8.0'
  action                     :install
end

require "rabbitmq/http/client"
endpoint = "http://127.0.0.1:15672"

ruby_block 'declare_rmq_exchange' do
  block do
    client = RabbitMQ::HTTP::Client.new(endpoint, :username => "user", :password => "321")
    client.declare_exchange("myvhost", "myexchange", durable: true, type: "direct")
  end
  action :nothing
end

这是chef-client的two-phase model造成的。首先,执行ruby代码(编译阶段),然后执行定义资源(如rabbitmq_userchef_gem)的实现( 收敛阶段).

由于您对 RabbitMQ::HTTP::Client.new 的调用是在编译阶段执行的,因此它会在用户设置之前首先执行。

将此代码包装在 ruby_block 资源中,以便按预期顺序执行。