Ensure a hosted zone exists with the given attributes.

    name
        The name of the state definition.

    Name
        The name of the domain. This should be a fully-specified domain, and should terminate with a
        period. This is the name you have registered with your DNS registrar. It is also the name
        you will delegate from your registrar to the Amazon Route 53 delegation servers returned in
        response to this request.  If not provided, the value of name will be used.

    PrivateZone
        Set True if creating a private hosted zone.  If true, then 'VPCs' is also required.

    Comment
        Any comments you want to include about the hosted zone.

    CallerReference
        A unique string that identifies the request and that allows create_hosted_zone() calls to be
        retried without the risk of executing the operation twice.  This helps ensure idempotency
        across state calls, but can cause issues if a zone is deleted and then an attempt is made
        to recreate it with the same CallerReference.  If not provided, a unique UUID will be
        generated at each state run, which can potentially lead to duplicate zones being created if
        the state is run again while the previous zone creation is still in PENDING status (which
        can occasionally take several minutes to clear).  Maximum length of 128.

    VPCs
        A list of dicts, each dict composed of a VPCRegion, and either a VPCId or a VPCName.
        Note that this param is ONLY used if PrivateZone == True

        VPCId
            When creating a private hosted zone, either the VPC ID or VPC Name to associate with is
            required.  Exclusive with VPCName.

        VPCName
            When creating a private hosted zone, either the VPC ID or VPC Name to associate with is
            required.  Exclusive with VPCId.

        VPCRegion
            When creating a private hosted zone, the region of the associated VPC is required.  If
            not provided, an effort will be made to determine it from VPCId or VPCName, if
            possible.  This will fail if a given VPCName exists in multiple regions visible to the
            bound account, in which case you'll need to provide an explicit value for VPCRegion.

def hosted_zone_present(name, Name=None, PrivateZone=False,
                        CallerReference=None, Comment=None, VPCs=None,
                        region=None, key=None, keyid=None, profile=None):
    '''
    Ensure a hosted zone exists with the given attributes.

    name
        The name of the state definition.

    Name
        The name of the domain. This should be a fully-specified domain, and should terminate with a
        period. This is the name you have registered with your DNS registrar. It is also the name
        you will delegate from your registrar to the Amazon Route 53 delegation servers returned in
        response to this request.  If not provided, the value of name will be used.

    PrivateZone
        Set True if creating a private hosted zone.  If true, then 'VPCs' is also required.

    Comment
        Any comments you want to include about the hosted zone.

    CallerReference
        A unique string that identifies the request and that allows create_hosted_zone() calls to be
        retried without the risk of executing the operation twice.  This helps ensure idempotency
        across state calls, but can cause issues if a zone is deleted and then an attempt is made
        to recreate it with the same CallerReference.  If not provided, a unique UUID will be
        generated at each state run, which can potentially lead to duplicate zones being created if
        the state is run again while the previous zone creation is still in PENDING status (which
        can occasionally take several minutes to clear).  Maximum length of 128.

    VPCs
        A list of dicts, each dict composed of a VPCRegion, and either a VPCId or a VPCName.
        Note that this param is ONLY used if PrivateZone == True

        VPCId
            When creating a private hosted zone, either the VPC ID or VPC Name to associate with is
            required.  Exclusive with VPCName.

        VPCName
            When creating a private hosted zone, either the VPC ID or VPC Name to associate with is
            required.  Exclusive with VPCId.

        VPCRegion
            When creating a private hosted zone, the region of the associated VPC is required.  If
            not provided, an effort will be made to determine it from VPCId or VPCName, if
            possible.  This will fail if a given VPCName exists in multiple regions visible to the
            bound account, in which case you'll need to provide an explicit value for VPCRegion.
    '''
    Name = Name if Name else name

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

    if not PrivateZone and VPCs:
        raise SaltInvocationError("Parameter 'VPCs' is invalid when creating a public zone.")
    if PrivateZone and not VPCs:
        raise SaltInvocationError("Parameter 'VPCs' is required when creating a private zone.")
    if VPCs:
        if not isinstance(VPCs, list):
            raise SaltInvocationError("Parameter 'VPCs' must be a list of dicts.")
        for v in VPCs:
            if not isinstance(v, dict) or not salt.utils.data.exactly_one((v.get('VPCId'), v.get('VPCName'))):
                raise SaltInvocationError("Parameter 'VPCs' must be a list of dicts, each composed "
                                      "of either a 'VPCId' or a 'VPCName', and optionally a "
                                      "'VPCRegion', to help distinguish between multitple matches.")
    # Massage VPCs into something AWS will accept...
    fixed_vpcs = []
    if PrivateZone:
        for v in VPCs:
            VPCId = v.get('VPCId')
            VPCName = v.get('VPCName')
            VPCRegion = v.get('VPCRegion')
            VPCs = __salt__['boto_vpc.describe_vpcs'](vpc_id=VPCId, name=VPCName, region=region,
                    key=key, keyid=keyid, profile=profile).get('vpcs', [])
            if VPCRegion and VPCs:
                VPCs = [v for v in VPCs if v['region'] == VPCRegion]
            if not VPCs:
                ret['comment'] = ('A VPC matching given criteria (vpc: {0} / vpc_region: {1}) not '
                                  'found.'.format(VPCName or VPCId, VPCRegion))
                log.error(ret['comment'])
                ret['result'] = False
                return ret
            if len(VPCs) > 1:
                ret['comment'] = ('Multiple VPCs matching given criteria (vpc: {0} / vpc_region: '
                                  '{1}) found: {2}.'.format(VPCName or VPCId, VPCRegion,
                                  ', '.join([v['id'] for v in VPCs])))
                log.error(ret['comment'])
                ret['result'] = False
                return ret
            vpc = VPCs[0]
            if VPCName:
                VPCId = vpc['id']
            if not VPCRegion:
                VPCRegion = vpc['region']
            fixed_vpcs += [{'VPCId': VPCId, 'VPCRegion': VPCRegion}]

    create = False
    update_comment = False
    add_vpcs = []
    del_vpcs = []
    args = {'Name': Name, 'PrivateZone': PrivateZone,
            'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
    zone = __salt__['boto3_route53.find_hosted_zone'](**args)
    if not zone:
        create = True
        # Grrrr - can only pass one VPC when initially creating a private zone...
        # The rest have to be added (one-by-one) later in a separate step.
        if len(fixed_vpcs) > 1:
            add_vpcs = fixed_vpcs[1:]
            fixed_vpcs = fixed_vpcs[:1]
        CallerReference = CallerReference if CallerReference else str(uuid.uuid4())  # future lint: disable=blacklisted-function
    else:
        # Currently the only modifiable traits about a zone are associated VPCs and the comment.
        zone = zone[0]
        if PrivateZone:
            for z in zone.get('VPCs'):
                if z not in fixed_vpcs:
                    del_vpcs += [z]
            for z in fixed_vpcs:
                if z not in zone.get('VPCs'):
                    add_vpcs += [z]
        if zone['HostedZone']['Config'].get('Comment') != Comment:
            update_comment = True

    if not (create or add_vpcs or del_vpcs or update_comment):
        ret['comment'] = 'Hostd Zone {0} already in desired state'.format(Name)
        return ret

    if create:
        if __opts__['test']:
            ret['comment'] = 'Route 53 {} hosted zone {} would be created.'.format('private' if
                    PrivateZone else 'public', Name)
            ret['result'] = None
            return ret
        vpc_id = fixed_vpcs[0].get('VPCId') if fixed_vpcs else None
        vpc_region = fixed_vpcs[0].get('VPCRegion') if fixed_vpcs else None
        newzone = __salt__['boto3_route53.create_hosted_zone'](Name=Name,
                CallerReference=CallerReference, Comment=Comment,
                PrivateZone=PrivateZone, VPCId=vpc_id, VPCRegion=vpc_region,
                region=region, key=key, keyid=keyid, profile=profile)
        if newzone:
            newzone = newzone[0]
            ret['comment'] = 'Route 53 {} hosted zone {} successfully created'.format('private' if
                    PrivateZone else 'public', Name)
            log.info(ret['comment'])
            ret['changes']['new'] = newzone
        else:
            ret['comment'] = 'Creation of Route 53 {} hosted zone {} failed'.format('private' if
                    PrivateZone else 'public', Name)
            log.error(ret['comment'])
            ret['result'] = False
            return ret

    if update_comment:
        if __opts__['test']:
            ret['comment'] = 'Route 53 {} hosted zone {} comment would be updated.'.format('private'
                    if PrivateZone else 'public', Name)
            ret['result'] = None
            return ret
        r = __salt__['boto3_route53.update_hosted_zone_comment'](Name=Name,
                Comment=Comment, PrivateZone=PrivateZone, region=region, key=key, keyid=keyid,
                profile=profile)
        if r:
            r = r[0]
            msg = 'Route 53 {} hosted zone {} comment successfully updated'.format('private' if
                    PrivateZone else 'public', Name)
            log.info(msg)
            ret['comment'] = '  '.join([ret['comment'], msg])
            ret['changes']['old'] = zone
            ret['changes']['new'] = salt.utils.dictupdate.update(ret['changes'].get('new', {}), r)
        else:
            ret['comment'] = 'Update of Route 53 {} hosted zone {} comment failed'.format('private'
                    if PrivateZone else 'public', Name)
            log.error(ret['comment'])
            ret['result'] = False
            return ret

    if add_vpcs or del_vpcs:
        if __opts__['test']:
            ret['comment'] = 'Route 53 {} hosted zone {} associated VPCs would be updated.'.format(
                    'private' if PrivateZone else 'public', Name)
            ret['result'] = None
            return ret
        all_added = True
        all_deled = True
        for vpc in add_vpcs:  # Add any new first to avoid the "can't delete last VPC" errors.
            r = __salt__['boto3_route53.associate_vpc_with_hosted_zone'](Name=Name,
                    VPCId=vpc['VPCId'], VPCRegion=vpc['VPCRegion'], region=region, key=key,
                    keyid=keyid, profile=profile)
            if not r:
                all_added = False
        for vpc in del_vpcs:
            r = __salt__['boto3_route53.disassociate_vpc_from_hosted_zone'](Name=Name,
                    VPCId=vpc['VPCId'], VPCRegion=vpc['VPCRegion'], region=region, key=key,
                    keyid=keyid, profile=profile)
            if not r:
                all_deled = False

        ret['changes']['old'] = zone
        ret['changes']['new'] = __salt__['boto3_route53.find_hosted_zone'](**args)
        if all_added and all_deled:
            msg = 'Route 53 {} hosted zone {} associated VPCs successfully updated'.format('private'
                    if PrivateZone else 'public', Name)
            log.info(msg)
            ret['comment'] = '  '.join([ret['comment'], msg])
        else:
            ret['comment'] = 'Update of Route 53 {} hosted zone {} associated VPCs failed'.format(
                    'private' if PrivateZone else 'public', Name)
            log.error(ret['comment'])
            ret['result'] = False
            return ret

    return ret