Easy way to control cost in AWS using Python

As you start moving workloads to the AWS cloud and opening access to developers you will see you AWS cost increase every month without controls in place.

The best way to control and have a charge back model in place is to use AWS tags. You can have tags assigned to different departments like Marketing, Research, Finance, etc. Now, if instances are created without proper tags you can have a program stop the instances.

You accomplish two objectives with this approach. First, you find out who is creating instances outside the processes you have put in place. Second, you get allocate charges to the correct departments.

To run the following code you need

  • AWS cli tools installed
  • Configure AWS keys via cli
  • Python3 installed
  • Import the boto3 library

#! /usr/bin/env python3
"""
This program terminate instances if proper tag is not used
"""
import time
import boto3
start_time = time.time()
ec2 = boto3.resource('ec2')
ec2_client = boto3.client('ec2')
tag_deparment = ['Finance', 'Marketing', 'HumanResources', 'Research'] # Your departments
shutdown_instance = False
for instance in ec2.instances.all():
instance_state = instance.state['Name']
if instance_state == ('running' or 'pending'):
for tags in instance.tags:
for department in tag_deparment:
if tags['Value'] == department:
shutdown_instance = False
break
else:
shutdown_instance = True
print('The following instance will be shutdown', instance.id, 'Shutdown = ', shutdown_instance)
if shutdown_instance is True:
ec2_client.stop_instances(
InstanceIds = [instance.id],
Force = True
)

view raw

shutdown_ec2.py

hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s