Last active
November 27, 2017 16:15
-
-
Save Sam-Martin/1486be72a60a96e376b7e0845d4a3602 to your computer and use it in GitHub Desktop.
Lambda Delete Test Kitchen Instances after 24hrs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
from datetime import datetime | |
import logging | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
def lambda_handler(event, context): | |
ec2 = boto3.client('ec2') | |
reservations = ec2.describe_instances( | |
Filters=[ | |
{ | |
'Name': 'tag:Name', | |
'Values': [ | |
'Test Kitchen*' | |
] | |
}, | |
{ | |
'Name': 'instance-state-name', | |
'Values': [ | |
'running' | |
] | |
} | |
] | |
).get('Reservations', []) | |
instances = sum([[i for i in r['Instances']] for r in reservations], []) | |
for i in instances: | |
launch_time = i['LaunchTime'].replace(tzinfo=None) | |
age = datetime.now().replace(tzinfo=None) - launch_time | |
age_hours = age.total_seconds() / 60 / 60 | |
logger.info(f"Instance - {i['InstanceId']} - launched {age_hours} hours ago") | |
if age_hours > 24: | |
logger.info(f"Deleting {i['InstanceId']} as it is {age_hours} hours old") | |
response = ec2.terminate_instances( | |
InstanceIds=[ | |
i['InstanceId'] | |
], | |
DryRun=False | |
) | |
logger.info(response) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment