Automatically Assign Node Roles Based on Node Hostname

Is there any way for Chef Server to automatically assign a role (or run list) to a node based on the node’s hostname, or some other kind of pattern matching? (For example, the node checks in and says “Hey my name is”, and Chef Server says “Okay, you’ll be assigned to the webapp role.”)

I know I can assign a role (or run list) to a node during the node’s bootstrap process but I was under the impression I could assign this information via Chef Server too.

I don’t think there’s anything that does this automatically.

You can craft custom bootstrap logic to apply to your node on startup, as well as write a recipe that reads the node’s hostname and applies a particular run list based on the value.

Our team is very much against the hostname having any meaning - using the roles applied at bootstrap to control the node, but I see how this can have some value for you.

1 Like

Another way is to have a separate node running that logic on top of chef-provisioning resources like chef_node.

Not sure if that’s much more complicated compared to a custom bootstrap process.

Here is how I solve basically the same issue:

I am using a standard bootstrap process. It includes exactly one cookbook that I call “main”.

The main::default recipe contains the business logic that decides which recipes, roles, etc. to add to the node - in my case, simply a big case statement that keys off the node name (my environment is small enough to do that). In your case, this recipe would parse out the node name (or the FQDN - which may or may not be the same) or whatever other values are appropriate.

The main::default recipe also contains some standard code that applies to all nodes, in my case things like making sure SELinux is enabled, SSH is locked down, etc.

So on the first chef run (during bootstrap), your system will only be prepped with some basic functionality. On the second chef run, the “real” run list (which still includes the “main” cookbook) will be executed.

Kevin Keane
The NetTech
Our values: Privacy, Liberty, Justice


I’ve been doing something like this with a two-pass bootstrap. The initial
chef-client run bootstraps the node and looks up the desired configuration
from a topology data bag on the Chef Server using either the node name or
an assigned node type, setting it using the chef_node resource. The second
run then does the real work. More details in my blog
the knife-topo plugin for
managing the topology data bag, and topo cookbook to do the initial run.


Kevin, would you mind sharing the skeleton of your .rb file? I’m attempting to do the same thing, but my knowledge of Chef is still very limited, and my Ruby skills are virtually nonexistent. If you could give me a starting point, I’d be very grateful.