tail -f /dev/null

産まれたばかりの仔羊. If you haven't had any obstacles lately, you're not challenging. be the worst.

AWS EC2 instance の一覧を CSV 形式で print

棚卸等で利用.

Env

% python --version
Python 3.7.1

% pip list installed | grep boto
boto3             1.12.6
botocore          1.15.6

code

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pandas as pd
import boto3
import click


def print_ec2_instances(profile):
    session = boto3.Session(profile_name=profile)
    ec2 = session.client('ec2')
    instances = ec2.describe_instances()['Reservations']
    account_id = ec2.describe_instances()['Reservations'][0]['OwnerId']

    account_id_map = {
        '111111111111': 'dev',
        '222222222222': 'staging',
        '333333333333': 'production'
    }

    try:
        aws_env = account_id_map[account_id]
    except KeyError as e:
        raise ValueError('undefined AWS account on account_id_map: {}'.format(account_id))

    r = {}
    for instance in instances:
        for tag in instance['Instances'][0]['Tags']:
            if "Name" in tag["Key"]:
                r['InstanceName'] = tag['Value']
        r['InstanceId'] = instance['Instances'][0]['InstanceId']
        r['PrivateIpAddress'] = instance['Instances'][0]['PrivateIpAddress']
        r['LaunchTime'] = instance['Instances'][0]['LaunchTime']
        df = pd.DataFrame(r, index=[aws_env])
        df_s = df.sort_values('InstanceName')
        csv = df_s.loc[:, ['PrivateIpAddress', 'InstanceId',
                           'InstanceName']].to_csv(header=False)
        print(csv, end="")


@click.command()
@click.option('-p', '--profile', help="specify aws profile")
def main(profile):
    print_ec2_instances(profile)


if __name__ == '__main__':
    main()

result

python ec2list.py --profile dev
dev,10.0.0.40,i-111111111111,instance_name1
dev,10.0.0.50,i-222222222222,instance_name2