Chef 简明教程

Chef - Roles

Chef 中的角色是按逻辑方式分组节点的一种方式。通常情况下,角色用于 Web 服务器、数据库服务器等。用户可以设置所有节点的自定义运行列表并覆盖角色中的属性值。

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
   }
}

一旦创建了角色,我们需要将角色上传到 Chef 服务器。

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

现在,我们需要为名为 server 的节点分配一个角色。

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

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

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

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

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

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

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

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

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