Chef - Roles


Advertisements

Roles in Chef are a logical way of grouping nodes. Typical cases are to have roles for web servers, database servers, and so on. One can set custom run list for all the nodes and override attribute value within roles.

Create a Role

vipin@laptop:~/chef-repo $ subl roles/web_servers.rb 
name "web_servers" 
description "This role contains nodes, which act as web servers" 
run_list "recipe[ntp]" 
default_attributes 'ntp' => { 
   'ntpdate' => { 
      'disable' => true 
   } 
}

Once we have the role created, we need to upload to the Chef server.

Upload Role to Chef Server

vipin@laptop:~/chef-repo $ knife role from file web_servers.rb 

Now, we need to assign a role to a node called server.

Assign a Role to Node

vipin@laptop:~/chef-repo $ knife node edit server 
"run_list": [ 
   "role[web_servers]" 
] 
Saving updated run_list on node server 

Run the Chef-Client

user@server:~$ sudo chef-client 
...TRUNCATED OUTPUT... 
[2013-07-25T13:28:24+00:00] INFO: Run List is [role[web_servers]] 
[2013-07-25T13:28:24+00:00] INFO: Run List expands to [ntp] 
...TRUNCATED OUTPUT... 

How It Works

  • Define a role in a Ruby file inside the roles folder of Chef repository.

  • A role consists of a name and a description attribute.

  • A role consists of role-specific run list and role-specific attribute settings.

  • Every node that has a role in its run list will have the role’s run list exacted into its own.

  • All the recipes in the role’s run list will be executed on the node.

  • The role will be uploaded to Chef server using the knife role from file command.

  • The role will be added to the node run list.

  • Running Chef client on a node having the role in its run list will execute all the recipes listed in the role.

Advertisements