'How to stop ec2 with crontab at @reboot?

I am using crontab on a Linux ec2 to run some code when the instance starts. The first two lines of the crontab run correctly, but I cannot make the instance stop after 120 seconds.

@reboot python3 run.py
@reboot python3 run2.py
@reboot sleep 120 aws ec2 stop-instances --instance-ids i-059............

If I run the was command in the terminal works without issues, is only in crontab that does not work.



Solution 1:[1]

This is a complete command:

sleep 120

This is another complete command:

aws ec2 stop-instances --instance-ids i-059

You can't just smash multiple commands together like you are attempting. If you tried running sleep 120 aws ec2 stop-instances --instance-ids i-059 you would see an error message. That error message is also probably showing up in your server's cron log.

The solution is to place a semicolon delimiter between the commands, like so:

sleep 120 ; aws ec2 stop-instances --instance-ids i-059

This tells the Linux shell to run the first command and wait for it to finish, then run the second command.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark B