3

I'm trying to add two lines to the root crontab when building an AWS instance. I have a set of commands that are part of the "user data". These commands are run as root when creating the instance. I would like to add these two lines to the crontab:

@daily /home/ubuntu/db-backup-to-s3-daily.sh
@hourly /home/ubuntu/db-backup-to-s3-hourly.sh

I am using the following approach (based on an answer to this question):

(crontab -u ubuntu -l ; echo -e "@daily /home/ubuntu/db-backup-to-s3-daily.sh\n@hourly /home/ubuntu/db-backup-to-s3-hourly.sh") | crontab -u ubuntu -

However, this does not work when the instance is being created, but it does work if I log in and run this line. Is there any different way that I can append lines to the crontab?

2
  • 1
    Consider /etc/cron.d instead of /etc/crontab. /etc/cron.d is better when using system automation. May 6, 2014 at 20:01
  • just wondering how you managed you aws secret keys with this? Specifically, how and where did you set the AWS_CONFIG_FILE variable so that cron is aware of it? Nov 24, 2015 at 9:38

1 Answer 1

7

If you are trying to mange crontabs programmatically, just create a file in /etc/cron.d/ for example, /etc/cron.d/example-cron, and populate it with the aforementioned lines:

@daily ubuntu /home/ubuntu/db-backup-to-s3-daily.sh
@hourly ubuntu /home/ubuntu/db-backup-to-s3-hourly.sh

The only difference is that you have to include a user to run the cron as, as the second argument. I set it to ubuntu in the example above, but you could set it to root for example.

4
  • The cron.d directories exist to solve issues like that. You can find a lot of *.d folders under /etc, and it makes life easier using them. I Agree with Kevin , this is best practice. And BTW crontabs they're (typically) stored uncer /var/spool/cron.
    – Petter H
    May 6, 2014 at 20:05
  • On that note, he could also place each script directly in /etc/cron.daily/, and /etc/cron.hourly/ respectively. But I figured this way was the path of least resistance.
    – Soviero
    May 6, 2014 at 20:09
  • yeah but AFAIK those scripts they run as root only.
    – Petter H
    May 6, 2014 at 20:21
  • echo "@daily ubuntu /home/ubuntu/db-backup-to-s3-daily.sh" >> /etc/cron.d/example-cron etc. To get root you may need to do a sudo tee combination.
    – hookenz
    May 6, 2014 at 20:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .