Python 100 project #26: AWS EC2 Listing

One of the most frustrating things on AWS is scattered resources all over the regions. I’m not sure if there is any way to check all the resources in one single pain of the glass, but in order to check all the resources, it is quite time consuming. As I’m using AWS mainly for test purpose, there is a high possibility that I forget to stop/terminate unnecessary instances. I made a script to list all the EC2 instances in all regions along with its status.

 

Output Example:

$ python3 aws_ec2list.py 
eu-central-1    i-01a0eab7412d22cc4     ubuntu_test     stopped
us-east-1       i-065513a3b3b2ab8a7     AlexaBed        stopped
us-east-1       i-0fcde0e20853242c3     aws-cloud9-cloud9dev-2d8b27e8cbe2405c8ab08968f65c70e2   stopped
us-east-1       i-008f961394cc993c5     python_package  stopped

 

Here is the code:

import boto3

from data_source.aws_credentials import *

def gen_credential():
    credential = boto3.session.Session(
        aws_access_key_id=aws_access_key_id,
        aws_secret_access_key=aws_secret_access_key)
    return credential


def get_regions(service):
    credential = gen_credential()
    return credential.get_available_regions(service)


def list_ec2_servers(region):
    credential = gen_credential()
    ec2 = credential.client('ec2', region_name=region)
    instances = ec2.describe_instances()
    for reservations in instances['Reservations']:
        for instance in reservations['Instances']:
            tags = parse_keyvalue_sets(instance['Tags'])
            state = instance['State']['Name']
            print(f"{region}\t{instance['InstanceId']}\t{tags['Name']}\t{state}")


def parse_keyvalue_sets(tags):
    result = {}
    for tag in tags:
        key = tag['Key']
        val = tag['Value']
        result[key] = val
    return result


if __name__ == "__main__":

    regions = get_regions('ec2')
    for region in regions:
        list_ec2_servers(region)