Chef - Data Bags


Chef data bags can be defined as an arbitrary collection of data which one can use with cookbooks. Using data bags is very helpful when one does not wish to hardcode attributes in recipes nor to store attributes in cookbooks.

Working Method

In the following setup, we are trying to communicate to http endpoint URL. For this, we need to create a data bag, which will hold the endpoint URL detail and use it in our recipe.

Step 1 − Create a directory for our data bag.

mma@laptop:~/chef-repo $ mkdir data_bags/hooks

Step 2 − Create a data bag item for request bin. One needs to make sure one is using a defined requestBin URL.

vipi@laptop:~/chef-repo $ subl data_bags/hooks/request_bin.json { 
   "id": "request_bin", 
   "url": "" 

Step 3 − Create a data bag on the Chef server

vipin@laptop:~/chef-repo $ knife data bag create hooks 
Created data_bag[hooks] 

Step 4 − Upload the data bag to the Chef server.

vipin@laptop:~/chef-repo $ knife data bag from file hooks requestbin.json 
Updated data_bag_item[hooks::RequestBin]

Step 5 − Update the default recipe of the cookbook to receive the required cookbook from a data bag.

vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/recipes/default.rb 
hook = data_bag_item('hooks', 'request_bin') 
http_request 'callback' do 
   url hook['url'] 

Step 6 − Upload the modified cookbook to the Chef server.

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

Step 7 − Run the Chef client on the node to check if the http request bin gets executed.

user@server:~$ sudo chef-client 
[2013-02-22T20:37:35+00:00] INFO: http_request[callback] 
GET to successful 

How it Works

Data bag is a named collection of structure data entries. One needs to define data entry and call the data bag item in JSON file. One can also search for data bag item from within the recipes to use the data stored in the data bags.

We created a data bag called hooks. A data bag is a directory within Chef repository. We used knife to create it on the server.