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?
Best Answer
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: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 toroot
for example.