Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect state of aws instance from inside of itself?

I have auto scaling group in EC2 and I want to detect the state of the instance when it is getting terminated, so that I could start exporting log files before it will be terminated.

I know a way to do this is use autoscaling lifecycle hooks but from my understanding I would have to use external monitor which would then have to ssh into instance and do the export of log files. Ideally I would like to find a way on how to detect state of instance from inside (when the auto scaling group sends command to terminate it) so it would do the export on its own without communicating with any other instances. Anyone would know if its possible to do this, if so where could I begin?

like image 738
Tomas Avatar asked Mar 10 '16 10:03

Tomas


1 Answers

Here's a solution, inspired by your idea of checking status...

Get the instance ID

http://169.254.169.254/latest/meta-data/instance-id

Get the instance's Lifecycle State

aws autoscaling describe-auto-scaling-instances --instance-ids <instance-id>

It returns something like:

{
  "AutoScalingInstances": [
      {
          "InstanceId": "i-4ba0837f",
          "HealthStatus": "HEALTHY",
          "AvailabilityZone": "us-west-2c",
          "AutoScalingGroupName": "my-auto-scaling-group",
          "LifecycleState": "InService"
      }
  ]
}

If Lifecycle Hooks are activated, the LifecycleState field would be Pending:Wait when it is being terminated. This would be the signal for your application to shutdown, export log files, etc.

Signal readiness to terminate

Once the application has finished its termination activities, it could signal its readiness to be terminated. This could be done via:

  • Defining a heartbeat value when creating the lifecycle hook, after which the instance is automatically terminated
  • Extending the heartbeat during the shutdown process (see below)
  • When ready to shutdown, stop sending the heartbeat

The heartbeat call would be:

aws autoscaling record-lifecycle-action-heartbeat --lifecycle-hook-name my-lifecycle-hook --instance-id my-instance

In total, the above steps should allow an instance to detect its own state and signal its own readiness to be terminated. (Although, to be accurate, the 'signal' is actually the 'absence' of a signal to keep running.

like image 196
John Rotenstein Avatar answered Sep 21 '22 02:09

John Rotenstein