Zoomzoom
Zoomzoom

Reputation: 1052

How to terminate EC2 instance from user-data script on the instance itself immediately?

I have some user-data script that configures some applications on My EC2 instances. I want a new instance to be terminated immediately if a certain condition occurs during that script run.

I've tried both the following commands in the script. However, the termination does not occur until 10+ minutes after the command is issued.

aws autoscaling terminate-instance-in-auto-scaling-group --instance-id $instanceid --no-should-decrement-desired-capacity


aws ec2 terminate-instances --instance-ids $instanceid 

Is there any way to force the termination to occur sooner?

Upvotes: 0

Views: 2764

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 270029

Rather than asking the Amazon EC2 service to terminate an instance, you can simply call the Operating System and tell it to Stop the instance:

sudo shutdown now -h

(The -h tells it to 'halt' the virtual hardware, which signals to the EC2 instance that the computer is now turned off, much like your home computer turns itself off after a 'Shutdown' command.)

Depending upon the configured Shutdown Behavior of the instance, it will either move into the Stopped or Terminated state.

I notice that you are using Auto Scaling. If Auto Scaling notices an instance is stopped/terminated, it will automatically launch a replacement. However, it might take a few minutes to detect this and launch a replacement.

Upvotes: 5

Related Questions