Tuesday, May 18, 2021

How to access Chef node attributes from Inspec

When testing existing servers for compliance, I get attribute values using the knife command on the server being tested: 

require 'json'
attr_json = JSON.parse(command("knife node show -c /etc/chef/client.rb #{sys_info.hostname('full')} -a 'my.attrib.name' -Fjson").stdout) 

Now, we can access the attribute value using attr_json.values[0]['my.attrib.name'] or attr_json[sys_info.hostname('full')]['my.attrib.name']

As you can see, nodes are named after the server's full hostname, but in case you use a different naming convention, you can get the node name from node_name in /etc/chef/client.rb