Chef 简明教程
Chef - Data Bags
Chef 数据包可以定义为数据的一个任意集合,可以用于食谱。当不想在食谱中硬编码属性,也不想将属性存储在食谱中时,使用数据包非常有帮助。
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
在下面的设置中,我们尝试与 http 端点 URL 通信。为此,我们需要创建一个数据包来保存端点 URL 详细信息,并在食谱中使用它。
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 - 为我们的数据包创建一个目录。
Step 1 − Create a directory for our data bag.
mma@laptop:~/chef-repo $ mkdir data_bags/hooks
Step 2 - 为请求 bin 创建数据包项。需要确保您使用已定义的 requestBin URL。
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": "http://requestb.in/1abd0kf1"
}
Step 3 - 在 Chef 服务器上创建数据包
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 - 将数据包上传到 Chef 服务器。
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 - 更新食谱的默认食谱,以从数据包接收所需的食谱。
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']
end
Step 6 - 将修改后的食谱上传到 Chef 服务器。
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 - 在节点上运行 Chef 客户端,以检查是否执行了 http 请求 bin。
Step 7 − Run the Chef client on the node to check if the http request bin gets executed.
user@server:~$ sudo chef-client
...TRUNCATED OUTPUT...
[2013-02-22T20:37:35+00:00] INFO: http_request[callback]
GET to http://requestb.in/1abd0kf1 successful
...TRUNCATED OUTPUT...
How it Works
数据包是一个命名的结构数据条目集合。需要定义数据条目并在 JSON 文件中调用数据包项。还可以在食谱中搜索数据包项,以使用存储在数据包中的数据。
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.
我们创建了一个名为 hooks 的数据包。数据包是 Chef 存储库中的一个目录。我们在服务器上使用 knife 创建它。
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.