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

笑着哭i 提交于 2019-12-05 03:32:36
Igor Serebryany

after a resounding lack of answers both here and on the opscode chef mailing list, i ended up using the following 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

i put this into the libraries dir in my cookbook; now i can use attribute.to_hash in both chef 10 (which already worked properly and which is unaffected by this monkey-patch) and chef 11. i've also reported this as a bug to opscode:

if you don't want to have to monkey-patch your chef, speak up on this issue: http://tickets.opscode.com/browse/CHEF-3857

Update: monkey-patch ticket was marked closed by these PRs

I hope I am not too late to the party but merging the node object with an empty hash did it for me:

chef (12.6.0)> {}.merge(node).class
 => Hash

I had the same problem and after much hacking around came up with this:

json_string = node[:attr_tree].inspect.gsub(/\=\>/,':')
my_hash = JSON.parse(json_string, {:symbolize_names => true})

inspect does the deep parsing that is missing from the other methods proposed and I end up with a hash that I can modify and pass around as needed.

The above answer is a little unnecessary. You can just do this:

json = node[:whatever][:whatever].to_hash.to_json
JSON.parse(json)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!