Chef Data bag tutorials
What is Chef Data bags?
A data bag is a global variable that is stored as JSON data and is accessible from a Chef server. A data bag is indexed for searching and can be loaded by a recipe or accessed during a search.
Elements of Chef databags?
- DATA BAG
- DATA BAG ITEM
- DATA BAG ITEM ELEMENTS
How to create data bags?
A data bag can be created in two ways: using knife or manually. In general, using knife to create data bags is recommended
Create data bags using knife
knife data bag create cts_data_bag
knife data bag create cts_data_bag cts_data_bag_item
Create data bags using Manually
$ mkdir data_bags
$ mkdir data_bags/hooks
$ knife data bag create hooks
$ vi data_bags/hooks/request_bin.json
{
"id": "request_bin",
"url": "http://requestb.in/1abd0kf1"
}
Chef Data Bag Use Case 1
$ vi cookbooks/my_cookbook/recipes/default.rb
hook = data_bag_item('hooks', 'request_bin')
http_request 'callback' do
url hook['url']
end
Chef Data Bag Use Case 2
knife download data_bags
knife data bag from file BAG_NAME ITEM_NAME.json
knife data bag from file cts_data_bag cts_data_bag_item
What Json Contents:
{
'id': 'cts_data_bag_item',
'name': "rajesh kumar"
}
$ knife search cts_data_bag ("*:*")
$ knife search cts_data_bag "(*)"
$ knife search cts_data_bag "(NOT id:admin_users)"
# => variable 'boy' is set to the cts_data_bag data bag item
boy = search(:cts_data_bag, "id:cts_data_bag_item").first
boy["name1"]
# => "ops"
charlie["shell"]
# => "/bin/zsh"
Chef Data Bag Use Case 3
boy = search(:cts_data_bag, "id:cts_data_bag_item").first
package "httpd"
service "httpd" do
action :start
end
file '/var/www/html/index.html' do
content "This is php version - #{node["version"]} -- #{boy["name1"]}"
end