Score:1

AWS auto destroy EC2 instances older than X days

in flag

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?

Tim avatar
gp flag
Tim
Can you please spell check your post - what do you mean by "practive"?
in flag
Yes. Sorry! should be practice
Score:1
in flag

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 ###############")
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.