Skip to content

Instantly share code, notes, and snippets.

@smstec
Last active May 10, 2019 13:22
Show Gist options
  • Save smstec/d4682c94f677b782895f80db3db38cfd to your computer and use it in GitHub Desktop.
Save smstec/d4682c94f677b782895f80db3db38cfd to your computer and use it in GitHub Desktop.
AWS Auto Scaling Group Clean Shutdown
import datetime
from time import sleep
import boto3
import requests
SPOT_URL = 'http://169.254.169.254/latest/meta-data/spot/instance-action'
ID_URL = 'http://169.254.169.254/latest/meta-data/instance-id'
EC2 = boto3.client('ec2')
def do_work():
""" Do something meaningful """
print(datetime.datetime.now())
def check_spot_shutdown():
"""
Check instance metadata for spot shutdown
Returns True if shutdown is signaled
"""
response = request.get(SPOT_URL)
if response.ok:
return True
return False
def check_asg_scale_in(instance_id=None):
"""
Check instance tags for scale in shutdown
Returns True if shutdown is signaled
"""
if instance_id is None:
response = request.get(ID_URL)
if response.ok:
instance_id = response.text
else:
raise ValueError('No instance_id')
tags = EC2.describe_tags(Filters=[{'Name': 'resource-id',
'Values': [instance_id]}])
tags = {tag['Key']: tag['Value'] for tag in tags['Tags']}
if 'asg_scale_in' in tags:
asg_complete_kwargs = {'AutoScalingGroupName': tags['AutoScalingGroupName'],
'LifecycleHookName': tags['LifecycleHookName'],
'LifecycleActionToken': tags['LifecycleActionToken'],
'LifecycleActionResult': 'ABANDON',
'InstanceId': instance_id}
# Signal shutdown
return True, asg_complete_kwargs
return False, {}
def main():
running = True
tags = {}
while running:
do_work()
running &= check_spot_shutdown()
asg_running, asg_complete = check_asg_scale_in()
running &= asg_running
sleep(10)
if 'LifecycleActionToken' in asg_complete:
client = boto3.client('autoscaling')
client.complete_lifecycle_action(**asg_complete)
if __name__ == '__main__':
main()
import json
import boto3
ec2 = boto3.client('ec2')
def lambda_handler(event, context):
print(event)
detail = event['detail']
if 'TERMINATING' not in detail['LifecycleTransition']:
print('Nothing to do')
return
tags = [{'Key': 'asg_scale_in', 'Value': 'SHUTDOWN'},
{'Key': 'AutoScalingGroupName', 'Value': detail['AutoScalingGroupName']},
{'Key': 'LifecycleHookName', 'Value': detail['LifecycleHookName']},
{'Key': 'LifecycleActionToken', 'Value': detail['LifecycleActionToken']}]
ec2.create_tags(Resources=[detail['EC2InstanceId']], Tags=tags)
print('Added tags to instance {}'.format(detail['EC2InstanceId']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment