AWS auto destroy EC2 instances older than X days

amazon-web-servicesaws-ec2

We create automatically EC2 instances as ReviewApps. The reviewer are supposed to destroy the ec2 instances but this doens't happen always.

So i would like to script (Lambda, Terraform, etc?) that EC2 instances for this specific AWS user are get automatically destroyed after X days. Is there are known execution?

Best Answer

Got it now working with following code:

#!/usr/bin/env python3
import boto3
import datetime

from botocore.config import Config

print ("############### EC2 Cleanup Start ###############")

my_config = Config(
    region_name = 'eu-central-1',
)

ec2 = boto3.resource('ec2', config=my_config)

# Delete AWS instances older than 14 days
date_filter = (datetime.datetime.now() - datetime.timedelta(days=14)).strftime("%Y-%m-%d")

instances = ec2.instances.filter(Filters=[
  {'Name':'launch-time', 'Values':[date_filter+'*']},
  {'Name':'tag-value', 'Values':['review-app-*']}
  ])
for instance in instances:
  print(instance.id, instance.terminate())

print ("############### EC2 Cleanup Done ###############")