Cherry
Cherry

Reputation: 33544

How print or debug Chef attributes

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?

Upvotes: 22

Views: 24070

Answers (4)

keen
keen

Reputation: 850

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.

Upvotes: 19

Deepan Prabhu Babu
Deepan Prabhu Babu

Reputation: 912

At times, it might be easy to read the variables off a node, after they are provisioned.

knife node edit <hostname-here> -a

Upvotes: 1

wisbucky
wisbucky

Reputation: 37827

Forking the answer by @keen, this produces a more human readable output in YAML format.

output = node.to_yaml
file '/var/node.yaml' do
  content output
end

Upvotes: 3

Tejay Cardon
Tejay Cardon

Reputation: 4223

You can use node.debug_value to show a single attribute. This will print out the value for that attribute at each level. However, doing this at each level for each attribute is harder (I'm not sure of a way to do it). Furthermore, because of the massive volume of attributes from ohai, I'm not sure you'd even want to do it.

If your chef run is completing correctly, you can do a knife node show -l <nodename> (that's a lower case L). That will show you the actual value, but it provides a huge volume of data, and doesn't tell you which values are default, normal, override, etc.

Upvotes: 8

Related Questions