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.

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, (six.string_types, 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, six.string_types):
        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 {0} 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