#!/usr/bin/env python
# coding=utf-8
import boto.ec2
import sys


def connect_aws(profile, ec2_region):
    return boto.ec2.connect_to_region(profile_name=profile, region_name=ec2_region)


def instance_get_ip(instance):
    return instance.ip_address if instance.ip_address else instance.private_ip_address


def print_instances(connect, pattern=None):
    search = "*" if pattern is None else "*" + pattern + "*"
    instances = connect.get_only_instances(instance_ids=None,
                                           filters={'tag:Name': search, 'instance-state-name': "running"})
    for instance in instances:
        ip = instance_get_ip(instance)
        print "%-30s %-20s" % (instance.tags["Name"], ip)


if __name__ == '__main__':
    ec2_region = "eu-west-1"
    ec2_accounts = [{'human_name': 'PRO', 'account_id': 'akamon_pro'},
                    {'human_name': 'DEV', 'account_id': 'akamon_dev'}]

    search_pattern = sys.argv[1] if len(sys.argv) > 1 else None

    for account in ec2_accounts:
        print '➙ ' + account['human_name'] + ' servers ------------------------------'
        print_instances(connect_aws(account['account_id'], ec2_region), search_pattern)
