Skip to content

Automate Deletion of EC2 instances after agreed period

0

We are looking for a solution that can do the following:

  1. Identify EC2 instances that have not been used for more that 3 weeks and that do not have an agreed "permanent" or equivalent tag.
  2. Notify the owner using the email address in the value of the 'owner' tag on the EC2 instance.
  3. Automatically power down and/or terminate the instance after 4 weeks.

We would like to use this across many AWS accounts within an organization, but cannot find a solution to do this. We can either run this on an admin instance, but would like to use a native solution.

Any help is appreciated - let me know if you need further information.

  • To get a further understanding, what does it mean by being used? Processes run? User accessing? Any other metric?

2 Answers
2

Hello,

There is no native solution as such but, there is a solution that is published by AWS for a similar scenario. You might want to take a look at Instance scheduler:
[+] https://aws.amazon.com/solutions/implementations/instance-scheduler-on-aws/

However, it also depends on what you mean by "have not been used". I have a set up in my account that uses AWS Lambda, Boto3 SDK and DynamoDB. The workflow is as follows:

  1. A lambda function runs through the account and collects details about all active resources on the account every 1 hour except that have a special tag to exclude them.
  2. This information is stored in DynamoDB table
  3. Another lambda function reviews the data in the DDB table and evaluates against pre-defined rules. For example, all EC2 instances that have an average CPU utilization of less than 1% over 24 data points stored in the DDB table to be stopped.
  4. Another lambda function evaluates the DDB items and performs necessary action such as stop/delete the resource.
AWS
SUPPORT ENGINEER
answered 3 years ago
  • I'm interested in how this would exclude instances with a special tag. Do you have copies of the Lambda function in step 1 that you can share?

    We would need to send an SNS to the account owner tag attached to the instance. Could this be done in the Lambda function in step 4?

1

AWS Trusted Advisor has a check, Low Utilization Amazon EC2 Instances, under Cost Optimizations, that will alert when:

An instance had 10% or less daily average CPU utilization and 5 MB or less network 
I/O on at least 4 of the previous 14 days.

These events are sent to Amazon EventBridge and you can create a rule to trigger an action, like an email from an SNS topic or a invoke a lambda function.

You can also turn on an Organization view of Trusted Advisor.

AWS
EXPERT
answered 3 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.