Chef の Attributes を yaml に書き出す
chef の attributes を yaml に書きだそうと思ったとき、
require 'yaml' file "/path/to/file.yml" do content YAML.dump(node[:yaml]) end
といったコードを思い浮かべると思いますが、
これでは以下のページのように、Object 名や、意図しない要素まで出力されてしまいます。
chef - How to create hash or yml from top level attributes values of node? - Server Fault
通常上記ページの通り、to_hash してから YAML.dump で解決できますが、
attributes に要素を追加したい場合は、node が Immutable な Object なのでできません。
具体的な例としては、attributes に data_bags で隠蔽している値を追加したい場合が挙げられます。
最適な方法ではないと思いますが、以下の方法で解決できます。
dbi = data_bag_item("user", "config") config = JSON.parse(node[:yaml].to_json) config["password"] = dbi[:password] file "/path/to/file.yml" do content YAML.dump(config) end
JSON 文字列 -> hash に変換することで、Immutable の制約か逃れられます。
JSON.parse で変換した時に、symbol ではアクセスできなくなりますので注意が必要です。
強引ですが楽な方法の紹介でした(コストの面で最適かは考慮していません)。