Search code examples
rubychef-infrarole

Chef get node's current role


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

Solution

  • 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.