
    Vha                        d Z dZd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 ddlmZ ddlmZ ddlmZ  G d de      Z G d de      Zd Zd Zd Zedk(  r e        yy# e	$ r Y dw xY w)ag  
---
module: secretsmanager_secret
version_added: 1.0.0
short_description: Manage secrets stored in AWS Secrets Manager
description:
  - Create, update, and delete secrets stored in AWS Secrets Manager.
  - Prior to release 5.0.0 this module was called C(community.aws.aws_secret).
    The usage did not change.
author:
  - "REY Remi (@rrey)"
options:
  name:
    description:
    - Friendly name for the secret you are creating.
    required: true
    type: str
  state:
    description:
    - Whether the secret should be exist or not.
    default: 'present'
    choices: ['present', 'absent']
    type: str
  overwrite:
    description:
    - Whether to overwrite an existing secret with the same name.
    - If set to C(True), an existing secret with the same I(name) will be overwritten.
    - If set to C(False), a secret with the given I(name) will only be created if none exists.
    type: bool
    default: True
    version_added: 5.3.0
  recovery_window:
    description:
    - Only used if state is absent.
    - Specifies the number of days that Secrets Manager waits before it can delete the secret.
    - If set to 0, the deletion is forced without recovery.
    default: 30
    type: int
  description:
    description:
    - Specifies a user-provided description of the secret.
    type: str
    default: ''
  replica:
    description:
    - Specifies a list of regions and kms_key_ids (optional) to replicate the secret to
    type: list
    elements: dict
    version_added: 5.3.0
    suboptions:
      region:
        description:
          - Region to replicate secret to.
        type: str
        required: true
      kms_key_id:
        description:
          - Specifies the ARN or alias of the AWS KMS customer master key (CMK) in the
            destination region to be used (alias/aws/secretsmanager is assumed if not specified)
        type: str
        required: false
  kms_key_id:
    description:
    - Specifies the ARN or alias of the AWS KMS customer master key (CMK) to be
      used to encrypt the I(secret) values in the versions stored in this secret.
    type: str
  secret_type:
    description:
    - Specifies the type of data that you want to encrypt.
    choices: ['binary', 'string']
    default: 'string'
    type: str
  secret:
    description:
    - Specifies string or binary data that you want to encrypt and store in the new version of the secret.
    - Mutually exclusive with the I(json_secret) option.
    default: ""
    type: str
  json_secret:
    description:
    - Specifies JSON-formatted data that you want to encrypt and store in the new version of the
      secret.
    - Mutually exclusive with the I(secret) option.
    type: json
    version_added: 4.1.0
  resource_policy:
    description:
    - Specifies JSON-formatted resource policy to attach to the secret. Useful when granting cross-account access
       to secrets.
    required: false
    type: json
    version_added: 3.1.0
  rotation_lambda:
    description:
    - Specifies the ARN of the Lambda function that can rotate the secret.
    type: str
  rotation_interval:
    description:
    - Specifies the number of days between automatic scheduled rotations of the secret.
    default: 30
    type: int
notes:
  - Support for I(purge_tags) was added in release 4.0.0.
extends_documentation_fragment:
  - amazon.aws.region.modules
  - amazon.aws.common.modules
  - amazon.aws.tags
  - amazon.aws.boto3
a  
- name: Add string to AWS Secrets Manager
  community.aws.secretsmanager_secret:
    name: 'test_secret_string'
    state: present
    secret_type: 'string'
    secret: "{{ super_secret_string }}"

- name: Add a secret with resource policy attached
  community.aws.secretsmanager_secret:
    name: 'test_secret_string'
    state: present
    secret_type: 'string'
    secret: "{{ super_secret_string }}"
    resource_policy: "{{ lookup('template', 'templates/resource_policy.json.j2', convert_data=False) | string }}"

- name: remove string from AWS Secrets Manager
  community.aws.secretsmanager_secret:
    name: 'test_secret_string'
    state: absent
    secret_type: 'string'
    secret: "{{ super_secret_string }}"

- name: Only create a new secret, but do not update if alredy exists by name
  community.aws.secretsmanager_secret:
    name: 'random_string'
    state: present
    secret_type: 'string'
    secret: "{{ lookup('community.general.random_string', length=16, special=false) }}"
    overwrite: false
a  
secret:
  description: The secret information
  returned: always
  type: complex
  contains:
    arn:
      description: The ARN of the secret.
      returned: always
      type: str
      sample: arn:aws:secretsmanager:eu-west-1:xxxxxxxxxx:secret:xxxxxxxxxxx
    description:
      description: A description of the secret.
      returned: when the secret has a description
      type: str
      sample: An example description
    last_accessed_date:
      description: The date the secret was last accessed.
      returned: always
      type: str
      sample: '2018-11-20T01:00:00+01:00'
    last_changed_date:
      description: The date the secret was last modified.
      returned: always
      type: str
      sample: '2018-11-20T12:16:38.433000+01:00'
    name:
      description: The secret name.
      returned: always
      type: str
      sample: my_secret
    rotation_enabled:
      description: The secret rotation status.
      returned: always
      type: bool
      sample: false
    version_ids_to_stages:
      description: Provide the secret version ids and the associated secret stage.
      returned: always
      type: dict
      sample: { "dc1ed59b-6d8e-4450-8b41-536dfe4600a9": [ "AWSCURRENT" ] }
    tags:
      description:
        - A list of dictionaries representing the tags associated with the secret in the standard boto3 format.
      returned: when the secret has tags
      type: list
      elements: dict
      contains:
        key:
          description: The name or key of the tag.
          type: str
          example: MyTag
          returned: success
        value:
          description: The value of the tag.
          type: str
          example: Some value.
          returned: success
    tags_dict:
      description: A dictionary representing the tags associated with the secret.
      type: dict
      returned: when the secret has tags
      example: {'MyTagName': 'Some Value'}
      version_added: 4.0.0
    N)
format_exc)BotoCoreError)ClientError)to_bytes)camel_dict_to_snake_dict)snake_dict_to_camel_dict)compare_policies)ansible_dict_to_boto3_tag_list)boto3_tag_list_to_ansible_dict)compare_aws_tags)AnsibleCommunityAWSModulec                   l    e Zd ZdZ	 	 	 	 	 	 	 d	dZed        Zed        Zed        Zed        Z	d Z
y)
SecretzHAn object representation of the Secret described by the self.module argsNc                     || _         || _        |
| _        || _        |dk(  rd| _        nd| _        || _        || _        |xs i | _        d| _        |r!d| _        || _	        dt        |	      i| _        y y )NbinarySecretBinarySecretStringFTAutomaticallyAfterDays)namedescriptionreplica_regions
kms_key_idsecret_typesecretresource_policytagsrotation_enabledrotation_lambda_arnintrotation_rules)selfr   r   r   r   r   r   r   
lambda_arnrotation_intervalr   s              w/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/aws/plugins/modules/secretsmanager_secret.py__init__zSecret.__init__   s     	&.$("-D-D.JB	 %$(D!'1D$#;SAR=S"TD     c                    d| j                   i}| j                  r| j                  |d<   | j                  r| j                  |d<   | j                  rNg }| j                  D ]8  }|d   r|j	                  |d   |d   d       #|j	                  d|d   i       : ||d<   | j
                  rt        | j
                        |d	<   | j                  || j                  <   |S )
NNameDescriptionKmsKeyIdr   regionRegionr*   r-   AddReplicaRegionsTags)	r   r   r   r   appendr   r
   r   r   )r!   argsadd_replica_regionsreplicas       r$   create_argszSecret.create_args  s    		""&"2"2D??#D"$// N<('..'(:KY`amYn/op'..'(:K/LM	N
 )<D$%999$))DDL!%Tr&   c                     d| j                   i}| j                  r| j                  |d<   | j                  r| j                  |d<   | j                  || j                  <   |S )NSecretIdr)   r*   )r   r   r   r   r   r!   r1   s     r$   update_argszSecret.update_args!  sW    DII&"&"2"2D??#D!%Tr&   c                 X    d| j                   i}| j                  r| j                  |d<   |S )Nr6   ResourcePolicy)r   r   r7   s     r$   secret_resource_policy_argsz"Secret.secret_resource_policy_args+  s/    DII&%)%9%9D!"r&   c                 ,    t        | j                        S )N)r
   r/   )r!   s    r$   
boto3_tagszSecret.boto3_tags2  s    -dii88r&   c                 R    | j                   }|j                  d       t        |      S )Nr   )__dict__popr   )r!   results     r$   as_dictzSecret.as_dict6  s"    

6'//r&   )N NNNNN)__name__
__module____qualname____doc__r%   propertyr4   r8   r;   r=   rB    r&   r$   r   r      sw    R U<  &     9 90r&   r   c                   j    e 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 Zd Zd Zd Zd Zy)SecretsManagerInterfacez An interface with SecretsManagerc                 R    || _         | j                   j                  d      | _        y )Nsecretsmanager)moduleclient)r!   rN   s     r$   r%   z SecretsManagerInterface.__init__?  s     kk(()9:r&   c                     	 | j                   j                  |      }|S # | j                   j                  j                  $ r d }Y |S t        $ r(}| j
                  j                  |d       Y d }~S d }~ww xY w)Nr6   zFailed to describe secretmsg)rO   describe_secret
exceptionsResourceNotFoundException	ExceptionrN   fail_json_aws)r!   r   r   es       r$   
get_secretz"SecretsManagerInterface.get_secretC  s    	J[[00$0?F
 	 {{%%?? 	F   	JKK%%a-H%II	Js     %A8A8A33A8c                    	 | j                   j                  |      }|S # | j                   j                  j                  $ r d }Y |S t        t
        f$ r(}| j                  j                  |d       Y d }~S d }~ww xY w)NrQ   z$Failed to get secret resource policyrR   )rO   get_resource_policyrU   rV   r   r   rN   rX   )r!   r   r   rY   s       r$   r\   z+SecretsManagerInterface.get_resource_policyL  s    	U"kk==t=LO
 	 {{%%?? 	#"O  {+ 	UKK%%a-S%TT	Us     %A>A>A99A>c                    | j                   j                  r| j                   j                  d       	  | j                  j                  di |j
                  }|j                  r%| j                  |      }|j                  d      d<   S # t        t        f$ r'}| j                   j                  |d       Y d }~dd }~ww xY w)NTchangedzFailed to create secretrR   	VersionIdrI   )rN   
check_mode	exit_jsonrO   create_secretr4   r   r   rX   r   update_rotationget)r!   r   created_secretrY   responses        r$   rc   z%SecretsManagerInterface.create_secretU  s    ;;!!KK!!$!/	H6T[[66L9K9KLN ""++F3H*2,,{*CN;' {+ 	HKK%%a-F%GG	Hs   &B CB>>Cc                 ,   | j                   j                  r| j                   j                  d       	  | j                  j                  di |j
                  }|S # t        t        f$ r(}| j                   j                  |d       Y d }~S d }~ww xY w)NTr^   zFailed to update secretrR   rI   )	rN   ra   rb   rO   update_secretr8   r   r   rX   r!   r   rg   rY   s       r$   ri   z%SecretsManagerInterface.update_secretb  s    ;;!!KK!!$!/	H0t{{00F63E3EFH  {+ 	HKK%%a-F%GG	Hs   &A B+BBc                 $   | j                   j                  r| j                   j                  d       	 t        j                  |j
                  j                  d             	  | j                  j                  di |j
                  }|S # t        t        f$ r;}| j                   j                  dt        |       t                      Y d }~nd }~ww xY w# t        t        f$ r(}| j                   j!                  |d       Y d }~S d }~ww xY w)	NTr^   r:   z)Failed to parse resource policy as JSON: )rS   	exceptionz'Failed to update secret resource policyrR   rI   )rN   ra   rb   jsonloadsr;   re   	TypeError
ValueError	fail_jsonstrr   rO   put_resource_policyr   r   rX   )r!   r   rY   rg   s       r$   rs   z+SecretsManagerInterface.put_resource_policyk  s    ;;!!KK!!$!/	tJJv99==>NOP	X6t{{66\9[9[\H  :& 	tKK!!(QRUVWRXQY&Zfpfr!ss	t
 {+ 	XKK%%a-V%WW	Xs/   .B #&C C1CCD'D

Dc                    | j                   j                  r| j                   j                  d       	 | j                  j	                  ||      }|S # t
        t        f$ r(}| j                   j                  |d       Y d }~S d }~ww xY w)NTr^   )r6   RemoveReplicaRegionsFailed to replicate secretrR   )rN   ra   rb   rO   remove_regions_from_replicationr   r   rX   )r!   r   regionsrg   rY   s        r$   remove_replicationz*SecretsManagerInterface.remove_replicationy  s    ;;!!KK!!$!/	K{{BBDgnBoH  {+ 	KKK%%a-I%JJ	Ks   A B
"BB
c                    | j                   j                  r| j                   j                  d       	 g }|D ]8  }|d   r|j                  |d   |d   d       #|j                  d|d   i       : | j                  j                  ||      }|S # t        t        f$ r(}| j                   j                  |d	       Y d }~S d }~ww xY w)
NTr^   r   r+   r,   r-   )r6   r.   rv   rR   )	rN   ra   rb   r0   rO   replicate_secret_to_regionsr   r   rX   )r!   r   rx   r   r3   rg   rY   s          r$   replicate_secretz(SecretsManagerInterface.replicate_secret  s    ;;!!KK!!$!/		K O" J<(#**gh6GU\]iUj+kl#**Hgh6G+HI	J
 {{>>`o>pH  {+ 	KKK%%a-I%JJ	Ks   AB C	!CC	c                    | j                   j                  r| j                   j                  d       	 | j                  j	                  |      }|S # t
        t        f$ r(}| j                   j                  |d       Y d }~S d }~ww xY w)NTr^   rQ   zFailed to restore secretrR   )rN   ra   rb   rO   restore_secretr   r   rX   r!   r   rg   rY   s       r$   r~   z&SecretsManagerInterface.restore_secret  s    ;;!!KK!!$!/	I{{1141@H  {+ 	IKK%%a-G%HH	I   A B	!BB	c                 d   | j                   j                  r| j                   j                  d       	 |dk(  r| j                  j	                  |d      }|S | j                  j	                  ||      }	 |S # t
        t        f$ r(}| j                   j                  |d       Y d }~S d }~ww xY w)NTr^   r   )r6   ForceDeleteWithoutRecovery)r6   RecoveryWindowInDayszFailed to delete secretrR   )rN   ra   rb   rO   delete_secretr   r   rX   )r!   r   recovery_windowrg   rY   s        r$   r   z%SecretsManagerInterface.delete_secret  s    ;;!!KK!!$!/	H!#;;44d_c4d
   ;;44dYh4i  {+ 	HKK%%a-F%GG	Hs   "A8 A8 8B/B**B/c                    | j                   j                  r| j                   j                  d       	 | j                  j	                  |      }|S # t
        t        f$ r(}| j                   j                  |d       Y d }~S d }~ww xY w)NTr^   rQ   z'Failed to delete secret resource policyrR   )rN   ra   rb   rO   delete_resource_policyr   r   rX   r   s       r$   r   z.SecretsManagerInterface.delete_resource_policy  s    ;;!!KK!!$!/	X{{9949HH  {+ 	XKK%%a-V%WW	Xr   c                    |j                   r?	 | j                  j                  |j                  |j                  |j
                        }|S 	 | j                  j                  |j                        }|S # t        t        f$ r(}| j                  j                  |d       Y d }~S d }~ww xY w# t        t        f$ r(}| j                  j                  |d       Y d }~S d }~ww xY w)N)r6   RotationLambdaARNRotationRuleszFailed to rotate secret secretrR   rQ   zFailed to cancel rotation)r   rO   rotate_secretr   r   r    r   r   rN   rX   cancel_rotate_secretrj   s       r$   rd   z'SecretsManagerInterface.update_rotation  s    ""S;;44#[[&,&@&@"("7"7 5  	N;;;;V[[;Q  ";/ S))!1Q)RR S
 ";/ N))!1L)MMNs/   <A5 &B/ 5B,B''B,/C&>C!!C&c                    | j                   j                  r| j                   j                  d       	 | j                  j	                  ||       y # t
        t        f$ r'}| j                   j                  |d       Y d }~y d }~ww xY w)NTr^   )r6   r/   zFailed to add tag(s) to secretrR   )rN   ra   rb   rO   tag_resourcer   r   rX   )r!   secret_namer   rY   s       r$   
tag_secretz"SecretsManagerInterface.tag_secret  ss    ;;!!KK!!$!/	OKK$$k$E{+ 	OKK%%a-M%NN	O   A B!BBc                    | j                   j                  r| j                   j                  d       	 | j                  j	                  ||       y # t
        t        f$ r'}| j                   j                  |d       Y d }~y d }~ww xY w)NTr^   )r6   TagKeysz#Failed to remove tag(s) from secretrR   )rN   ra   rb   rO   untag_resourcer   r   rX   )r!   r   tag_keysrY   s       r$   untag_secretz$SecretsManagerInterface.untag_secret  ss    ;;!!KK!!$!/	TKK&&X&N{+ 	TKK%%a-R%SS	Tr   c                 x   |j                   |j                  dd      k7  ry|j                  |j                  d      k7  ry| j                  j	                  |j                  d            }|j
                  dk(  rt        |j                        }n|j                  }||j                  |j
                        k7  ryy)	zCompare secrets except tags and rotation

        Args:
            desired_secret: camel dict representation of the desired secret state.
            current_secret: secret reference as returned by the secretsmanager api.

        Returns: bool
        r)   rC   Fr*   r(   rQ   r   T)r   re   r   rO   get_secret_valuer   r   r   )r!   desired_secretcurrent_secretcurrent_secret_valuedesired_values        r$   secrets_matchz%SecretsManagerInterface.secrets_match  s     %%););M2)NN$$(:(::(FF#{{;;^EWEWX^E_;`%%7$^%:%:;M*11M044^5O5OPPr&   N)rD   rE   rF   rG   r%   rZ   r\   rc   ri   rs   ry   r|   r~   r   r   rd   r   r   r   rI   r&   r$   rK   rK   <  sR    *;
"OTr&   rK   c                     | j                   |j                  dd      k7  ry| j                   r>| j                  |j                  d      k7  ry| j                  |j                  d      k7  ryy)zCompare secrets rotation configuration

    Args:
        desired_secret: camel dict representation of the desired secret state.
        current_secret: secret reference as returned by the secretsmanager api.

    Returns: bool
    RotationEnabledFr   r   T)r   re   r   r    )r   r   s     r$   rotation_matchr     si     &&.*<*<=NPU*VV&&--1C1CDW1XX((N,>,>,OOr&   c                 .   g }g }| j                   ||fS | j                   r| j                   }|j                  dg       D ]Q  }|r9|D ]3  }|d   |d   k(  r|j                  |        |j                  |d          5 >|j                  |d          S ||fS )zCompare secrets replication configuration

    Args:
        desired_secret: camel dict representation of the desired secret state.
        current_secret: secret reference as returned by the secretsmanager api.

    Returns: bool
    ReplicationStatusr-   r+   )r   re   remover0   )r   r   regions_to_set_replicationregions_to_remove_replicationcurrent_secret_regiondesired_secret_regions         r$   compare_regionsr     s     "$$&!%%-)+HHH%%%3%C%C"!/!3!34G!L R%)C Z%(26KH6UU.556KL1889Nx9XY	Z *001Fx1PQR &'DDDr&   c                     t        t        dd      t        dd            } t        t        d      t        ddgd	      t        d
d      t        d      t        dd|       t               t        ddgd	      t        dd      t        dd      t        dd       t        dd dg      t        d
d      t               t        dd      t        dd      dddggd      }d}|j                  j                  d      }t	        |      }|j                  j                  d      }t        |j                  j                  d       |j                  j                  d!      |j                  j                  d      xs |j                  j                  d      |j                  j                  d"      |j                  j                  d#      |j                  j                  d$      |j                  j                  d%      |j                  j                  d&      |j                  j                  d'      |j                  j                  d(      )
      }|j                  j                  d*      }|j                  |j                        }|dk(  r|r||j                  d+      s)t        |j                  |j                  |,            }	d}nD|j                  d+      r.|d-k(  r)t        |j                  |j                  |,            }	d}nd.}	nd/}	|dk(  r|C|j                  |      }	|j                  r"|	j                  d0      r|j                  |      }	d}n|j                  d+      r|j                  |j                         d}|j                  ||      s0|j                  j                  d1      }
|
r|j                  |      }	d}t!        ||      s|j#                  |      }	d}|j%                  |j                        }|j                  d2      }t'        |j                  |      r=|j                  |r|j)                  |j                        }	n|j                  |      }	d}|j                  j                  d&      ~t+        |j                  d3g             }t-        ||j.                  |      \  }}|r'|j1                  |j                  t3        |             d}|r|j5                  |j                  |       d}t7        ||      \  }}|r|j9                  |j                  |       d}|r|j;                  |j                  |       d}t        |j                  |j                              }	|	j                  d&d       t+        |	j                  d&g             |	d4<   |	j=                  d5       |j?                  |	6       y )7Nrr   T)typerequiredF)r+   r   )r   presentabsent)choicesdefaultbool)r   r   rC   )r   listdict)r   elementsoptionsr   string)r   no_logrm   )r   r   resource_tags)r   r   aliasesr      )r   state	overwriter   r3   r   r   r   json_secretr   r   
purge_tagsrotation_lambdar#   r   r   r   )argument_specmutually_exclusivesupports_check_moder   r   r   r   r   r3   r   r   r   r   r#   )r   r   r   r   r   r"   r#   r   DeletedDate)r   r   z%secret already scheduled for deletionzsecret does not existARNr   r:   r/   	tags_dictresponse_metadata)r_   r   ) r   AnsibleAWSModuleparamsre   rK   r   rZ   r   r   r   rc   r   rs   r~   r   ri   r   rd   r\   r	   r   r   r   r   r   r
   r   r   r|   ry   r@   rb   )replica_argsrN   r_   r   secrets_mgrr   r   r   r   rA   r    current_resource_policy_responsecurrent_resource_policycurrent_tagstags_to_addtags_to_remover   r   s                     r$   mainr     s   .UU3L
 $'9h"7K648+&,O&8(<hO2d3VD9#>fd_<MNFD9#v!%5"!=#;
" &}56 'F, GMMg&E)&1Kmm''(9:O&!-((#Gv}}'8'8'GMM%%m4)))4==$$\2))*;<]]v&==$$%67 --++,?@F ""<0J ++FKK8N!%%m41--fkk?-[ ##M2!7K1--fkk?-[ @,F	! ..v6F%%&**U*;$88@G !!-0**6;;7,,V^D"MM--k:	(66v>F"G!&.9$44V</:/N/Nv{{/[,&F&J&JK[&\# 6 68OP))16M(??LF(<<VDF}}  (4=n>P>PQWY[>\].>|V[[Zd.e+^**6;;8VWb8cd"G!,,V[[.I"GHWX^`nHoE&(E),,V[[:TU,..v{{<YZ)+*@*@*MN::fd#/"@FTVAW"XF;

&'
WV4r&   __main__)DOCUMENTATIONEXAMPLESRETURNrm   	tracebackr   botocore.exceptionsr   r   ImportErroransible.module_utils._textr   0ansible.module_utils.common.dict_transformationsr   r   :ansible_collections.amazon.aws.plugins.module_utils.policyr	   ;ansible_collections.amazon.aws.plugins.module_utils.taggingr
   r   r   >ansible_collections.community.aws.plugins.module_utils.modulesr   r   objectr   rK   r   r   r   rD   rI   r&   r$   <module>r      s   l\@@
D   	1/ 0 U U W f f X xM0V M0`hf hV&E>t5n zF g  		s   A; ;BB