How print or debug Chef attributes

Cherry picture Cherry · Dec 12, 2014 · Viewed 17k times · Source

I created a Chef cookbook with attributes, then tried to boostrap a code to node and pass additional attributes in addition and/or override the defaults.

Is it possible to print an attribute tree to see what attributes are loaded, and which are overridden?

Answer

keen picture keen · Sep 14, 2015

To get the entire attribute tree from inside a converged Chef, as opposed to via knife from Chef Server, which is useless in a solo environment, in a useful form look at node.to_hash. More information is in "Chef::Node".

To get a pretty printed log you can use Chef's JSON library's pretty printer:

output="#{Chef::JSONCompat.to_json_pretty(node.to_hash)}"
log output

or write a file local to your client:

output="#{Chef::JSONCompat.to_json_pretty(node.to_hash)}"
file '/tmp/node.json' do
  content output
end

Note that this is the converged node, so you won't get the default/override/etc. levels you can get with node.debug_value, but if you don't actually know the name/path of the attribute, or you need to loop over a number of attributes, this could be your friend.

You'll get a huge result that looks like this highly trimmed example:

{
  "chef_type": "node",
  "name": "node.example.com",
  "chef_environment": "_default",
  "build-essential": {
    "compile_time": false
  },
  "homebrew": {
    "owner": null,
    "auto-update": true,
  ...
  },
  "recipe": [
    "example"
  ],
  "run_list": [
    "recipe[example]"
  ]
}

"How do you create pretty json in CHEF (ruby)" had the pretty printer pointer.