
    Vhϒ                        d Z dZdZddlZ	 ddlZddlmZ ddlm	Z	 ddl
mZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ  ej(                  ddd      d        Z ej(                  ddd      d        Zd Z ej(                  ddd      d        Z ej(                  ddd      d        Z ej(                  ddd      d        Z ej(                  ddd      d        Z ej(                  ddd      d        Zd Zd Zd Zd Z d Z!d Z"d0dZ#d Z$d  Z%d! Z&d" Z'd# Z(d$ Z)d% Z*d& Z+d' Z,d( Z-d) Z.d* Z/d+ Z0d, Z1d- Z2d. Z3e4d/k(  r e3        yy# e$ r Y Lw xY w)1aq  
---
module: kms_key
version_added: 5.0.0
short_description: Perform various KMS key management tasks
description:
  - Manage role/user access to a KMS key.
  - Not designed for encrypting/decrypting.
  - Prior to release 5.0.0 this module was called M(community.aws.aws_kms).
    The usage did not change.
  - This module was originally added to C(community.aws) in release 1.0.0.
options:
  alias:
    description:
      - An alias for a key.
      - For safety, even though KMS does not require keys to have an alias, this module expects all
        new keys to be given an alias to make them easier to manage. Existing keys without an alias
        may be referred to by O(key_id). Use M(amazon.aws.kms_key_info) to find key ids.
      - Note that passing a O(key_id) and O(alias) will only cause a new alias to be added, an alias will never be renamed.
      - The V(alias/) prefix is optional.
      - Required if O(key_id) is not given.
    required: false
    aliases:
      - key_alias
    type: str
  key_id:
    description:
      - Key ID or ARN of the key.
      - One of O(alias) or O(key_id) are required.
    required: false
    aliases:
      - key_arn
    type: str
  enable_key_rotation:
    description:
      - Whether the key should be automatically rotated every year.
    required: false
    type: bool
  state:
    description:
      - Whether a key should be present or absent.
      - Note that making an existing key V(absent) only schedules a key for deletion.
      - Passing a key that is scheduled for deletion with O(state=present) will cancel key deletion.
    required: false
    choices:
      - present
      - absent
    default: present
    type: str
  enabled:
    description: Whether or not a key is enabled.
    default: true
    type: bool
  description:
    description:
      - A description of the CMK.
      - Use a description that helps you decide whether the CMK is appropriate for a task.
    type: str
  multi_region:
    description:
      -  Whether to create a multi-Region primary key or not.
    default: false
    type: bool
    version_added: 5.5.0
  pending_window:
    description:
      - The number of days between requesting deletion of the CMK and when it will actually be deleted.
      - Only used when O(state=absent) and the CMK has not yet been deleted.
      - Valid values are between V(7) and V(30) (inclusive).
      - 'See also: U(https://docs.aws.amazon.com/kms/latest/APIReference/API_ScheduleKeyDeletion.html#KMS-ScheduleKeyDeletion-request-PendingWindowInDays)'
    type: int
    aliases: ['deletion_delay']
    version_added: 1.4.0
    version_added_collection: community.aws
  purge_grants:
    description:
      - Whether the O(grants) argument should cause grants not in the list to be removed.
    default: false
    type: bool
  grants:
    description:
      - A list of grants to apply to the key. Each item must contain O(grants.grantee_principal).
        Each item can optionally contain O(grants.retiring_principal), O(grants.operations), O(grants.constraints),
        O(grants.name).
      - O(grants.grantee_principal) and O(grants.retiring_principal) must be ARNs.
      - 'For full documentation of suboptions see the boto3 documentation:'
      - 'U(https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/kms.html#KMS.Client.create_grant)'
    type: list
    elements: dict
    default: []
    suboptions:
        grantee_principal:
            description: The full ARN of the principal being granted permissions.
            required: true
            type: str
        retiring_principal:
            description: The full ARN of the principal permitted to revoke/retire the grant.
            type: str
        operations:
            type: list
            elements: str
            description:
              - A list of operations that the grantee may perform using the CMK.
            choices: ['Decrypt', 'Encrypt', 'GenerateDataKey', 'GenerateDataKeyWithoutPlaintext', 'ReEncryptFrom', 'ReEncryptTo',
                      'CreateGrant', 'RetireGrant', 'DescribeKey', 'Verify', 'Sign']
        constraints:
            description:
              - Constraints is a dict containing V(encryption_context_subset) or V(encryption_context_equals),
                either or both being a dict specifying an encryption context match.
                See U(https://docs.aws.amazon.com/kms/latest/APIReference/API_GrantConstraints.html) or
                U(https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/kms.html#KMS.Client.create_grant)
            type: dict
        name:
            description:
              - A friendly name for the grant.
              - Use this value to prevent the unintended creation of duplicate grants when retrying this request.
            type: str
  policy:
    description:
      - Policy to apply to the KMS key.
      - See U(https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html)
    type: json
  key_spec:
    aliases:
      - customer_master_key_spec
    description:
      - Specifies the type of KMS key to create.
      - The specification is not changeable once the key is created.
    type: str
    default: SYMMETRIC_DEFAULT
    choices: ['SYMMETRIC_DEFAULT', 'RSA_2048', 'RSA_3072', 'RSA_4096', 'ECC_NIST_P256', 'ECC_NIST_P384', 'ECC_NIST_P521', 'ECC_SECG_P256K1']
    version_added: 2.1.0
    version_added_collection: community.aws
  key_usage:
    description:
      - Determines the cryptographic operations for which you can use the KMS key.
      - The usage is not changeable once the key is created.
    type: str
    default: ENCRYPT_DECRYPT
    choices: ['ENCRYPT_DECRYPT', 'SIGN_VERIFY']
    version_added: 2.1.0
    version_added_collection: community.aws
author:
  - Ted Timmons (@tedder)
  - Will Thames (@willthames)
  - Mark Chappell (@tremble)
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.tags
  - amazon.aws.boto3

notes:
  - There are known inconsistencies in the amount of time required for updates of KMS keys to be fully reflected on AWS.
    This can cause issues when running duplicate tasks in succession or using the M(amazon.aws.kms_key_info) module to fetch key metadata
    shortly after modifying keys.
    For this reason, it is recommended to use the return data from this module (M(amazon.aws.kms_key)) to fetch a key's metadata.
  - The C(policies) return key was removed in amazon.aws release 8.0.0.
a  
# Create a new KMS key
- amazon.aws.kms_key:
    alias: mykey
    tags:
      Name: myKey
      Purpose: protect_stuff

# Create a new multi-region KMS key
- amazon.aws.kms_key:
    alias: mykey
    multi_region: true
    tags:
      Name: myKey
      Purpose: protect_stuff

# Update previous key with more tags
- amazon.aws.kms_key:
    alias: mykey
    tags:
      Name: myKey
      Purpose: protect_stuff
      Owner: security_team

# Update a known key with grants allowing an instance with the billing-prod IAM profile
# to decrypt data encrypted with the environment: production, application: billing
# encryption context
- amazon.aws.kms_key:
    key_id: abcd1234-abcd-1234-5678-ef1234567890
    grants:
      - name: billing_prod
        grantee_principal: arn:aws:iam::123456789012:role/billing_prod
        constraints:
          encryption_context_equals:
            environment: production
            application: billing
        operations:
          - Decrypt
          - RetireGrant

- name: Update IAM policy on an existing KMS key
  amazon.aws.kms_key:
    alias: my-kms-key
    policy: '{"Version": "2012-10-17", "Id": "my-kms-key-permissions", "Statement": [ { <SOME STATEMENT> } ]}'
    state: present

- name: Example using lookup for policy json
  amazon.aws.kms_key:
    alias: my-kms-key
    policy: "{{ lookup('template', 'kms_iam_policy_template.json.j2') }}"
    state: present
a|  
key_id:
  description: ID of key.
  type: str
  returned: always
  sample: "abcd1234-abcd-1234-5678-ef1234567890"
key_arn:
  description: ARN of key.
  type: str
  returned: always
  sample: "arn:aws:kms:ap-southeast-2:123456789012:key/abcd1234-abcd-1234-5678-ef1234567890"
key_state:
  description:
    - The state of the key.
    - Will be one of C('Creating'), C('Enabled'), C('Disabled'), C('PendingDeletion'), C('PendingImport'),
      C('PendingReplicaDeletion'), C('Unavailable'), or C('Updating').
  type: str
  returned: always
  sample: "PendingDeletion"
key_usage:
  description: The cryptographic operations for which you can use the key.
  type: str
  returned: always
  sample: "ENCRYPT_DECRYPT"
origin:
  description: The source of the key's key material. When this value is C(AWS_KMS),
    AWS KMS created the key material. When this value is C(EXTERNAL), the
    key material was imported or the CMK lacks key material.
  type: str
  returned: always
  sample: "AWS_KMS"
aws_account_id:
  description: The AWS Account ID that the key belongs to.
  type: str
  returned: always
  sample: "1234567890123"
creation_date:
  description: Date and time of creation of the key.
  type: str
  returned: always
  sample: "2017-04-18T15:12:08.551000+10:00"
deletion_date:
  description: Date and time after which KMS deletes this KMS key.
  type: str
  returned: when RV(key_state) is PendingDeletion
  sample: "2017-04-18T15:12:08.551000+10:00"
  version_added: 3.3.0
  version_added_collection: community.aws
description:
  description: Description of the key.
  type: str
  returned: always
  sample: "My Key for Protecting important stuff"
enabled:
  description: Whether the key is enabled. True if RV(key_state) is V(Enabled).
  type: bool
  returned: always
  sample: false
enable_key_rotation:
  description: Whether the automatic annual key rotation is enabled. Returns None if key rotation status can't be determined.
  type: bool
  returned: always
  sample: false
aliases:
  description: List of aliases associated with the key.
  type: list
  returned: always
  sample:
    - aws/acm
    - aws/ebs
key_policies:
  description: List of policy documents for the key. Empty when access is denied even if there are policies.
  type: list
  returned: always
  elements: dict
  sample:
    Version: "2012-10-17"
    Id: "auto-ebs-2"
    Statement:
    - Sid: "Allow access through EBS for all principals in the account that are authorized to use EBS"
      Effect: "Allow"
      Principal:
        AWS: "*"
      Action:
      - "kms:Encrypt"
      - "kms:Decrypt"
      - "kms:ReEncrypt*"
      - "kms:GenerateDataKey*"
      - "kms:CreateGrant"
      - "kms:DescribeKey"
      Resource: "*"
      Condition:
        StringEquals:
          kms:CallerAccount: "123456789012"
          kms:ViaService: "ec2.ap-southeast-2.amazonaws.com"
    - Sid: "Allow direct access to key metadata to the account"
      Effect: "Allow"
      Principal:
        AWS: "arn:aws:iam::123456789012:root"
      Action:
      - "kms:Describe*"
      - "kms:Get*"
      - "kms:List*"
      - "kms:RevokeGrant"
      Resource: "*"
  version_added: 3.3.0
  version_added_collection: community.aws
tags:
  description: Dictionary of tags applied to the key. Empty when access is denied even if there are tags.
  type: dict
  returned: always
  sample:
    Name: myKey
    Purpose: protecting_stuff
grants:
  description: List of grants associated with a key.
  type: list
  elements: dict
  returned: always
  contains:
    constraints:
      description: Constraints on the encryption context that the grant allows.
        See U(https://docs.aws.amazon.com/kms/latest/APIReference/API_GrantConstraints.html) for further details
      type: dict
      returned: always
      sample:
        encryption_context_equals:
           "aws:lambda:_function_arn": "arn:aws:lambda:ap-southeast-2:123456789012:function:xyz"
    creation_date:
      description: Date of creation of the grant.
      type: str
      returned: always
      sample: "2017-04-18T15:12:08+10:00"
    grant_id:
      description: The unique ID for the grant.
      type: str
      returned: always
      sample: "abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234"
    grantee_principal:
      description: The principal that receives the grant's permissions.
      type: str
      returned: always
      sample: "arn:aws:sts::123456789012:assumed-role/lambda_xyz/xyz"
    issuing_account:
      description: The AWS account under which the grant was issued.
      type: str
      returned: always
      sample: "arn:aws:iam::123456789012:root"
    key_id:
      description: The key ARN to which the grant applies.
      type: str
      returned: always
      sample: "arn:aws:kms:ap-southeast-2:123456789012:key/abcd1234-abcd-1234-5678-ef1234567890"
    name:
      description: The friendly name that identifies the grant.
      type: str
      returned: always
      sample: "xyz"
    operations:
      description: The list of operations permitted by the grant.
      type: list
      returned: always
      sample:
        - Decrypt
        - RetireGrant
    retiring_principal:
      description: The principal that can retire the grant.
      type: str
      returned: always
      sample: "arn:aws:sts::123456789012:assumed-role/lambda_xyz/xyz"
changes_needed:
  description: Grant types that would be changed/were changed.
  type: dict
  returned: always
  sample: { "role": "add", "role grant": "add" }
had_invalid_entries:
  description: Whether there are invalid (non-ARN) entries in the KMS entry. These don't count as a change, but will be removed if any changes are being made.
  type: bool
  returned: always
multi_region:
  description:
    - Indicates whether the CMK is a multi-Region C(True) or regional C(False) key.
    - This value is True for multi-Region primary and replica CMKs and False for regional CMKs.
  type: bool
  version_added: 5.5.0
  returned: always
  sample: False
customer_master_key_spec:
  description: Specifies the type of KMS key to create.
  type: str
  returned: always
  sample: "SYMMETRIC_DEFAULT"
encryption_algorithms:
  description: The encryption algorithms that the KMS key supports.
  type: list
  elements: str
  returned: always
  sample: ["SYMMETRIC_DEFAULT"]
key_manager:
  description: The manager of the KMS key.
  type: str
  returned: always
  sample: "AWS"
key_spec:
  description: Specifies the type of KMS key to create.
  type: str
  returned: always
  sample: "SYMMETRIC_DEFAULT"
    N)camel_dict_to_snake_dict)is_boto3_error_code)AnsibleAWSModule)compare_policies)AWSRetry)ansible_dict_to_boto3_tag_list)boto3_tag_list_to_ansible_dict)compare_aws_tags   g       @)retriesdelaybackoffc                 `    | j                  d      }|j                         j                         S )N	list_keysget_paginatorpaginatebuild_full_result
connection	paginators     f/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/modules/kms_key.pyget_kms_keys_with_backoffr     s*    ((5I1133    c                 `    | j                  d      }|j                         j                         S )Nlist_aliasesr   r   s     r   get_kms_aliases_with_backoffr     s*    ((8I1133r   c                     t               }t        |       d   D ];  }d|v s|d   |v r||d      j                  |d   dd         -|d   dd  g||d   <   = |S )NAliasesTargetKeyId	AliasName   )dictr   append)r   _aliasesaliass      r   get_kms_aliases_lookupr'     s    vH-j9)D JE!]#x/}-.55eK6H6LM272DQR2H1I}-.J Or   c                 *     | j                   dd|i|S )NKeyId )list_resource_tags)r   key_idkwargss      r   get_kms_tags_with_backoffr.     s    (:((@v@@@r   c                 |    t        |      }| j                  d      } |j                  di |j                         S )Nr)   list_grantsr*   )r#   r   r   r   )r   r,   paramsr   s       r   get_kms_grants_with_backoffr3     s;    F((7I9''99;;r   c                 &    | j                  |      S )Nr0   )describe_key)r   r,   s     r   get_kms_metadata_with_backoffr6     s    """00r   c                 d    | j                  d      }|j                  |      j                         S )Nlist_key_policiesr0   r   )r   r,   r   s      r   list_key_policies_with_backoffr9     s0    (()<=IF+==??r   c                 (    | j                  ||      S )Nr)   
PolicyName)get_key_policy)r   r,   policy_names      r   get_key_policy_with_backoffr?     s    $$6k$JJr   c                 h   i }g }d}|rA	 t        | |fi |}|j                  |d          j                  d      r	|d   |d<   nd}|rA|S # t        d      $ r i }Y 3t        j                  j
                  t        j                  j                  f$ r}|j                  |d       Y d }~d }~ww xY w)	NTTagsAccessDeniedExceptionzFailed to obtain key tagsmsg
NextMarkerMarkerF)	r.   extendr   botocore
exceptionsClientErrorBotoCoreErrorfail_json_awsget)r   moduler,   r-   tagsmoretag_responsees           r   get_kms_tagsrS     s     FDD
		E4ZR6RLKKV,- L)+L9F8D  K ##:; 	L++--
 	E   (C DD		Es   !A B16B1B,,B1c                 8   	 t        | |      d   }|D cg c]  }t        | ||      d    c}S c c}w # t        d      $ r g cY S t        j                  j
                  t        j                  j                  f$ r}|j                  |d       Y d }~y d }~ww xY w)NPolicyNamesPolicyrB   zFailed to obtain key policiesrC   )r9   r?   r   rH   rI   rJ   rK   rL   )r   rN   r,   policiespolicyrR   s         r   get_kms_policiesrY     s    	E1*fEmT`hiV\+JGQiii67 	'')) E 	Q$CDD	Es'   4 /4 4 B6B<BBc                 |    | j                  di       }t        |       }d|v r|d   |d   d<   d|v r|d   |d   d<   |S )zGcamel_to_snake_grant snakifies everything except the encryption contextConstraintsEncryptionContextEqualsconstraintsencryption_context_equalsEncryptionContextSubsetencryption_context_subset)rM   r   )grantr]   results      r   camel_to_snake_grantrc     s]    ))M2.K%e,F K/=HIb=c}9: K/=HIb=c}9:Mr   c                 J   	 t        | |      d   }j                  d      |d<   	 t        |       }	 | j                  |      }|j                  d      |d	<   j                  |d   g       |d<   t        |      }	 t        | |      d   D cg c]  }t        |       c}|d<   t        | ||      }t        |dd      |d<   t!        | ||      }	|	D 
cg c]  }
t#        j$                  |
       c}
|d<   |S # t        j                  j                  t        j                  j                  f$ r}|j                  |d       Y d }~6d }~ww xY w# t        j                  j                  t        j                  j                  f$ r}|j                  |d       Y d }~nd }~ww xY w# t        d
dg      $ r	 d |d	<   Y gw xY wc c}w # t        j                  j                  t        j                  j                  f$ r}|j                  |d       Y d }~sd }~ww xY wc c}
w )NKeyMetadatazFailed to obtain key metadatarC   ArnKeyArnzFailed to obtain aliasesr0   KeyRotationEnabledenable_key_rotationrB   UnsupportedOperationExceptionr)   aliasesGrantsgrantszFailed to obtain key grantsTagKeyTagValuerO   key_policies)r6   rH   rI   rJ   rK   rL   popr'   get_key_rotation_statusrM   r   r   r3   rc   rS   r	   rY   jsonloads)r   rN   r,   rb   rR   rk   current_rotation_statusra   rO   rW   rX   s              r   get_key_detailsrv   %  s"   E.z6B=Q zz%(F8@(4-","D"D6"D"R(?(C(CDX(Y$%  F7OR8F9%f-FC5PQ[]c5dem5n
,1 '
x
 
FF3D3D(JOF6N
FF;H?GHVdjj0HF>M; ++X-@-@-N-NO EQ$CDDE ++X-@-@-N-NO @Q$>??@  79XYZ -(,$%-
 ++X-@-@-N-NO CQ$ABBC
 Iso   C7 E &F' <G GG H 77E.EE7F$FF$'G ?G G 7H?HHc                    t        |d   | d         }| j                  d      r| d   |d<   | j                  d      r| d   |d<   | j                  d      r| d   |d	<   | j                  d
      rQt               |d<   | d
   j                  d      r| d
   d   |d   d<   | d
   j                  d      r| d
   d   |d   d<   |S )Nkey_arngrantee_principal)r)   GranteePrincipal
operations
Operationsretiring_principalRetiringPrincipalnameNamer]   r[   r`   r_   r^   r\   )r#   rM   )ra   keygrant_paramss      r   convert_grant_paramsr   H  s    c)nuEX?YZLyy%*<%8\"yy%&,12F,G()yy$V}Vyy&*f]###$?@EJ=EYZuEvL'(AB##$?@EJ=EYZuEvL'(ABr   c                 J   | j                  d      |j                  d      k7  ry| j                  d      |j                  d      k7  ryt        | j                  dg             t        |j                  d            k7  ry| j                  d      |j                  d      k7  ryy)Nry   Tr}   r{   r]   F)rM   set)existing_grantdesired_grants     r   different_grantr   Y  s    -.-2C2CDW2XX./=3D3DEY3ZZ
>lB/0C8I8I,8W4XX-(M,=,=m,LLr   c                    t        d | D              }t        d |D              }t        |j                               t        |j                               z
  }|r4t        |j                               t        |j                               z
  }n
t               }t        |j                               t        |j                               z  }|D ]7  }t        ||   ||         s|j	                  |       |j	                  |       9 g }	g }
|D ]  }||   }|	j                  |        |D ]  }||   }|
j                  |        |	|
fS )Nc              3   *   K   | ]  }|d    |f  ywr   Nr*   ).0egs     r   	<genexpr>z!compare_grants.<locals>.<genexpr>f  s     Db"V*b)D   c              3   *   K   | ]  }|d    |f  ywr   r*   )r   dgs     r   r   z!compare_grants.<locals>.<genexpr>g  s     BRFR(Br   )r#   r   keysr   addr$   )existing_grantsdesired_grantspurge_grantsexisting_dictdesired_dictto_add_keysto_remove_keysto_change_candidates	candidateto_add	to_remover   ra   s                r   compare_grantsr   e  sC   DODDMB>BBLl'')*S1C1C1E-FFK]//12S9J9J9L5MM}1134s<;L;L;N7OO) *	=3\)5LMOOI&y)*
 FI S!e   c"  9r   c                    |d   dk(  ry|j                   ryd|d   i}|j                  j                  d      r|j                  j                  d      |d<   	  | j                  di | y# t        j
                  j                  t        j
                  j                  f$ r}|j                  |d	
       Y d }~y d }~ww xY w)NKeyStatePendingDeletionFTr)   rf   pending_windowPendingWindowInDaysz#Failed to schedule key for deletionrC   r*   )	
check_moder2   rM   schedule_key_deletionrH   rI   rJ   rK   rL   )r   rN   key_metadatadeletion_paramsrR   s        r   start_key_deletionr   ~  s    J#44U 34O}})*171B1BCS1T-.K(
((;?;++X-@-@-N-NO KQ$IJJKs   A+ +7B?"B::B?c                    |d   }|d   dk7  ry|j                   ry	 | j                  |       d|d<   y# t        j                  j                  t        j                  j
                  f$ r}|j                  |d	       Y d }~yd }~ww xY w)
Nrx   	key_stater   FTr0   DisabledzFailed to cancel key deletionrC   )r   cancel_key_deletionrH   rI   rJ   rK   rL   )r   rN   r   r,   rR   s        r   r   r     s    ^F
;,,E&&V&4 &K  ++X-@-@-N-NO EQ$CDDEs   5 7B	,BB	c                    d}|sd}|d   |k(  ry|d   }|j                   s*|r	 | j                  |       y
	 | j                  |       y
y
# t        j                  j                  t        j                  j
                  f$ r}|j                  |d       Y d }~y
d }~ww xY w# t        j                  j                  t        j                  j
                  f$ r}|j                  |d	       Y d }~y
d }~ww xY w)NEnabledr   r   Frx   r0   zFailed to enable keyrC   zFailed to disable keyT)r   
enable_keyrH   rI   rJ   rK   rL   disable_key)r   rN   r   enableddesired_stater,   rR   s          r   ensure_enabled_disabledr     s   M"
;=(^FD%%F%3 E&&V&4  ''33X5H5H5V5VW D$$Q,B$CC D
 ''33X5H5H5V5VW E$$Q,C$DDEs.   A B# 7B BB #7C7C22C7c                 l   t        |      }|y|d   }t        |       d   }||D cg c]  }|d   	 c}v ry|j                  s	 | j                  ||       yyc c}w # t        j
                  j                  t        j
                  j                  f$ r}|j                  |d       Y d }~yd }~ww xY w)	NFrx   r   r!   )r    r!   zFailed create key aliasrC   T)	canonicalize_alias_namer   r   create_aliasrH   rI   rJ   rK   rL   )r   rN   r   r&   r,   rk   _aliasrR   s           r   update_aliasr     s    #E*E}^F*:6yAG7;$;;	C##%#H  < ##//1D1D1R1RS 	C  (A BB	Cs   AA 7B3B..B3c                    |y|d   |k(  ry|d   }|j                   s	 | j                  ||       yy# t        j                  j                  t        j                  j
                  f$ r}|j                  |d       Y d }~yd }~ww xY w)NFdescriptionrx   )r)   Descriptionz Failed to update key descriptionrC   T)r   update_key_descriptionrH   rI   rJ   rK   rL   )r   rN   r   r   r,   rR   s         r   update_descriptionr     s    
=[(^F	L--F-T  ##//1D1D1R1RS 	L  (J KK	Ls   4 7B+BBc                 l   |yt        |d   ||      \  }}t        |      st        |      sy|d   }|j                  sH|r	 | j                  ||       |r0	 t        |j                  d   dd	      }	| j                  ||	
       yy# t        j
                  j                  t        j
                  j                  f$ r}|j                  |d       Y d }~d }~ww xY w# t        j
                  j                  t        j
                  j                  f$ r}|j                  |d       Y d }~yd }~ww xY w)NFrO   rx   )r)   TagKeyszUnable to remove tagrC   rn   ro   tag_name_key_nametag_value_key_name)r)   rA   zUnable to add tag to keyT)r
   boolr   untag_resourcerH   rI   rJ   rK   rL   r   r2   tag_resource)
r   rN   r   desired_tags
purge_tagsr   r   r,   rR   rO   s
             r   update_tagsr     s3   (VlJOFILDO^FD))	)J H5MM&)&.'1
 ''f4'@  ''33X5H5H5V5VW D$$Q,B$CCD ''33X5H5H5V5VW H$$Q,F$GGHs0   B .C 7C?CC7D3D..D3c                 t   |y	 t        j                  |      }|d   }	 | j	                  |d      }t        j                  |d         }t        |      sy|j                  s	 | j                  |d|       y
y
# t        $ r}|j                  |d       Y d }~d }~ww xY w# t
        j                  j                  t
        j                  j                  f$ r i }Y w xY w# t
        j                  j                  t
        j                  j                  f$ r}|j                  |d	       Y d }~y
d }~ww xY w)NFz"Unable to parse new policy as JSONrC   rx   defaultr;   rV   )r)   r<   rV   zUnable to update key policyT)rs   rt   
ValueErrorrL   r=   rH   rI   rJ   rK   r   r   put_key_policy)	r   rN   r   rX   
new_policyrR   r,   keyretoriginal_policys	            r   update_policyr     s8   ~JZZ'
 ^F**I*N**VH%56 OZ8	G%%FyQW%X +  JQ$HIIJ ++X-@-@-N-NO   ##//1D1D1R1RS 	G  (E FF	Gs@   A; +B$ %C# ;	B!BB!$9C C #7D7D22D7c                 L   |y|d   }	 | j                  |      }|j                  d      |k(  ry	 |j                  s*	 |r| j                  |       y	| j                  |       	 y	y	# t        d      $ r Y Gt        j                  j
                  t        j                  j                  f$ r}|j                  |d       Y d }~d }~ww xY w# t        j                  j
                  t        j                  j                  f$ r}|j                  |d       Y d }~y	d }~ww xY w)
NFrx   r0   rh   rB   z)Unable to get current key rotation statusrC   z%Failed to enable/disable key rotationT)rr   rM   r   rH   rI   rJ   rK   rL   r   ri   disable_key_rotation)r   rN   r   ri   r,   ru   rR   s          r   update_key_rotationr     s6   "^F
Q","D"D6"D"R"&&';<@SS T 	Q"..V.< 	 //f/= # 67 '')) Q 	Q$OPP	Q ##//1D1D1R1RS 	Q  (O PP	Qs:   &A) C C )C96C/CC7D#DD#c                 b   |d   }t        |||      \  }}t        |      st        |      sy|d   }|j                  sD|D ]  }		 | j                  ||	d           |D ]!  }	t        |	|      }	  | j                  d
i | # y	# t        j
                  j                  t        j
                  j                  f$ r}
|j                  |
d       Y d }
~
d }
~
ww xY w# t        j
                  j                  t        j
                  j                  f$ r}
|j                  |
d       Y d }
~
d }
~
ww xY w)Nrm   Frx   grant_id)r)   GrantIdzUnable to retire grantrC   zUnable to create grantTr*   )r   r   r   retire_grantrH   rI   rJ   rK   rL   r   create_grant)r   rN   r   r   r   r   r   r   r,   ra   rR   r   s               r   update_grantsr   7  s;   (mO&UFILDO^F 	FEF''feJ>O'P	F
  	FE/s;LF'
''7,7	F  ''33X5H5H5V5VW F$$Q,D$EEF ''33X5H5H5V5VW F$$Q,D$EEFs0   B.C7C:CC7D.D))D.c           
         d}|t        | ||      z  }|t        | |||j                  d         z  }|t        | |||j                  d         z  }|t	        | |||j                  d         z  }|t        | |||j                  d   |j                  j                  d            z  }|t        | |||j                  j                  d            z  }|t        | |||j                  j                  d      |j                  j                  d	            z  }|t        | |||j                  j                  d
            z  }t        | ||d         }||d<   |S )NFr   r&   r   rO   r   rX   rm   r   ri   rx   changed)r   r   r2   r   r   r   rM   r   r   r   rv   )r   rN   r   r   rb   s        r   
update_keyr   O  sM   G":vs;;G&z63i@XYYG|JV]]75KLLG!*fc6==;WXXG{:vsFMM&4I6==K\K\]iKjkkG}Zfmm6G6G6QRRG}Zfmm6G6G6QSYS`S`SdSdesStuuG":vsFMM<M<MNc<deeG ZY@FF9Mr   c                 $   |j                   j                  d      }|j                   j                  d      }|j                   j                  d      }t        |j                   d   xs i dd      }t        d|||d	|
      }|j                  rddiS |j                   j                  d      r|j                   d   |d<   |j                   j                  d      r|j                   d   |d<   	  | j
                  di |d   }t        | |d         }	t        | ||	|j                   d          t        | ||	|j                   j                  d             t        | ||	|j                   j                  d             t        | ||	|j                   j                  d      d       t        | ||	d         }d|d<   |S # t        j                  j                  t        j                  j                  f$ r}|j                  |d       Y d }~d }~ww xY w)N	key_usagekey_specmulti_regionrO   rn   ro   r   FAWS_KMS)BypassPolicyLockoutSafetyCheckrA   KeyUsageCustomerMasterKeySpecOriginMultiRegionr   Tr   r   rX   rV   re   zFailed to create initial keyrC   r)   r&   ri   r   rm   r,   r*   )r2   rM   r   r#   r   
create_keyrH   rI   rJ   rK   rL   rv   r   r   r   r   )
r   rN   r   r   r   	tags_listr2   rb   rR   r   s
             r   r   r   a  s   !!+.I}}  ,H==$$^4L.f#"%	I ',& F 4  }}' &m <}}}"!==2xD&&&00? *ffWo
>CVS&--*@A
FC1B1BCX1YZJV]]5F5Fy5QR*fc6==+<+<X+FN ZX?FF9M ++X-@-@-N-NO DQ$BCCDs   -F: :7H1H

Hc                 T    d}|t        | ||      z  }t        | ||d         }||d<   |S )NFrf   r   )r   rv   )r   rN   r   r   rb   s        r   
delete_keyr     s=    G!*flCCGZe1DEFF9Mr   c                 8    | y | j                  d      r| S d| z   S )Nzalias/)
startswith)r&   s    r   r   r     s(    }!er   c                 l   t        |j                  j                  d            }	 |rt        | |      d   S t        | |      d   S # | j                  j
                  $ r Y y t        j                  j                  t        j                  j                  f$ r}|j                  |d       Y d }~y d }~ww xY w)Nr&   re   zFailed to fetch key metadata.)
r   r2   rM   r6   rI   NotFoundExceptionrH   rJ   rK   rL   )r   rN   r,   r&   rR   s        r   fetch_key_metadatar     s     $FMM$5$5g$>?E
A0VD]SS,Z?NN  22 ++X-@-@-N-NO AQ ?@@As"   A A B3!6B3B..B3c                 x   | j                   j                  d      dk(  rL| j                   j                  d      r1|s/| j                  d| j                   j                  d       d       | j                   j                  d      r5|r2| j                   j                  d      dk(  r| j                  d       y y y y )	Nstatepresentr,   zCould not find key with id z
 to updaterC   r   z?You cannot change the multi-region property on an existing key.)r2   rM   	fail_json)rN   r   s     r   validate_paramsr     s    }}!Y.6==3D3DX3NWc:6==;L;LX;V:WWabc}}(\fmm>O>OPW>X\e>e^_ ?f\(r   c                     t        t        dg      t        dgd      t        dg      t               t        dd	      t        dd
	      t        ddg      t        dd	      t        dg d      t        d      t        dd
	      t        dddg      t        d      t        dddgg d      t        ddddg            } t        d| ddgg       }|j                  d!      }t        |||j                  j                  d      |j                  j                  d            }t        ||       |j                  j                  d"      dk(  r3||j                  d
#       t        |||      } |j                  d%i | |r/t        |||d$         }t        |||      } |j                  d%i | t        ||      } |j                  d%i | y )&N	key_alias)rk   deletion_delayint)rk   typerx   r   T)r   r   Fr#   resource_tags)r   rk   list)r   r   elementsrs   )r   r   absent)r   choicesstrSYMMETRIC_DEFAULTcustomer_master_key_spec)r  RSA_2048RSA_3072RSA_4096ECC_NIST_P256ECC_NIST_P384ECC_NIST_P521ECC_SECG_P256K1)r   r   rk   r   ENCRYPT_DECRYPTSIGN_VERIFY)r   r   r   )r&   r   r,   r   r   r   rO   r   rm   rX   r   r   ri   r   r   r&   r,   )supports_check_modeargument_specrequired_one_ofkmsr   )r   rf   r*   )r#   r   clientr   r2   rM   r   	exit_jsonr   rv   r   r   )r  rN   r  r   rb   key_detailss         r   mainr    s   K=)%5$6UCYK(F&$/vu5v'89VT2f= vu59y(.CD!v.'/0		
 %&6
;"MH  #!8,-F --
C%c66==3D3DX3NPVP]P]PaPabiPjkLFL)}}!X-U+C6"6"%c6<3FGC5"6"V$FFvr   __main__)F)5DOCUMENTATIONEXAMPLESRETURNrs   rH   ImportError0ansible.module_utils.common.dict_transformationsr   <ansible_collections.amazon.aws.plugins.module_utils.botocorer   ;ansible_collections.amazon.aws.plugins.module_utils.modulesr   :ansible_collections.amazon.aws.plugins.module_utils.policyr   ;ansible_collections.amazon.aws.plugins.module_utils.retriesr   ;ansible_collections.amazon.aws.plugins.module_utils.taggingr   r	   r
   jittered_backoffr   r   r'   r.   r3   r6   r9   r?   rS   rY   rc   rv   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  __name__r*   r   r   <module>r!     s  ^@3jP
d 	 V \ X W P f f X 1As;4 <4
 1As;4 <4

 1As;A <A 1As;< << 1As;1 <1 1As;@ <@
 1As;K <K0
E F"	2K$&0* :::0$)XA,`<~ zF U  		s   E EE