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

时间:2017-03-21 13:33:41

标签: rubygems chef chef-recipe

我在厨房流浪汉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]"

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

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

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

1 个答案:

答案 0 :(得分:2)

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

当您在编译阶段执行对RabbitMQ::HTTP::Client.new的调用时,它会在用户设置之前执行。

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