English 中文(简体)
Dynamically Configuring Recipes
  • 时间:2024-11-03

Chef - Dynamically Configuring Recipes


Previous Page Next Page  

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 − 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 − 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 − Uploading the modified cookbook.

vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook 
Uploading my_cookbook [0.1.0]

Step 4 − Running Chef-Cpent of the defined node.

user@server:~$ sudo chef-cpent 
...TRUNCATED OUTPUT... 
[2013-01-13T20:48:21+00:00] INFO: ** Saying what I was told to 
say: hello world! 
...TRUNCATED OUTPUT... 

Working Method

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 has a restricted structure starting from the default being the lowest, then comes normal (which is apased 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 − 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_pst "recipe[my_cookbook]" 
default_attributes "my_cookbook" => { "message" => "Hallo Welt!" } 

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 − Assign the role to a node.

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

Step 4 − Run the Chef-Cpent.

user@server:~$ sudo chef-cpent 
...TRUNCATED OUTPUT... 
[2013-01-13T20:49:49+00:00] INFO: ** Saying what I was told to 
say: Hallo Welt! 
...TRUNCATED OUTPUT...
Advertisements