Chef 简明教程
Chef - Dynamically Configuring Recipes
属性是动态配置配方的主要组件。属性使作者可以配置配方。通过覆盖配方中设置的默认值,用户可以注入他们自己的值。
Attributes are the key components for dynamically configuring cookbooks. Attributes enable the authors to make the cookbook configurable. By overriding default values set in cookbooks, the user can inject their own values.
Step 1 - 为配方属性创建一个默认文件并向其添加一个默认属性。
Step 1 − Create a default file for cookbook attributes and add a default attribute to it.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/attributes/default.rb
default['my_cookbook']['message'] = 'hello world!'
Step 2 - 在食谱中定义属性。
Step 2 − Define the attribute inside the recipe.
vipin@laptop:~/chef-repo $ subl cookbooks/<Cookbook Name>/recipes/default.rb
message = node['my_cookbook']['message']
Chef::Log.info("** Saying what I was told to say: #{message}")
Step 3 − 上传已修改的 cookbook。
Step 3 − Uploading the modified cookbook.
vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook
Uploading my_cookbook [0.1.0]
Step 4 − 运行已定义节点的 Chef 客户端。
Step 4 − Running Chef-Client of the defined node.
user@server:~$ sudo chef-client
...TRUNCATED OUTPUT...
[2013-01-13T20:48:21+00:00] INFO: ** Saying what I was told to
say: hello world!
...TRUNCATED OUTPUT...
Working Method
Chef 在执行属性之前加载属性文件中的所有属性。这些属性保存在节点对象中。可以在配方中访问保存在节点对象中的所有属性,并检索其当前值。
Chef loads all attributes from the attribute file before it executes them. The attributes are stored with the node object. One can access all the attributes stored with the node object within recipes and retrieve their current values.
Chef 具有受限结构,从最底层的默认开始,然后是普通结构(别名为 set),最后是覆盖。配方中设置的属性级别优先于在属性文件中设置的相同级别。
Chef has a restricted structure starting from the default being the lowest, then comes normal (which is aliased with the set) and then overrides. The attribute level set in the recipe has precedence over the same level set in an attribute file.
Overriding Attribute at the Node and Environment Level
在角色或环境中定义的属性具有最高优先级。
Attribute defined in roles or environment have the highest precedence.
Step 1 − 创建角色。
Step 1 − Create a role.
vipin@laptop:~/chef-repo $ subl roles/german_hosts.rb
name "german_hosts"
description "This Role contains hosts, which should print out
their messages in German"
run_list "recipe[my_cookbook]"
default_attributes "my_cookbook" => { "message" => "Hallo Welt!" }
Step 2 − 将角色上传至 Chef 服务器。
Step 2 − Upload the role to Chef server.
vipin@laptop:~/chef-repo $ knife role from file german_hosts.rb
Updated Role german_hosts!
Step 3 − 将角色分配给节点。
Step 3 − Assign the role to a node.
vipin@laptop:~/chef-repo $ knife node edit server
"run_list": [
"role[german_hosts]"
]
Saving updated run_list on node server
Step 4 − 运行 Chef 客户端。
Step 4 − Run the Chef-Client.
user@server:~$ sudo chef-client
...TRUNCATED OUTPUT...
[2013-01-13T20:49:49+00:00] INFO: ** Saying what I was told to
say: Hallo Welt!
...TRUNCATED OUTPUT...