Ensure policy is attached to the given principal.

    name
        The name of the state definition

    policyName
        Name of the policy.

    principal
        The principal which can be a certificate ARN or a Cognito ID.

    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.

def policy_attached(name, policyName, principal,
            region=None, key=None, keyid=None, profile=None):
    '''
    Ensure policy is attached to the given principal.

    name
        The name of the state definition

    policyName
        Name of the policy.

    principal
        The principal which can be a certificate ARN or a Cognito ID.

    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.
    '''
    ret = {'name': policyName,
           'result': True,
           'comment': '',
           'changes': {}
           }

    r = __salt__['boto_iot.list_principal_policies'](principal=principal,
                              region=region, key=key, keyid=keyid, profile=profile)

    if 'error' in r:
        ret['result'] = False
        ret['comment'] = 'Failed to attach policy: {0}.'.format(r['error']['message'])
        return ret

    attached = False
    for policy in r.get('policies', []):
        if policy.get('policyName') == policyName:
            attached = True
            break
    if not attached:
        if __opts__['test']:
            ret['comment'] = 'Policy {0} is set to be attached to {1}.'.format(policyName, principal)
            ret['result'] = None
            return ret
        r = __salt__['boto_iot.attach_principal_policy'](policyName=policyName,
                                               principal=principal,
                                               region=region, key=key,
                                               keyid=keyid, profile=profile)
        if not r.get('attached'):
            ret['result'] = False
            ret['comment'] = 'Failed to attach policy: {0}.'.format(r['error']['message'])
            return ret
        ret['changes']['old'] = {'attached': False}
        ret['changes']['new'] = {'attached': True}
        ret['comment'] = 'Policy {0} attached to {1}.'.format(policyName, principal)
        return ret

    ret['comment'] = os.linesep.join([ret['comment'], 'Policy {0} is attached.'.format(policyName)])
    ret['changes'] = {}

    return ret