![如何从节点的顶级属性值创建哈希或 yml?](https://linux22.com/image/796095/%E5%A6%82%E4%BD%95%E4%BB%8E%E8%8A%82%E7%82%B9%E7%9A%84%E9%A1%B6%E7%BA%A7%E5%B1%9E%E6%80%A7%E5%80%BC%E5%88%9B%E5%BB%BA%E5%93%88%E5%B8%8C%E6%88%96%20yml%EF%BC%9F.png)
我有一个 chef 菜谱,我想获取 node['cfn']['environment'] 下的所有属性并将它们写入 yml 文件。我可以这样做(效果很好):
content = {
"environment_class" => node['cfn']['environment']['environment_class'],
"node_id" => node['cfn']['environment']['node_id'],
"reporting_prefix" => node['cfn']['environment']['reporting_prefix'],
"cfn_signal_url" => node['cfn']['environment']['signal_url']
}
yml_string = YAML::dump(content)
file "/etc/configuration/environment/platform.yml" do
mode 0644
action :create
content "#{yml_string}"
end
但我不喜欢必须明确列出属性的名称。如果我稍后添加新属性,最好将其自动包含在写出的 yml 文件中。所以我尝试了这样的方法:
yml_string = node['cfn']['environment'].to_yaml
但是因为该节点实际上是一个 Mash,所以我得到了一个像这样的 platform.yml 文件(它包含很多我不想要的意外嵌套):
--- !ruby/object:Chef::Node::Attribute
normal:
tags: []
cfn:
environment: &25793640
reporting_prefix: Platform2
signal_url: https://cloudformation-waitcondition-us-east-1.s3.amazonaws.com/...
environment_class: Dev
node_id: i-908adf9
...
但我想要的是这个:
----
reporting_prefix: Platform2
signal_url: https://cloudformation-waitcondition-us-east-1.s3.amazonaws.com/...
environment_class: Dev
node_id: i-908adf9
如何才能实现所需的 yml 输出而无需按名称明确列出属性?
答案1
这将达到目的:
yml_string = YAML::dump(node['cfn']['environment'].to_hash)
答案2
这也有效并且更好的 ruby 风格:
yml_string = node['cfn']['environment'].to_hash.to_yaml