import boto.ec2


def get_instances(stack_name, aws_config):
    """Get the IP addresses of all instances in a CloudFormation stack."""
    conn = boto.ec2.connect_to_region(
        aws_config['ec2_region'],
        aws_access_key_id=aws_config['ec2_access_key'],
        aws_secret_access_key=aws_config['ec2_secret_key'])

    reservations = conn.get_all_reservations(
        filters={
            'tag:aws:cloudformation:stack-name': stack_name,
        }
    )
    addrs = {}
    for resv in reservations:
        for inst in resv.instances:
            # Instances might still be around for stopped stacks with
            # the same stack name, so ignore them.
            if inst.state in ['terminated', 'shutting-down']:
                continue

            if inst.tags['Name'] == 'NATDevice':
                addrs[inst.tags['Name']] = inst.ip_address
            else:
                addrs[inst.tags['Name']] = inst.private_ip_address

    return addrs