How to add a cron job entry using Chef recipe

cloudbud picture cloudbud · Nov 17, 2015 · Viewed 8.4k times · Source

All,

I have a shell script that is creates tar file of logs. I have embeded the recipe in the cookbook.

The recipe looks like this :

cookbook_file "/var/create-tar.sh" do
source "create-tar.sh"
mode 0755
end

execute "create tar files of logs older than 1 day" do
command "sh /var/create-tar.sh"
end

The execute resource is executing the recipe. I want to schedule this shell script in cron by making an entry in cronjob.

The crontab entry should be :

*/2 * * * * sh -x /var/test.sh  > /var/log/backup 2>&1

How can I add this entry in my recipe?

Answer

StephenKing picture StephenKing · Nov 17, 2015

Cron Jobs in Chef

Chef includes a resource for setting up Cron jobs - it's called cron.

cron 'test' do
  minute '*/2'
  command 'sh -x /var/test.sh  > /var/log/backup 2>&1'
end

But what is your ultimate goal? Log rotation?

Log Rotation with Chef and Logrotate

There is a tool for that, called logrotate and there is a Chef cookbook for that: logrotate.

This gives you a resource that allows to to specify, which logs you want to rotate and with what options:

logrotate_app 'test' do
  path      '/var/log/test/*.log'
  frequency 'daily'
  rotate    30
end

Just in case you want to implement such a thing ;-)