Chef 简明教程

Chef - Definition

定义可以定义为一种对资源进行分组的逻辑方法,该资源会被反复使用。在此流程中,我们将资源分组并为它们命名,以重新获取已定义代码的可读性。

Definition can be defined as a logical method of grouping resources, which are used again and again. In this flow, we group the resources and give them a name to regain readability of defined cookbooks.

为此,我们应该有一个代码。在本例中,我们使用 test_cookbook 和节点运行列表,其中包括该代码。

In order to do this, we should have a recipe. In this case, we are using test_cookbook and a run list of nodes, which includes the cookbook.

Creating a Definition

Step 1 − 在代码定义文件夹中创建新的定义文件。

Step 1 − Create a new definition file in the cookbooks definition folder.

vipin@laptop:~/chef-repo $ subl cookbooks/test_cookbook/definitions/
capistrano_deploy_dirs.rb
define :capistrano_deploy_dirs, :deploy_to => '' do
   directory "#{params[:deploy_to]}/releases"
   directory "#{params[:deploy_to]}/shared"
   directory "#{params[:deploy_to]}/shared/system"
end

Step 2 − 在代码默认配方中使用定义。

Step 2 − Use a definition inside the cookbooks default recipe.

vipin@laptop:~/chef-repo $ subl cookbooks/test_cookbook/recipes/default.rb
capistrano_deploy_dirs do
   deploy_to "/srv"
end

Step 3 − 将代码提交到 chef 服务器。

Step 3 − Upload the cookbook to the chef server.

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

Step 4 − 在目标节点上运行 Chef 客户端。

Step 4 − Run the Chef client on the desired node.

vipin@laptop:~/chef-repuser@server $ sudo chef-client
...TRUNCATED OUTPUT...
[2013-01-18T16:31:11+00:00] INFO: Processing directory[/srv/
releases] action create (my_cookbook::default line 2)
[2013-01-18T16:31:11+00:00] INFO: directory[/srv/releases] created
directory /srv/releases
[2013-01-18T16:31:11+00:00] INFO: Processing directory[/srv/
shared] action create (my_cookbook::default line 3)
[2013-01-18T16:31:11+00:00] INFO: directory[/srv/shared] created
directory /srv/shared
[2013-01-18T16:31:11+00:00] INFO: Processing directory[/srv/
shared/system] action create (my_cookbook::default line 4)
[2013-01-18T16:31:11+00:00] INFO: directory[/srv/shared/system]

代码中的定义就像微服务,可以对资源进行分组并为它们命名。某个定义有一个名称,可以使用该名称从代码中分辨出可以调用哪些资源,它还有一个参数列表。

Definition in cookbooks are like micros, which group the resources and give them a name. A definition has a name by which one can tell them from which can be called inside the recipe and it has a list of perimeters.

在定义中,我们有若干参数,在我们的代码中,这些参数如下所示。

In the definition, we have parameters which in our code looks like the following.

…..
directory "#{params[:deploy_to]}/releases"
directory "#{params[:deploy_to]}/shared"
directory "#{params[:deploy_to]}/shared/system”
……

以下是在默认配方中使用它的方法。

It can be used inside the default recipe as follows.

capistrano_deploy_dirs do
   deploy_to "/srv"`
end