ruby - Chef 11 : any way to turn attributes into a ruby hash?

标签 ruby hash attributes chef-infra

我在 chef 属性中为我的服务生成一个配置。但是,在某些时候,我需要将属性混搭转换为简单的 ruby​​ 散列。这曾经在 Chef 10 中运行良好:

node.myapp.config.to_hash

但是,从 Chef 11 开始,这不起作用。只有属性的顶层被转换为散列,然后嵌套值仍然是不可变的混搭对象。修改它们会导致如下错误:

Chef::Exceptions::ImmutableAttributeModification ------------------------------------------------ Node attributes are read-only when you do not specify which precedence level to set. To set an attribute use code like `node.default["key"] = "value"'

我已经尝试了很多方法来解决这个问题,但都不起作用:

node.myapp.config.dup.to_hash
JSON.parse(node.myapp.config.to_json)

json 解析 hack,看起来应该很好用,结果是:

JSON::ParserError
unexpected token at '"#<Chef::Node::Attribute:0x000000020eee88>"'

除了在每本 Recipe 中包含一个嵌套的解析函数之外,是否有任何实际可靠的方法将属性转换为简单、普通、良好的旧 ruby​​ 哈希?

最佳答案

在这里和 opscode chef 邮件列表上都缺乏答案后,我最终使用了以下 hack:

class Chef
  class Node
   class ImmutableMash
      def to_hash
        h = {}
        self.each do |k,v|
          if v.respond_to?('to_hash')
            h[k] = v.to_hash
          else
            h[k] = v
          end
        end
        return h
      end
    end
  end
end

我将其放入我的 Recipe 的库目录中;现在我可以在 Chef 10(已经正常工作并且不受此猴子补丁影响)和 Chef 11 中使用 attribute.to_hash。我也已将此作为错误报告给操作代码:

如果您不想给您的 Chef 打补丁,请就此问题发表意见: http://tickets.opscode.com/browse/CHEF-3857

更新 monkey-patch ticket 已被 these 标记为已关闭PRs

关于ruby - Chef 11 : any way to turn attributes into a ruby hash?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14738364/

相关文章:

ruby - node.js/ruby 与 beanstalkd 的集成

c - C中MD5的实现

python - python属性查找过程如何工作?

ruby - 如何使用正则表达式按 HTML 标签拆分

arrays - Ruby 二维数组到 csv?

perl - Perl 中的 HashMap

c# - 对于名为 "Misc"的类别,CategoryAttribute 返回 "Default"

控制台环境中的 C# 自定义属性验证

Ruby 动态模块混入

Perl - 将文件文本解析为散列