"""
Autogenerated state module using `pop-create-idem <https://gitlab.com/saltstack/pop/pop-create-idem>`__

hub.exec.boto3.client.kms.create_grant
hub.exec.boto3.client.kms.list_grants
hub.exec.boto3.client.kms.retire_grant
hub.exec.boto3.client.kms.revoke_grant
"""



from typing import *
import dict_tools.differ as differ
async def present(hub, ctx, key_id: Text, grantee_principal: Text, operations: List, name: Text = None, retiring_principal: Text = None, constraints: Dict = None, grant_tokens: List = None)  -> Dict[str, Any]:
    r'''
    **Autogenerated function**
    
    Adds a grant to a customer master key (CMK).  A grant is a policy instrument that allows AWS principals to use
    AWS KMS customer master keys (CMKs) in cryptographic operations. It also can allow them to view a CMK
    (DescribeKey) and create and manage grants. When authorizing access to a CMK, grants are considered along with
    key policies and IAM policies. Grants are often used for temporary permissions because you can create one, use
    its permissions, and delete it without changing your key policies or IAM policies.  For detailed information
    about grants, including grant terminology, see Using grants in the  AWS Key Management Service Developer Guide .
    For examples of working with grants in several programming languages, see Programming grants. The CreateGrant
    operation returns a GrantToken and a GrantId.   When you create, retire, or revoke a grant, there might be a
    brief delay, usually less than five minutes, until the grant is available throughout AWS KMS. This state is
    known as eventual consistency. Once the grant has achieved eventual consistency, the grantee principal can use
    the permissions in the grant without identifying the grant.  However, to use the permissions in the grant
    immediately, use the GrantToken that CreateGrant returns. For details, see Using a grant token in the  AWS Key
    Management Service Developer Guide .   The CreateGrant operation also returns a GrantId. You can use the GrantId
    and a key identifier to identify the grant in the RetireGrant and RevokeGrant operations. To find the grant ID,
    use the ListGrants or ListRetirableGrants operations.   For information about symmetric and asymmetric CMKs, see
    Using Symmetric and Asymmetric CMKs in the AWS Key Management Service Developer Guide. For more information
    about grants, see Grants in the  AWS Key Management Service Developer Guide . The CMK that you use for this
    operation must be in a compatible key state. For details, see Key state: Effect on your CMK in the AWS Key
    Management Service Developer Guide.  Cross-account use: Yes. To perform this operation on a CMK in a different
    AWS account, specify the key ARN in the value of the KeyId parameter.   Required permissions: kms:CreateGrant
    (key policy)  Related operations:     ListGrants     ListRetirableGrants     RetireGrant     RevokeGrant

    Args:
        name(Text, optional): A friendly name for the grant. Use this value to prevent the unintended creation of duplicate
            grants when retrying this request. When this value is absent, all CreateGrant requests result in
            a new grant with a unique GrantId even if all the supplied parameters are identical. This can
            result in unintended duplicates when you retry the CreateGrant request. When this value is
            present, you can retry a CreateGrant request with identical parameters; if the grant already
            exists, the original GrantId is returned without creating a new grant. Note that the returned
            grant token is unique with every CreateGrant request, even when a duplicate GrantId is returned.
            All grant tokens for the same grant ID can be used interchangeably. Defaults to None.
        key_id(Text): Identifies the customer master key (CMK) for the grant. The grant gives principals permission to
            use this CMK. Specify the key ID or key ARN of the CMK. To specify a CMK in a different AWS
            account, you must use the key ARN. For example:   Key ID: 1234abcd-12ab-34cd-56ef-1234567890ab
            Key ARN: arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab    To get
            the key ID and key ARN for a CMK, use ListKeys or DescribeKey.
        grantee_principal(Text): The identity that gets the permissions specified in the grant. To specify the principal, use the
            Amazon Resource Name (ARN) of an AWS principal. Valid AWS principals include AWS accounts
            (root), IAM users, IAM roles, federated users, and assumed role users. For examples of the ARN
            syntax to use for specifying a principal, see AWS Identity and Access Management (IAM) in the
            Example ARNs section of the AWS General Reference.
        retiring_principal(Text, optional): The principal that is given permission to retire the grant by using RetireGrant operation. To
            specify the principal, use the Amazon Resource Name (ARN) of an AWS principal. Valid AWS
            principals include AWS accounts (root), IAM users, federated users, and assumed role users. For
            examples of the ARN syntax to use for specifying a principal, see AWS Identity and Access
            Management (IAM) in the Example ARNs section of the AWS General Reference. Defaults to None.
        operations(List): A list of operations that the grant permits.  The operation must be supported on the CMK. For
            example, you cannot create a grant for a symmetric CMK that allows the Sign operation, or a
            grant for an asymmetric CMK that allows the GenerateDataKey operation. If you try, AWS KMS
            returns a ValidationError exception. For details, see Grant operations in the AWS Key Management
            Service Developer Guide.
        constraints(Dict, optional): Specifies a grant constraint.  AWS KMS supports the EncryptionContextEquals and
            EncryptionContextSubset grant constraints. Each constraint value can include up to 8 encryption
            context pairs. The encryption context value in each constraint cannot exceed 384 characters.
            These grant constraints allow a cryptographic operation only when the encryption context in the
            request matches (EncryptionContextEquals) or includes (EncryptionContextSubset) the encryption
            context specified in this structure. For more information about encryption context, see
            Encryption Context in the  AWS Key Management Service Developer Guide . For information about
            grant constraints, see Using grant constraints in the AWS Key Management Service Developer
            Guide. The encryption context grant constraints are supported only on operations that include an
            encryption context. You cannot use an encryption context grant constraint for cryptographic
            operations with asymmetric CMKs or for management operations, such as DescribeKey or
            RetireGrant. Defaults to None.
        grant_tokens(List, optional): A list of grant tokens.  Use a grant token when your permission to call this operation comes
            from a new grant that has not yet achieved eventual consistency. For more information, see Grant
            token in the AWS Key Management Service Developer Guide. Defaults to None.

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            resource_is_present:
              aws_auto.kms.grant.present:
                - key_id: value
                - grantee_principal: value
                - operations: value
    '''
    
    result = dict(comment="", changes= None, name=name, result=True)
    ret = await hub.exec.boto3.client.kms.grant.id(
        ctx,
        jmes_path=name
    )
    if ret["status"]:
        # name is now the first id that matched the JMES search path
        name = ret["ret"]
    

    
    before = await hub.exec.boto3.client.kms.list_grants(name)

    if before:
        result["comment"] = f"'{name}' already exists"
    else:
        try:
            ret = await hub.exec.boto3.client.kms.create_grant(
                ctx,
                
                
                **{"Name": name, "KeyId": key_id, "GranteePrincipal": grantee_principal, "RetiringPrincipal": retiring_principal, "Operations": operations, "Constraints": constraints, "GrantTokens": grant_tokens}
            )
            result["result"] = ret["status"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                return result
            ret["comment"] = f"Created '{name}'"
        except hub.tool.boto3.exception.ClientError as e:
            result["comment"] = f"{e.__class__.__name__}: {e}"

    
    # TODO perform other modifications as needed here
    ...

    after = await hub.exec.boto3.client.kms.list_grants(name)
    result["changes"] = differ.deep_diff(before, after)
    return result

async def absent(hub, ctx, name: Text, key_id: Text, grant_id: Text)  -> Dict[str, Any]:
    r'''
    **Autogenerated function**
    
    Deletes the specified grant. You revoke a grant to terminate the permissions that the grant allows. For more
    information, see Retiring and revoking grants in the  AWS Key Management Service Developer Guide . When you
    create, retire, or revoke a grant, there might be a brief delay, usually less than five minutes, until the grant
    is available throughout AWS KMS. This state is known as eventual consistency. For details, see Eventual
    consistency in the  AWS Key Management Service Developer Guide .   Cross-account use: Yes. To perform this
    operation on a CMK in a different AWS account, specify the key ARN in the value of the KeyId parameter.
    Required permissions: kms:RevokeGrant (key policy).  Related operations:     CreateGrant     ListGrants
    ListRetirableGrants     RetireGrant

    Args:
        name(Text): A name, ID, or JMES search path to identify the resource.
        key_id(Text): A unique identifier for the customer master key (CMK) associated with the grant. To get the key
            ID and key ARN for a CMK, use ListKeys or DescribeKey. Specify the key ID or key ARN of the CMK.
            To specify a CMK in a different AWS account, you must use the key ARN. For example:   Key ID:
            1234abcd-12ab-34cd-56ef-1234567890ab    Key ARN: arn:aws:kms:us-
            east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab    To get the key ID and key ARN
            for a CMK, use ListKeys or DescribeKey.
        grant_id(Text): Identifies the grant to revoke. To get the grant ID, use CreateGrant, ListGrants, or
            ListRetirableGrants.

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            resource_is_absent:
              aws_auto.kms.grant.absent:
                - name: value
                - key_id: value
                - grant_id: value
    '''
    
    result = dict(comment="", changes= None, name=name, result=True)
    ret = await hub.exec.boto3.client.kms.grant.id(
        ctx,
        jmes_path=name
    )
    if ret["status"]:
        # name is now the first id that matched the JMES search path
        name = ret["ret"]
    

    

    before = await hub.exec.boto3.client.kms.list_grants(name)

    if not before:
        result["comment"] = f"'{name}' already absent"
    else:
        try:
            ret = await hub.exec.boto3.client.kms.revoke_grant(
                ctx,
                
                
                **{"KeyId": key_id, "GrantId": grant_id}
            )
            result["result"] = ret["status"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                return result
            result["comment"] = f"Deleted '{name}'"
        except hub.tool.boto3.exception.ClientError as e:
            result["comment"] = f"{e.__class__.__name__}: {e}"

    

    after = await hub.exec.boto3.client.kms.list_grants(name)
    result["changes"] = differ.deep_diff(before, after)
    return result

