2

I have a cronjob that calls a rails task that needs access to environment variables (S3 credentials). I have the environment variables set in my .bashrc and I can run the task from the command line, the cronjob though fails due to missing credentials.

If I add the credentials to the crontab then the cronjob executes successfully. My crontab is generated with the whenever gem so I have added the S3 credentials in my schedule.rb like so:

# aws credentials
env :AWS_S3_KEY, ENV['AWS_S3_KEY']
env :AWS_S3_SECRET, ENV['AWS_S3_SECRET']

Is there a way for cron jobs to access the environment variables without specifically setting them in the crontab file while still using the whenever gem?

shane
  • 89
  • 2
  • 11

2 Answers2

4

You should define a custom job_type that takes in those environment variables. An example schedule.rb would be:

every 1.day do 
  job_type :my_custom_rake_job, "cd :path && RAILS_ENV=:environment AWS_S3_KEY=:aws_s3_key AWS_S3_SECRET=:aws_s3_secret bundle exec rake :task --silent :output"
  my_custom_rake_job 'foo:bar', :aws_s3_key => @aws_s3_key, :aws_s3_secret => @aws_s3_secret
end

Now to run whenever to update your crontab you would do the following in bash:

whenever --set "aws_s3_key=$AWS_S3_KEY&aws_s3_secret=$AWS_S3_SECRET" --update-crontab 
Sugam
  • 171
  • 1
  • 8
0

Yes, you will need to set up some script file that will set evniroment variables for cron. See SO question

Community
  • 1
  • 1
Mark Huk
  • 2,379
  • 21
  • 28