3

I have a bit of code like this that makes an array of all nodes matching the search criteria. I have a whole bunch of different flavors of load balancer, each of which has it's own Chef role.

I can see what I want with knife node edit max_data_lb-1

  "run_list": [
  "role[max_data_lb]"
]

I am looking to pull out the role and put it in a variable for later use. I've seen a lot of ways that I can check if a specific role is in the current run_list like this node.role?('name'), but that only returns a boolean. I can't figure out how to return the array of roles in the run_list.

  flavor = '#{node.role}'
# Somehow scrapes the node data for the role on the currently processing node.
#max_data_lb in one of my cases.

⚠ lb_q = "roles:#{flavor} AND chef_environment:#{node.chef_environment}"
  lb_array = search(:node, lb_q, filter_result: { fqdn: ['fqdn'] }).map { |n| n['fqdn'] }.sort


#Code I'm trying to generalize and replace
⚠ #max_data_lb_q = "roles:max_data_lb AND chef_environment:#{node.chef_environment}"
⚠ #max_data_lb_array = search(:node, q, filter_result: { fqdn: ['fqdn'] }).map { |n| n['fqdn'] }.sort

⚠ #maxapi_lb_q = "roles:max_api_lb AND chef_environment:#{node.chef_environment}"
⚠ #maxapi_lb_array = search(:node, q, filter_result: { fqdn: ['fqdn'] }).map { |n| n['fqdn'] }.sort
Brando__
  • 365
  • 6
  • 24

1 Answers1

4

Node has a roles attribute, where Chef automatically stores all the roles from the node's run list. You can access it from the recipe like that:

my_roles = node['roles'] #or node[:roles] 

Whichever you prefer (strings or symbols) to access attributes.

Draco Ater
  • 20,820
  • 8
  • 62
  • 86
  • Looks good to me, thanks. Where is this documented? I looked for quite a while before I asked. http://www.rubydoc.info/gems/chef/Chef/Node, particularly here – Brando__ May 02 '17 at 05:49
  • We don't recommend you use the auto-generated docs, Chef does not use YARD consistently (but we're working on it). – coderanger May 02 '17 at 05:53
  • As for the various automatic attributes (mostly from Ohai) there are too many to list everything but some main ones are documented at https://docs.chef.io/attributes.html#automatic-ohai – coderanger May 02 '17 at 05:54