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-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...
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 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.
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_list "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_list": [ "role[german_hosts]" ] Saving updated run_list on node server
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...