Chef - Scripts for Data Bags


Advertisements


In certain conditions, it is not possible to put the server under the full control of Chef. In such cases, one might need to access values in Chef data bags from scripts. In order to do this, one needs to store data bag values in a JSON file and let the added script access those values.

For this, one needs to have a cookbook. In our case we would use test_cookbook as earlier and should have the run list of the node including test_cookbook definition in it.

Working Method

Step 1 − Create a data bag.

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

Step 2 − Create a data bag item.

vipin@laptop:~/chef-repo $ subl data_bags/servers/Storage.json { 
   "id": "storage", 
   "host": "10.0.0.12" 
} 

Step 3 − Update the data bag item.

vipin@laptop:~/chef-repo $ subl data_bags/servers/Storage.json { 
   "id": "storage", 
   "host": "10.0.0.12" 
} 

Using in Cookbook

Step 1 − Need to create a JSON file containing data bag values using the above cookbook so that external scripts can access those values.

vipin@laptop:~/chef-repo $ subl cookbooks/test_cookbook/recipes/default.rb 
file "/etc/backup_config.json" do 
   owner "root"
   group "root" 
   mode 0644 
   content data_bag_item('servers', 'backup')['host'].to_json 
end

Step 2 − Upload test_cookbook to Chef server.

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

Step 3 − Run the Chef client on the node.

user@server:~$ sudo chef-client 
...TRUNCATED OUTPUT... 
[2013-03-14T20:30:33+00:00] INFO: Processing 
file[/etc/backup_config.json] action create 
(my_cookbook::default line 9) 
[2013-03-14T20:30:34+00:00] INFO: entered create 
[2013-03-14T20:30:34+00:00] INFO: 
file[/etc/backup_config.json] owner changed to 0 
[2013-03-14T20:30:34+00:00] INFO: 
file[/etc/backup_config.json] group changed to 0 
[2013-03-14T20:30:34+00:00] INFO: 
file[/etc/backup_config.json] mode changed to 644 
[2013-03-14T20:30:34+00:00] INFO: 
file[/etc/backup_config.json] created file 
/etc/backup_config.json 
...TRUNCATED OUTPUT... 

Step 4 − Validating the content of the generated JSON file.

user@server:~$ cat /etc/backup_config.json 
"10.0.0.12" 

Workflow of Scripts

In the above command, the file resource that we have used which creates JSON file inside the /etc directory is defined in the default cookbook. It gets the file content directly from the data bag using the data_bag_item method. We access the host values from the data bag item and convert it to JSON. The file resource uses the JSON-converted values as its content and writes it to the disk.



Advertisements
E-Books Store