Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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?

share|improve this question
1  
Consider /etc/cron.d instead of /etc/crontab. /etc/cron.d is better when using system automation. –  Stefan Lasiewski May 6 '14 at 20:01

1 Answer 1

up vote 5 down vote accepted

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.

share|improve this answer
    
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 '14 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 '14 at 20:09
    
yeah but AFAIK those scripts they run as root only. –  Petter H May 6 '14 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. –  Matt May 6 '14 at 20:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.