"""
Manage ELBs

.. versionadded:: 2014.7.0

Create and destroy ELBs. Be aware that this interacts with Amazon's
services, and so may incur charges.

This module uses ``boto``, which can be installed via package, or pip.

This module accepts explicit elb credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.

If IAM roles are not used you need to specify them either in a pillar file or
in the minion's config file:

.. code-block:: yaml

    elb.keyid: GKTADJGHEIQSXMKKRBJ08H
    elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs

It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:

.. code-block:: yaml

    myprofile:
        keyid: GKTADJGHEIQSXMKKRBJ08H
        key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
        region: us-east-1

.. code-block:: yaml

    Ensure myelb ELB exists:
        boto_elb.present:
            - name: myelb
            - region: us-east-1
            - availability_zones:
                - us-east-1a
                - us-east-1c
                - us-east-1d
            - keyid: GKTADJGHEIQSXMKKRBJ08H
            - key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
            - listeners:
                - elb_port: 443
                  instance_port: 80
                  elb_protocol: HTTPS
                  instance_protocol: HTTP
                  certificate: 'arn:aws:iam::1111111:server-certificate/mycert'
                  policies:
                      - my-ssl-policy
                      - cookie-policy
                - elb_port: 8210
                  instance_port: 8210
                  elb_protocol: TCP
            - backends:
                - instance_port: 80
                  policies:
                      - enable-proxy-protocol
            - health_check:
                target: 'HTTP:80/'
            - attributes:
                cross_zone_load_balancing:
                  enabled: true
                access_log:
                  enabled: true
                  s3_bucket_name: 'mybucket'
                  s3_bucket_prefix: 'my-logs'
                  emit_interval: 5
                connecting_settings:
                  idle_timeout: 60
            - cnames:
                - name: mycname.example.com.
                  zone: example.com.
                  ttl: 60
                - name: myothercname.example.com.
                  zone: example.com.
            - security_groups:
                - my-security-group
            - policies:
                - policy_name: my-ssl-policy
                  policy_type: SSLNegotiationPolicyType
                  policy:
                    Protocol-TLSv1.2: true
                    Protocol-SSLv3: false
                    Server-Defined-Cipher-Order: true
                    ECDHE-ECDSA-AES128-GCM-SHA256: true
                - policy_name: cookie-policy
                  policy_type: LBCookieStickinessPolicyType
                  policy: {}  # no policy means this is a session cookie
                - policy_name: enable-proxy-protocol
                  policy_type: ProxyProtocolPolicyType
                  policy:
                    ProxyProtocol: true

    # Using a profile from pillars
    Ensure myelb ELB exists:
        boto_elb.present:
            - name: myelb
            - region: us-east-1
            - profile: myelbprofile

    # Passing in a profile
    Ensure myelb ELB exists:
        boto_elb.present:
            - name: myelb
            - region: us-east-1
            - profile:
                keyid: GKTADJGHEIQSXMKKRBJ08H
                key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs

It's possible to specify attributes from pillars by specifying a pillar. You
can override the values defined in the pillard by setting the attributes on the
resource. The module will use the default pillar key 'boto_elb_attributes',
which allows you to set default attributes for all ELB resources.

Setting the attributes pillar:

.. code-block:: yaml

    my_elb_attributes:
      cross_zone_load_balancing:
        enabled: true
      connection_draining:
        enabled: true
        timeout: 20
      access_log:
        enabled: true
        s3_bucket_name: 'mybucket'
        s3_bucket_prefix: 'my-logs'
        emit_interval: 5

Overriding the attribute values on the resource:

.. code-block:: yaml

    Ensure myelb ELB exists:
        boto_elb.present:
            - name: myelb
            - region: us-east-1
            - attributes_from_pillar: my_elb_attributes
            # override cross_zone_load_balancing:enabled
            - attributes:
                cross_zone_load_balancing:
                  enabled: false
            - profile: myelbprofile

It's possible to specify cloudwatch alarms that will be setup along with the
ELB. Note the alarm name will be defined by the name attribute provided, plus
the ELB resource name.

.. code-block:: yaml

    Ensure myelb ELB exists:
        boto_elb.present:
            - name: myelb
            - region: us-east-1
            - profile: myelbprofile
            - alarms:
                UnHealthyHostCount:
                  name: 'ELB UnHealthyHostCount **MANAGED BY SALT**'
                  attributes:
                    metric: UnHealthyHostCount
                    namespace: AWS/ELB
                    statistic: Average
                    comparison: '>='
                    threshold: 1.0
                    period: 600
                    evaluation_periods: 6
                    unit: null
                    description: ELB UnHealthyHostCount
                    alarm_actions: ['arn:aws:sns:us-east-1:12345:myalarm']
                    insufficient_data_actions: []
                    ok_actions: ['arn:aws:sns:us-east-1:12345:myalarm']

You can also use alarms from pillars, and override values from the pillar
alarms by setting overrides on the resource. Note that 'boto_elb_alarms'
will be used as a default value for all resources, if defined and can be
used to ensure alarms are always set for a resource.

Setting the alarms in a pillar:

.. code-block:: yaml

    my_elb_alarm:
      UnHealthyHostCount:
        name: 'ELB UnHealthyHostCount **MANAGED BY SALT**'
        attributes:
          metric: UnHealthyHostCount
          namespace: AWS/ELB
          statistic: Average
          comparison: '>='
          threshold: 1.0
          period: 600
          evaluation_periods: 6
          unit: null
          description: ELB UnHealthyHostCount
          alarm_actions: ['arn:aws:sns:us-east-1:12345:myalarm']
          insufficient_data_actions: []
          ok_actions: ['arn:aws:sns:us-east-1:12345:myalarm']

Overriding the alarm values on the resource:

.. code-block:: yaml

    Ensure myelb ELB exists:
        boto_elb.present:
            - name: myelb
            - region: us-east-1
            - profile: myelbprofile
            - alarms_from_pillar: my_elb_alarm
            # override UnHealthyHostCount:attributes:threshold
            - alarms:
                UnHealthyHostCount:
                  attributes:
                    threshold: 2.0

Tags can also be set:

.. versionadded:: 2016.3.0

.. code-block:: yaml

    Ensure myelb ELB exists:
        boto_elb.present:
            - name: myelb
            - region: us-east-1
            - profile: myelbprofile
            - tags:
                MyTag: 'My Tag Value'
                OtherTag: 'My Other Value'
"""


import hashlib
import logging
import re

import salt.utils.data
import salt.utils.dictupdate
import salt.utils.stringutils
from salt.exceptions import SaltInvocationError

log = logging.getLogger(__name__)


def __virtual__():
    """
    Only load if boto is available.
    """
    if "boto_elb.exists" in __salt__:
        return "boto_elb"
    return (False, "boto_elb module could not be loaded")


def present(
    name,
    listeners,
    availability_zones=None,
    subnets=None,
    subnet_names=None,
    security_groups=None,
    scheme="internet-facing",
    health_check=None,
    attributes=None,
    attributes_from_pillar="boto_elb_attributes",
    cnames=None,
    alarms=None,
    alarms_from_pillar="boto_elb_alarms",
    policies=None,
    policies_from_pillar="boto_elb_policies",
    backends=None,
    region=None,
    key=None,
    keyid=None,
    profile=None,
    wait_for_sync=True,
    tags=None,
    instance_ids=None,
    instance_names=None,
):
    """
    Ensure the ELB exists.

    name
        Name of the ELB.

    availability_zones
        A list of availability zones for this ELB.

    listeners
        A list of listener lists; example::

            [
                ['443', 'HTTPS', 'arn:aws:iam::1111111:server-certificate/mycert'],
                ['8443', '80', 'HTTPS', 'HTTP', 'arn:aws:iam::1111111:server-certificate/mycert']
            ]

    subnets
        A list of subnet IDs in your VPC to attach to your LoadBalancer.

    subnet_names
        A list of subnet names in your VPC to attach to your LoadBalancer.

    security_groups
        The security groups assigned to your LoadBalancer within your VPC. Must
        be passed either as a list or a comma-separated string.

        For example, a list:

        .. code-block:: yaml

            - security_groups:
              - secgroup-one
              - secgroup-two

        Or as a comma-separated string:

        .. code-block:: yaml

            - security_groups: secgroup-one,secgroup-two

    scheme
        The type of a LoadBalancer, ``internet-facing`` or ``internal``. Once
        set, can not be modified.

    health_check
        A dict defining the health check for this ELB.

    attributes
        A dict defining the attributes to set on this ELB.
        Unknown keys will be silently ignored.

        See the :mod:`salt.modules.boto_elb.set_attributes` function for
        recognized attributes.

    attributes_from_pillar
        name of pillar dict that contains attributes.   Attributes defined for this specific
        state will override those from pillar.

    cnames
        A list of cname dicts with attributes needed for the DNS add_record state.
        By default the boto_route53.add_record state will be used, which requires: name, zone, ttl, and identifier.
        See the boto_route53 state for information about these attributes.
        Other DNS modules can be called by specifying the provider keyword.
        the cnames dict will be passed to the state as kwargs.

        See the :mod:`salt.states.boto_route53` state for information about
        these attributes.

    alarms:
        a dictionary of name->boto_cloudwatch_alarm sections to be associated with this ELB.
        All attributes should be specified except for dimension which will be
        automatically set to this ELB.

        See the :mod:`salt.states.boto_cloudwatch_alarm` state for information
        about these attributes.

    alarms_from_pillar:
        name of pillar dict that contains alarm settings.   Alarms defined for this specific
        state will override those from pillar.

    region
        Region to connect to.

    key
        Secret key to be used.

    keyid
        Access key to be used.

    profile
        A dict with region, key and keyid, or a pillar key (string)
        that contains a dict with region, key and keyid.

    wait_for_sync
        Wait for an INSYNC change status from Route53.

    tags
        dict of tags

    instance_ids
        list of instance ids.  The state will ensure that these, and ONLY these, instances
        are registered with the ELB.  This is additive with instance_names.

    instance_names
        list of instance names.  The state will ensure that these, and ONLY these, instances
        are registered with the ELB.  This is additive with instance_ids.
    """

    # load data from attributes_from_pillar and merge with attributes
    tmp = __salt__["config.option"](attributes_from_pillar, {})
    attributes = salt.utils.dictupdate.update(tmp, attributes) if attributes else tmp

    ret = {"name": name, "result": True, "comment": "", "changes": {}}

    if not isinstance(security_groups, (str, list, type(None))):
        msg = (
            "The 'security_group' parameter must be either a list or a "
            "comma-separated string."
        )
        log.error(msg)
        ret.update({"comment": msg, "result": False})
        return ret
    if isinstance(security_groups, str):
        security_groups = security_groups.split(",")

    _ret = _elb_present(
        name,
        availability_zones,
        listeners,
        subnets,
        subnet_names,
        security_groups,
        scheme,
        region,
        key,
        keyid,
        profile,
    )
    ret.update(
        {
            "changes": _ret["changes"],
            "comment": "  ".join([ret["comment"], _ret["comment"]]),
        }
    )
    ret["result"] = ret["result"] if _ret["result"] else _ret["result"]
    if ret["result"] is False:
        return ret
    exists = __salt__["boto_elb.exists"](name, region, key, keyid, profile)
    if not exists and __opts__["test"]:
        return ret

    if attributes:
        _ret = _attributes_present(name, attributes, region, key, keyid, profile)
        ret.update(
            {
                "changes": salt.utils.dictupdate.update(
                    ret["changes"], _ret["changes"]
                ),
                "comment": "  ".join([ret["comment"], _ret["comment"]]),
            }
        )
        ret["result"] = ret["result"] if _ret["result"] else _ret["result"]
        if ret["result"] is False:
            return ret

    _ret = _health_check_present(name, health_check, region, key, keyid, profile)
    ret.update(
        {
            "changes": salt.utils.dictupdate.update(ret["changes"], _ret["changes"]),
            "comment": "  ".join([ret["comment"], _ret["comment"]]),
        }
    )
    ret["result"] = ret["result"] if _ret["result"] else _ret["result"]
    if ret["result"] is False:
        return ret

    if cnames:
        lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile)
        if lb:
            for cname in cnames:
                _ret = None
                dns_provider = "boto_route53"
                cname.update({"record_type": "CNAME", "value": lb["dns_name"]})
                if "provider" in cname:
                    dns_provider = cname.pop("provider")
                if dns_provider == "boto_route53":
                    for p in ("profile", "key", "keyid", "region", "wait_for_sync"):
                        cname[p] = locals().get(p) if p not in cname else cname[p]
                _ret = __states__["boto_route53.present"](**cname)
                ret.update(
                    {
                        "changes": salt.utils.dictupdate.update(
                            ret["changes"], _ret["changes"]
                        ),
                        "comment": "  ".join([ret["comment"], _ret["comment"]]),
                    }
                )
                ret["result"] = ret["result"] if _ret["result"] else _ret["result"]
                if ret["result"] is False:
                    return ret

    _ret = _alarms_present(
        name, alarms, alarms_from_pillar, region, key, keyid, profile
    )
    ret.update(
        {
            "changes": salt.utils.dictupdate.update(ret["changes"], _ret["changes"]),
            "comment": "  ".join([ret["comment"], _ret["comment"]]),
        }
    )
    ret["result"] = ret["result"] if _ret["result"] else _ret["result"]
    if ret["result"] is False:
        return ret

    _ret = _policies_present(
        name,
        policies,
        policies_from_pillar,
        listeners,
        backends,
        region,
        key,
        keyid,
        profile,
    )
    ret.update(
        {
            "changes": salt.utils.dictupdate.update(ret["changes"], _ret["changes"]),
            "comment": "  ".join([ret["comment"], _ret["comment"]]),
        }
    )
    ret["result"] = ret["result"] if _ret["result"] else _ret["result"]
    if ret["result"] is False:
        return ret

    _ret = _tags_present(name, tags, region, key, keyid, profile)
    ret.update(
        {
            "changes": salt.utils.dictupdate.update(ret["changes"], _ret["changes"]),
            "comment": "  ".join([ret["comment"], _ret["comment"]]),
        }
    )
    ret["result"] = ret["result"] if _ret["result"] else _ret["result"]
    if ret["result"] is False:
        return ret

    if not instance_ids:
        instance_ids = []
    if instance_names:
        # AWS borks on adding instances in "non-running" states, so filter 'em out.
        running_states = ("pending", "rebooting", "running", "stopping", "stopped")
        for n in instance_names:
            instance_ids += __salt__["boto_ec2.find_instances"](
                name=n,
                region=region,
                key=key,
                keyid=keyid,
                profile=profile,
                in_states=running_states,
            )
    # Backwards compat:  Only touch attached instances if requested (e.g. if some are defined).
    if instance_ids:
        if __opts__["test"]:
            if __salt__["boto_elb.set_instances"](
                name, instance_ids, True, region, key, keyid, profile
            ):
                ret["comment"] += " ELB {} instances would be updated.".format(name)
                ret["result"] = None
        else:
            success = __salt__["boto_elb.set_instances"](
                name, instance_ids, False, region, key, keyid, profile
            )
            if not success:
                ret["comment"] += "Failed to set requested instances."
                ret["result"] = False

    return ret


def register_instances(
    name, instances, region=None, key=None, keyid=None, profile=None
):
    """
    Add EC2 instance(s) to an Elastic Load Balancer. Removing an instance from
    the ``instances`` list does not remove it from the ELB.

    name
        The name of the Elastic Load Balancer to add EC2 instances to.

    instances
        A list of EC2 instance IDs that this Elastic Load Balancer should
        distribute traffic to. This state will only ever append new instances
        to the ELB. EC2 instances already associated with this ELB will not be
        removed if they are not in the ``instances`` list.

    .. versionadded:: 2015.8.0

    .. code-block:: yaml

        add-instances:
          boto_elb.register_instances:
            - name: myloadbalancer
            - instances:
              - instance-id1
              - instance-id2
    """
    ret = {"name": name, "result": True, "comment": "", "changes": {}}
    lb = __salt__["boto_elb.exists"](name, region, key, keyid, profile)
    if not lb:
        msg = "Could not find lb {}".format(name)
        log.error(msg)
        ret.update({"comment": msg, "result": False})
        return ret

    health = __salt__["boto_elb.get_instance_health"](name, region, key, keyid, profile)
    nodes = [
        value["instance_id"]
        for value in health
        if value["description"] != "Instance deregistration currently in progress."
    ]
    new = [value for value in instances if value not in nodes]
    if not new:
        msg = "Instance/s {} already exist.".format(str(instances).strip("[]"))
        log.debug(msg)
        ret.update({"comment": msg})
        return ret

    if __opts__["test"]:
        ret["comment"] = "ELB {} is set to register : {}.".format(name, new)
        ret["result"] = None
        return ret

    state = __salt__["boto_elb.register_instances"](
        name, instances, region, key, keyid, profile
    )
    if state:
        msg = "Load Balancer {} has been changed".format(name)
        log.info(msg)
        new = set().union(nodes, instances)
        ret.update(
            {
                "comment": msg,
                "changes": {"old": "\n".join(nodes), "new": "\n".join(list(new))},
            }
        )
    else:
        msg = "Load balancer {} failed to add instances".format(name)
        log.error(msg)
        ret.update({"comment": msg, "result": False})
    return ret


DEFAULT_PILLAR_LISTENER_POLICY_KEY = "boto_elb_listener_policies"


def _elb_present(
    name,
    availability_zones,
    listeners,
    subnets,
    subnet_names,
    security_groups,
    scheme,
    region,
    key,
    keyid,
    profile,
):
    ret = {"result": True, "comment": "", "changes": {}}
    if not salt.utils.data.exactly_one((availability_zones, subnets, subnet_names)):
        raise SaltInvocationError(
            "Exactly one of availability_zones, subnets, "
            "subnet_names must be provided as arguments."
        )
    if not listeners:
        listeners = []
    for listener in listeners:
        if len(listener) < 3:
            raise SaltInvocationError(
                "Listeners must have at minimum port,"
                " instance_port and protocol values in"
                " the provided list."
            )
        if "elb_port" not in listener:
            raise SaltInvocationError("elb_port is a required value for listeners.")
        if "instance_port" not in listener:
            raise SaltInvocationError(
                "instance_port is a required value for listeners."
            )
        if "elb_protocol" not in listener:
            raise SaltInvocationError("elb_protocol is a required value for listeners.")
        listener["elb_protocol"] = listener["elb_protocol"].upper()
        if listener["elb_protocol"] == "HTTPS" and "certificate" not in listener:
            raise SaltInvocationError(
                "certificate is a required value for"
                " listeners if HTTPS is set for"
                " elb_protocol."
            )

        # best attempt at principle of least surprise here:
        #     only use the default pillar in cases where we don't explicitly
        #     define policies OR policies_from_pillar on a listener
        policies = listener.setdefault("policies", [])
        policies_pillar = listener.get("policies_from_pillar", None)
        if not policies and policies_pillar is None:
            policies_pillar = DEFAULT_PILLAR_LISTENER_POLICY_KEY
        if policies_pillar:
            policies += __salt__["pillar.get"](policies_pillar, {}).get(
                listener["elb_protocol"], []
            )

    # Look up subnet ids from names if provided
    if subnet_names:
        subnets = []
        for i in subnet_names:
            r = __salt__["boto_vpc.get_resource_id"](
                "subnet", name=i, region=region, key=key, keyid=keyid, profile=profile
            )
            if "error" in r:
                ret["comment"] = "Error looking up subnet ids: {}".format(r["error"])
                ret["result"] = False
                return ret
            if "id" not in r:
                ret["comment"] = "Subnet {} does not exist.".format(i)
                ret["result"] = False
                return ret
            subnets.append(r["id"])

    _security_groups = None
    if subnets:
        vpc_id = __salt__["boto_vpc.get_subnet_association"](
            subnets, region, key, keyid, profile
        )
        vpc_id = vpc_id.get("vpc_id")
        if not vpc_id:
            ret["comment"] = "Subnets {} do not map to a valid vpc id.".format(subnets)
            ret["result"] = False
            return ret
        _security_groups = __salt__["boto_secgroup.convert_to_group_ids"](
            security_groups,
            vpc_id=vpc_id,
            region=region,
            key=key,
            keyid=keyid,
            profile=profile,
        )
        if not _security_groups:
            ret[
                "comment"
            ] = "Security groups {} do not map to valid security group ids.".format(
                security_groups
            )
            ret["result"] = False
            return ret
    exists = __salt__["boto_elb.exists"](name, region, key, keyid, profile)
    if not exists:
        if __opts__["test"]:
            ret["comment"] = "ELB {} is set to be created.".format(name)
            ret["result"] = None
            return ret
        created = __salt__["boto_elb.create"](
            name=name,
            availability_zones=availability_zones,
            listeners=listeners,
            subnets=subnets,
            security_groups=_security_groups,
            scheme=scheme,
            region=region,
            key=key,
            keyid=keyid,
            profile=profile,
        )
        if created:
            ret["changes"]["old"] = {"elb": None}
            ret["changes"]["new"] = {"elb": name}
            ret["comment"] = "ELB {} created.".format(name)
        else:
            ret["result"] = False
            ret["comment"] = "Failed to create {} ELB.".format(name)
    else:
        ret["comment"] = "ELB {} present.".format(name)
        _ret = _security_groups_present(
            name, _security_groups, region, key, keyid, profile
        )
        ret["changes"] = salt.utils.dictupdate.update(ret["changes"], _ret["changes"])
        ret["comment"] = "  ".join([ret["comment"], _ret["comment"]])
        if not _ret["result"]:
            ret["result"] = _ret["result"]
            if ret["result"] is False:
                return ret
        _ret = _listeners_present(name, listeners, region, key, keyid, profile)
        ret["changes"] = salt.utils.dictupdate.update(ret["changes"], _ret["changes"])
        ret["comment"] = "  ".join([ret["comment"], _ret["comment"]])
        if not _ret["result"]:
            ret["result"] = _ret["result"]
            if ret["result"] is False:
                return ret
        if availability_zones:
            _ret = _zones_present(name, availability_zones, region, key, keyid, profile)
            ret["changes"] = salt.utils.dictupdate.update(
                ret["changes"], _ret["changes"]
            )
            ret["comment"] = "  ".join([ret["comment"], _ret["comment"]])
            if not _ret["result"]:
                ret["result"] = _ret["result"]
                if ret["result"] is False:
                    return ret
        elif subnets:
            _ret = _subnets_present(name, subnets, region, key, keyid, profile)
            ret["changes"] = salt.utils.dictupdate.update(
                ret["changes"], _ret["changes"]
            )
            ret["comment"] = "  ".join([ret["comment"], _ret["comment"]])
            if not _ret["result"]:
                ret["result"] = _ret["result"]
    return ret


def _listeners_present(name, listeners, region, key, keyid, profile):
    ret = {"result": True, "comment": "", "changes": {}}
    lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile)
    if not lb:
        ret["comment"] = "{} ELB configuration could not be retrieved.".format(name)
        ret["result"] = False
        return ret
    if not listeners:
        listeners = []

    expected_listeners_by_tuple = {}
    for l in listeners:
        l_key = __salt__["boto_elb.listener_dict_to_tuple"](l)
        expected_listeners_by_tuple[l_key] = l
    actual_listeners_by_tuple = {}
    for l in lb["listeners"]:
        l_key = __salt__["boto_elb.listener_dict_to_tuple"](l)
        actual_listeners_by_tuple[l_key] = l

    to_delete = []
    to_create = []

    for t, l in expected_listeners_by_tuple.items():
        if t not in actual_listeners_by_tuple:
            to_create.append(l)
    for t, l in actual_listeners_by_tuple.items():
        if t not in expected_listeners_by_tuple:
            to_delete.append(l)

    if __opts__["test"]:
        msg = []
        if to_create or to_delete:
            msg.append("ELB {} set to have listeners modified:".format(name))
            for listener in to_create:
                msg.append(
                    "Listener {} added.".format(
                        __salt__["boto_elb.listener_dict_to_tuple"](listener)
                    )
                )
            for listener in to_delete:
                msg.append(
                    "Listener {} deleted.".format(
                        __salt__["boto_elb.listener_dict_to_tuple"](listener)
                    )
                )
            ret["result"] = None
        else:
            msg.append("Listeners already set on ELB {}.".format(name))
        ret["comment"] = "  ".join(msg)
        return ret

    if to_delete:
        ports = [l["elb_port"] for l in to_delete]
        deleted = __salt__["boto_elb.delete_listeners"](
            name, ports, region, key, keyid, profile
        )