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

# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

DOCUMENTATION="""
---
module: ec2_elb_facts
short_description: Creates a fact with instance to ELB mappings
version_added: "1.0"
options: {}
description:
     - This module fetches data from AWS using the boto api and returns 
       a hash as a fact that maps instances to the ELB(s) that they belong to.
examples:
    - code: ansible all -m ec2_elb_facts
      description: Obtain ELB info using boto
requirements: [ "boto" ]
author: "John Jarvis <john@jarv.org>"
"""

try:
    import boto
except ImportError:
    print "failed=True msg='boto required for this module'"
    sys.exit(1)


from collections import defaultdict

def get_elb_info(module):

    try:
        elb = boto.connect_elb()
    except boto.exception.NoAuthHandlerFound, e:
        module.fail_json(msg = str(e))

    elbs = elb.get_all_load_balancers()
    elb_info = defaultdict(set)
    for lb in elbs:
        for info in lb.instances:
            elb_info[info.id].add(lb.name)
    elb_info = {k: list(v) for k,v in elb_info.iteritems()}
    return elb_info


def main():


    module = AnsibleModule(argument_spec = dict())
    elb_info = get_elb_info(module)
    ec2_facts_result = dict(changed=False, ansible_facts={'elbs': elb_info})
    module.exit_json(**ec2_facts_result)

# this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>

main()
