Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sam-Martin/1486be72a60a96e376b7e0845d4a3602 to your computer and use it in GitHub Desktop.
Save Sam-Martin/1486be72a60a96e376b7e0845d4a3602 to your computer and use it in GitHub Desktop.
Lambda Delete Test Kitchen Instances after 24hrs
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