Chef recipe detect role assigned to node use in guards


Currently I have lots of recipes / cookbooks that build up a traditional 3rd party application stack.

Some actions are only required to be run on certain types of nodes. Looking at the Role documentation you can assign custom run_lists to roles.

I’d like to do this the other way round in a Chef Guard.


directory ‘C:\mordor’ do
rights :read, ‘MORDOR\Minions’
rights :full_control, ‘MORDOR\Sauron’
only_if { node role includes “DatabaseServer”}

is this possible at all?

Many thanks for reading.


I would not suggest that approach. You want to control that with some kind of node['database']['needs_mordor'] attribute to control it and then in the roles that need mordor you set that attribute to true. If you find yourself duplicating lines all over the place in roles that’s probably an indication that you have a broader type of server which itself needs to be a role that is mixed into all the sub roles.

If you’re worried about setting attributes in role files (since they’re not versioned) you should already be using the role cookbook pattern (and if you’re fighting with follow-on problems, then you probably want to be using policyfiles and move on from roles+environments entirely).

1 Like

Hi Lamont,

many thanks for your full response - appreciated.

to clarify my setup : If i have one particular server that will run 100% of the application stack and all others in the farm use 60% I was looking at how to identify that primary server within a chef run.

I'm currently using the chef wrapper cookbook pattern ...

with one cookbook containing all the recipes / templates etc and the wrapper cookbooks having all the environmentally unique data -:

appcookbook, appcookbook_dev, appcookbook_test, appcookbook_uat, appcookbook_prd

Your solution
To confirm then with your response I'd first create an attribute :

default['application_x']['version']['primary_node'] = false

and in the role assigned to the primary node set as true to override it.

Then to switch this between nodes its simply a case of moving that role to the new server.

That would work for us and obviously i want any solution to fit into native Chef architecture / processes.

Queries :

  1. Would migrating away from environmental wrapper cookbooks to policy files provide any other solutions to this problem?

  2. Should we migrate to policy files anyway as thats a better approach? We'll be implementing Chef Automate with potentially multiple organisations shortly.

Many thanks