Chef - 在ruby_block中设置实例变量

时间:2017-09-20 05:31:21

标签: chef

简单,尽管有关收敛的新问题。编译时间。假设我在自定义食谱中有以下库

库/ foo.rb

class Chef::Recipe::Foo

  attr_accessor :bar

  def initialize()
    @bar = {}
  end
end

然后我尝试在记录检查之前在bar内设置实例属性ruby_block

配方/ default.rb

foo = Foo.new

ruby_block "set_hash" do
  block do
    foo.bar = {'key' => 'val'}
  end
  action :run
  notifies :write, "log[inspect_hash]", :immediately
end

log "inspect_hash" do
  message foo.bar.inspect
  action :nothing
end

哪个输出空哈希

INFO: Processing ruby_block[set_hash] action run (cookbook::default line 12)
INFO: ruby_block[set_hash] called
INFO: ruby_block[set_hash] sending write action to log[inspect_hash] (immediate)
INFO: Processing log[inspect_hash] action write (cookbook::default line 20)
INFO: {}

根据docs,在上面的运行过程中,类Foo应该已经被实例化,因为编译了配方并且ruby_block被评估为主厨资源

  

ruby​​_block资源中的Ruby代码使用其他资源进行评估   在收敛期间,而Ruby代码在ruby_block资源之外   在配方编译之前,在其他资源之前进行评估。

我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:1)

您应该使用run_state来存储跨多个资源的变量:

ruby_block "set_hash" do
  block do
    node.run_state['foo'] = {'key' => 'val'}
  end
  action :run
  notifies :write, "log[inspect_hash]", :immediately
end

log "inspect_hash" do
  lazy { message node.run_state['foo'] }
  action :nothing
end