User
User

Reputation: 2148

Self-terminating EC2 instance from autoscaling group in Amazon

I'm running custom transactional tasks on my EC2 instances. The decision to shutdown or not an instance is taken under many conditions by special process running on this instance. The termination should be done by instance itself, because Autoscaling Group does not know when data processing is finish. Do the following steps are consistent with the philosophy of AWS?

  1. Creates AMI with option: "Shutdown behaviour: Terminate".
  2. Autoscaling group creates a new instance with option "Protect From Scale In".
  3. Custom process on EC2 calls command:

    $ sudo shutdown -P now
    

    to terminate an instance in proper time.

Is that correct? Or maybe AWS has some tools to do that, eg. emit special signal to terminate an instance?

Thank you

Upvotes: 1

Views: 1865

Answers (2)

bpeikes
bpeikes

Reputation: 3695

We have a similar pattern, but getting a working solution seems kludgy. We do it a little differently:

  1. Start with Protect From Scale In
  2. When processing is complete, have the instance turn of it's "Protect From Scale In" flag
  3. Have instance trigger the Scale-In policy, by reducing count by 1.
  4. ASG then terminates this instance and doesn't restart a new one because scale in was called

One of the things I don't like about this is that you end up with creating the IAM Role for the EC2 instances, then create the ASG, then go back and update the IAM Role, to give it permissions to SetInstanceProtection and ExecutePolicy for it's own group. You need to do this because we couldn't figure out how to create a policy that referenced the autoscalegroup that the caller is in.

Did you ever resolve this with a different solution?

Upvotes: 0

Rodrigo Murillo
Rodrigo Murillo

Reputation: 13640

That process has one issue I believe:

In step 1, the "Shutdown behaviour: Terminate" option is not an AMI level setting. It is a launch time setting, for instances launched outside of an autoscaling group.

Within an Autoscaling Group, there is no option to configure a Launch Configuration with the equivalent of "Shutdown behaviour: Terminate". Presumably, ASG instances must be terminated during scale in events.

The simple approach would be to have the instance call the AWS CLI terminate-instances command:

aws ec2 terminate-instances --instance-ids i-xxxxxxxx

You would need to acquire the instance id from the AWS Metadata in order to run the terminate-instances command.

Upvotes: 0

Related Questions