Example #1
0
def print_instances(state=None, tags=None, filters=None):
    """
    Print ec2 instances using ec2.get_instances().

    tags/filters parameter requires special formatting because
    fabric passes all arguments as strings. The 'quotes' are required
    so that the pipe is not parsed by the shell.
        tags='Key:Value|Key:Value|...'

    Example:
    fab print_instances:tags='env:prod|InVPC:True',filters='instance-type:t2.micro|tenancy:default'
    """
    def _create_dict(items):
        """ builds a dict from command line arg """
        item_dict = {}
        for i in items.split('|'):
            arr = i.split(':')
            item_dict[arr[0]] = arr[1]
        return item_dict

    tag_dict = {}
    filter_dict = {}
    # setup filter dictionaries
    if tags:
        tag_dict = _create_dict(tags)
    if filters:
        filter_dict = _create_dict(filters)

    instances = ec2.get_instances(state=state, tags=tag_dict, filters=filter_dict)

    # print all matching names and ids
    for i in instances:
        for tag in i.tags:
            if tag['Key'] == 'Name':
                print '{0}: {1}'.format(tag['Value'], i.instance_id)
Example #2
0
def get_unused_records():
    '''returns all records currently unused by ec2 instances
     this currently does not handle alias->alias records'''

    # create list of all existing EC2 IPs stopped instances don't have IP addresses
    instances = ec2.get_instances(state='running')
    running_ips = [i.private_ip_address for i in instances]
    running_ips += [i.public_ip_address for i in instances if i.public_ip_address]

    # create list of IPv4Network objects containing AWS cidr ranges
    amazon_json = json.loads(
        requests.get('https://ip-ranges.amazonaws.com/ip-ranges.json').text)['prefixes']
    networks = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16']
    networks += [net['ip_prefix'] for net in amazon_json]
    ranges = [ipaddress.ip_network(net.decode()) for net in networks]

    # add 'A' records with unused IP addresses to unused_records
    # add alias records to new list to be traversed next
    unused_records = []
    alias_records = []
    for record in get_records():
        if record['Type'] == 'A' and record.has_key('ResourceRecords'):
            ip_addr = record['ResourceRecords'][0]['Value']

            # only add to unused_records if IP is not used by a
            # running instance and IP is in an AWS address range
            if (ip_addr not in running_ips
                    and True in [ipaddress.ip_address(ip_addr.decode()) in net for net in ranges]):
                unused_records.append(record)
        elif record['Type'] == 'CNAME' or record.has_key('AliasTarget'):
            alias_records.append(record)

    # search for alias records that point at unused A records
    unused_names = [rec['Name'] for rec in unused_records]
    for record in alias_records:
        if (record.has_key('ResourceRecords')
                and record['ResourceRecords'][0]['Value'] in unused_names):
            unused_records.append(record)
        elif record.has_key('AliasTarget') and record['AliasTarget']['DNSName'] in unused_names:
            unused_records.append(record)

    return unused_records
Example #3
0
def resize_dev():
    """ resize all dev hosts """
    instances = ec2.get_instances(tags={'environment':'dev'})
    # dry_run: print out potential changes
    # force: reboot running instances
    ec2.resize_instances(instances, 'm3.large', dry_run=True, force=True)