0

I am trying to render a yaml object in chef template it is working fine but as we know in yaml spaces also matters so it is creating new properties.

collection: <%= @collection.to_hash.to_yaml %>

Where collection is a json object

collection = { "name": "col1", "nested": { "nKey": 1 } }

Expected result is

collection:
  name: col1
  nested:
    nKey: 1

Getting result

collection: ---
  name: col1
nested: !ruby/hash:Mash #nested is not part of collection.
  nKey: 1

And second is there any way to remove types(!ruby/hash:Mash) and --- from to_yaml function ?

9me
  • 1,078
  • 10
  • 36
  • I am not sure about your use case. I think the best would be using file resource with to_yaml output as a content (instead of the template). As for Mash comment, you have to run the nested to_hash conversion, your data is probably coming from a node object, not a json. `---` could be gsub'ed(?) – Szymon Jul 25 '18 at 17:40
  • Thank you for your reply, I have one role from chef server. Then based on that role i want to render a template. everything is working fine except nested object. this is my whole use-case. instead of making nested properties it is making straight properties as I showed in my code example. – 9me Jul 26 '18 at 06:00

1 Answers1

0

You usually want to use to_json, since all JSON is valid YAML. It's a bit ugly, but usually works better :)

coderanger
  • 52,400
  • 4
  • 52
  • 75
  • Sorry its not working for me. i tried both options `collection: <%= @collection.to_json %>` and `collection: <%= @collection.to_json.to_yaml %>`. to_josn is giving only json but i need YAML file. so it is creating only one string line which is `collection: --- '{ "name": "col1", "nested": { "nKey": 1 } }' %>` which is not useful in yaml file :-( Thank you – 9me Jul 26 '18 at 11:46
  • That is fine in a YAML file. As I said, it's ugly but works. YAML is a superset of JSON. – coderanger Jul 26 '18 at 15:51