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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With