Chef 简明教程

Chef - Environment Variable

环境变量是让 Chef 配方在任何特定节点上成功运行的关键方法。有许多办法可以做到这一点,可以手动设置它们,也可以使用 Shell 脚本。在此处,我们需要通过配方来设置它们。

Environment variable is a key way to make Chef recipe run on any particular node successfully. There are multiple ways of doing it, either manually setting them up or by using a Shell script. Setting them via recipe is what we need to perform here.

为此,我们需要有一个食谱手册,在这里我们将使用 test_cookbook 和包含 test_cookbook 的运行列表。

To do this, we need to have a cookbook here we would use test_cookbook and a run list which contains test_cookbook.

Setting Environment Variable Using Chef Recipe

Step 1 - 使用环境变量更新 cookbook 的默认配方。

Step 1 − Update the default recipe of cookbook with an environment variable.

vipin@laptop:~/chef-repo $ subl cookbooks/test_cookbook/recipes/default.rb
ENV['MESSAGE'] = 'Testing environment variable update with chef !'
execute 'print value of environment variable $MESSAGE' do
   command 'echo $MESSAGE > /tmp/message'
end

Step 2 - 将更新的 cookbook 上传到服务器。

Step 2 − Upload the updated cookbook to the server.

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

Step 3 - 运行 Chef 客户端以创建临时文件。

Step 3 − Running the Chef client to create a temp file.

user@server:~$ sudo chef-client
...TRUNCATED OUTPUT...
[2013-01-25T15:01:57+00:00] INFO: Processing execute[print
value of environment variable $MESSAGE] action run
(my_cookbook::default line 11)
[2013-01-25T15:01:57+00:00] INFO: execute[print value of
environment variable $MESSAGE] ran successfully
...TRUNCATED OUTPUT...

Validating Variable

user@server:~$ cat /tmp/message
Hello from Chef

Working Method

Ruby 通过 ENV –a 哈希公开当前的环境变量,以读取和修改环境变量。

Ruby exposes the current environment variable via ENV –a hash to read and modify the environment variable.

Execute Resource

我们可以在 cookbook 的 Chef 默认配方中使用 execute 资源来执行相同的操作。

We can use execute resource to do the same inside the Chef default recipe of cookbook.

mma@laptop:~/chef-repo $ subl cookbooks/test_cookbook/recipes/default.rb
execute 'print value of environment variable $MESSAGE' do
   command 'echo $MESSAGE > /tmp/message'
   environment 'MESSAGE' => 'Hello from the execute resource'
end

Note - 使用 ENV 设置环境变量将在整个 Chef 运行过程中使该变量可用。相反,将其传递给 execute 资源将仅使其可用于资源执行的命令。

Note − Setting an environment variable using ENV will make that variable available during the whole Chef run. In contrast, passing it to the execute resource will only make it available for that one command executed by the resource.