How to set environment variable in crontab using chef?

I have a recipe that defines jobs to run from an EC2 crontab instance. Here is an example recipe that I run:

cron "examplejob" do minute "0" hour "2" command "job" user "job" end 

This works great. In addition to this cron job, I also want to set several environment variables in crontab. Reading this , it should be possible to use the path attribute. However, I cannot find a concrete example of how to implement this.

I tried:

 cron "env" do path "MY_VAR=/path/for/variable" end 

But that does not work. How can I set environment variables at the top of crontab? Any insight appreciated! Thanks.

+4
source share
2 answers

I believe the answer you are looking for is the environment attribute that the Hash object expects.

See http: //docs.opscodecode/chef/resources.html#arguments and https://github.com/opscode/chef/commit/96ef7d770a7d898fdce097c7fda9039abf7bf485

To set up a custom environment variable, you should write the following

 my_env_vars = {"env1" => "val1", "env2" => "val2"} cron "env" do environment my_env_vars command "/path/to/job -someoption" end 

The chef will iterate over your hash, and you should see the following in sudo crontab -e

 # Chef Name: env env1=val1 env2=val2 * * * * * /path/to/job -someoption 

Quick note: on my machine with a chef 10.16.2 passing the hash directly to the cron stanza will return a syntax error. syntax error, unexpected tASSOC, expecting '}' Not that you passed in the hash anyway, but I thought it was worth mentioning, as someone else could repeat my same error. Once you throw the hash into a variable, everything works as expected.

+5
source

Amounts of data with a top-level key that matches your environment. The Opscode wiki has a quick and accurate description of how you could do this. Bags and data environments As per your previous example:

 cron "[node.chef_environment]" do path "bag_item[node.chef_environment]["path_for_variable"]" end 

Alternatively, if you want a fantasy, you can use Templates your data packets and just call the template in the recipe. This applies if you have crontab calling the same function with just another variable. Thus, you can edit the template every time you need, and it will be displayed in different environments.

-1
source

Source: https://habr.com/ru/post/1440396/


All Articles