English 中文(简体)
Chef - Environment Variable
  • 时间:2024-12-22

Chef - Environment Variable


Previous Page Next Page  

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.

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

Setting Environment Variable Using Chef Recipe

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 − Upload the updated cookbook to the server.

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

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

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

Vapdating Variable

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

Working Method

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

Execute Resource

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 − 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.

Advertisements