Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

`.to_yaml` does not do what one would expect #8820

Open
jaymzh opened this issue Aug 14, 2019 · 4 comments

Comments

@jaymzh
Copy link
Member

commented Aug 14, 2019

Description

node['foo'].to_yaml dumps the entire node object and countless internal references. It should be the same as .to_json, and collapse the attributes below that and then generate yaml.

Chef Version

15.1.36

Platform Version

Ubuntu 18.04

Replication Case

node.default['test'] = {'bar' => ['baz'], 'bing' => 'boo'}
node['test'].to_yaml
@coding-blip

This comment has been minimized.

Copy link

commented Aug 14, 2019

I have seen this issue too, though not directly the same I don't think. What I did to get around it was to first convert to_json and then convert that to_yaml. Not sure if something like this will work for you or not. Who knows, maybe we can both learn a better way to do it!

require 'yaml'

my_hash = {}
node['thing']['config'].each do |config_item, config_value|
  my_hash.merge!(config_item => config_value)
end

# Convert to JSON then YAML in order to process properly
file "#{node['thing']['config_dir']}/config.yml" do
  content JSON.parse(my_hash.to_json).to_yaml.lines.to_a[1..-1].join
end
@jaymzh

This comment has been minimized.

Copy link
Member Author

commented Aug 14, 2019

oh my work around was simple: node['test'].to_json.to_yaml ... but the to_yaml method needs to get fixed.

@mateuszkwiatkowski

This comment has been minimized.

Copy link

commented Sep 9, 2019

It seems that this is caused by yaml (psych) module and is not specific to Chef. Nodes attributes are instance of Chef::Node::ImmutableMash and they can be converted to Hash by .to_h method. Json module checks if object responds to .to_h or .to_hash methods and converts it before doing convertion to JSON. I checked psych source code and didn't find similar logic in there.

node['test'].to_h.to_yaml works too.

@lamont-granquist

This comment has been minimized.

Copy link
Contributor

commented Sep 9, 2019

likely Chef::Node::Attribute just needs:

def to_yaml(*opts)
  to_hash.to_yaml(*opts)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
5 participants
You can’t perform that action at this time.