Jayesh Dhandha
Jayesh Dhandha

Reputation: 2129

How to terminate ec2 instance 1 hour after uptime

I want to terminate my ec2 instance between 1hour and 1h30 min (random interval) after it starts.

How can i achieve this?

Using cron job or at command

Below is the working code, But it will be good if i can do this using crontab instead of sleep command.

sleep $(shuf -i 3600-5400-n 1) && aws ec2 terminate-instances --instance-ids $AWS_INSTANCE_ID --region ${region}

Thanks

Upvotes: 0

Views: 846

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 270124

When the instance starts, you could run a script (eg via User Data) that:

  • Sleeps for the desired time period (eg sleep 3600)
  • Does a shutdown (eg sudo shutdown -h now)

Be sure to set your termination behaviour to Terminate otherwise the instance will simply stop.

Upvotes: 1

Related Questions