7.09.2013

AWS: More Listings of EC2 Information

AWS: EC2 情報の簡易一覧表示

こちらの改良版。
mog project: AWS: Brief Listing of EC2 Instances 

インスタンスの他に、ボリューム、スナップショットの一覧も表示。

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

import sys
import subprocess
try:
    import json
except ImportError:
    print('You need python 2.6 or later to run this script.')
    sys.exit(1)


def list_instances():
    print('Instances:')
    command_args = ['describe-instances']
    headers = [
        ('Name', 16),
        ('Instance', 16),
        ('Type', 10),
        ('Launch Time', 26),
        ('State', 12),
    ]

    def generator(output):
        for i in output['Reservations'][0]['Instances']:
            yield [
                get_name(i),
                i['InstanceId'],
                i['InstanceType'],
                i['LaunchTime'],
                i['State']['Name'],
            ]
    print_list(command_args, headers, generator)


def list_volumes():
    print('Volumes:')
    command_args = ['describe-volumes']
    headers = [
        ('Name', 16),
        ('Volume ID', 16),
        ('Cap', 8),
        ('Type', 11),
        ('Zone', 17),
        ('State', 12),
    ]

    def generator(output):
        for i in output['Volumes']:
            yield [
                get_name(i),
                i['VolumeId'],
                '%d GB' % i['Size'],
                i['VolumeType'],
                i['AvailabilityZone'],
                i['State'],
            ]
    print_list(command_args, headers, generator)


def list_snapshots():
    print('Snapshots:')
    command_args = ['describe-snapshots', '--owner-ids', 'self']
    headers = [
        ('Name', 16),
        ('Snapshot ID', 16),
        ('Cap', 8),
        ('Start Time', 28),
        ('State', 12),
    ]

    def generator(output):
        for i in output['Snapshots']:
            yield [
                get_name(i),
                i['SnapshotId'],
                '%d GB' % i['VolumeSize'],
                i['StartTime'],
                i['State'],
            ]
    print_list(command_args, headers, generator)


def get_name(obj):
    return ''.join(
        [x['Value'] for x in obj.get('Tags', []) if x['Key'] == 'Name'])


def print_list(command_args, headers, generator):
    # Print header.
    print(''.join([x[0].ljust(x[1]) for x in headers]))
    print('-' * sum([x[1] for x in headers]))

    # Run command.
    stdout = subprocess.check_output(['aws', 'ec2'] + command_args)
    output = json.loads(stdout)

    # Print result.
    for result in generator(output):
        print(''.join(
            [result[i][:x[1] - 1].ljust(x[1]) for i, x in enumerate(headers)]))

    # Print footer.
    print('')


if __name__ == '__main__':
    list_instances()
    list_volumes()
    list_snapshots()

0 件のコメント:

コメントを投稿