
    Vh0                         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 Z G d de      Zy# e$ r Y @w xY w)a
  
name: secretsmanager_secret
author:
  - Aaron Smith (!UNKNOWN) <ajsmith10381@gmail.com>

short_description: Look up secrets stored in AWS Secrets Manager
description:
  - Look up secrets stored in AWS Secrets Manager provided the caller
    has the appropriate permissions to read the secret.
  - Lookup is based on the secret's I(Name) value.
  - Optional parameters can be passed into this lookup; O(version_id) and O(version_stage).
  - Prior to release 6.0.0 this module was known as C(aws_ssm), the usage remains the same.

options:
  _terms:
    description: Name of the secret to look up in AWS Secrets Manager.
    required: true
  bypath:
    description: A boolean to indicate whether the parameter is provided as a hierarchy.
    default: false
    type: bool
    version_added: 1.4.0
  nested:
    description: A boolean to indicate the secret contains nested values.
    type: bool
    default: false
    version_added: 1.4.0
  version_id:
    description: Version of the secret(s).
    required: false
  version_stage:
    description: Stage of the secret version.
    required: false
  join:
    description:
      - Join two or more entries to form an extended secret.
      - This is useful for overcoming the 4096 character limit imposed by AWS.
      - No effect when used with O(bypath).
    type: bool
    default: false
  on_deleted:
    description:
      - Action to take if the secret has been marked for deletion.
      - V(error) will raise a fatal error when the secret has been marked for deletion.
      - V(skip) will silently ignore the deleted secret.
      - V(warn) will skip over the deleted secret but issue a warning.
    default: "error"
    type: str
    choices: ["error", "skip", "warn"]
    version_added: 2.0.0
  on_missing:
    description:
      - Action to take if the secret is missing.
      - C(error) will raise a fatal error when the secret is missing.
      - C(skip) will silently ignore the missing secret.
      - C(warn) will skip over the missing secret but issue a warning.
    default: "error"
    type: str
    choices: ["error", "skip", "warn"]
  on_denied:
    description:
      - Action to take if access to the secret is denied.
      - C(error) will raise a fatal error when access to the secret is denied.
      - C(skip) will silently ignore the denied secret.
      - C(warn) will skip over the denied secret but issue a warning.
    default: "error"
    type: str
    choices: ["error", "skip", "warn"]
extends_documentation_fragment:
  - amazon.aws.boto3
  - amazon.aws.common.plugins
  - amazon.aws.region.plugins
aU  
- name: Lookup secretsmanager secret in the current region
  ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_secret', '/path/to/secrets', bypath=true) }}"

- name: Create RDS instance with aws_secret lookup for password param
  amazon.aws.rds_instance:
    state: present
    db_instance_identifier: app-db
    engine: mysql
    instance_type: db.m1.small
    username: dbadmin
    password: "{{ lookup('amazon.aws.aws_secret', 'DbSecret') }}"
    tags:
      Environment: staging

- name: Skip if secret does not exist
  ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_secret', 'secret-not-exist', on_missing='skip')}}"

- name: Warn if access to the secret is denied
  ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_secret', 'secret-denied', on_denied='warn')}}"

- name: Lookup secretsmanager secret in the current region using the nested feature
  ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_secret', 'secrets.environments.production.password', nested=true) }}"
  # The secret can be queried using the following syntax: `aws_secret_object_name.key1.key2.key3`.
  # If an object is of the form `{"key1":{"key2":{"key3":1}}}` the query would return the value `1`.
- name: Lookup secretsmanager secret in a specific region using specified region and aws profile using nested feature
  ansible.builtin.debug: >
   msg="{{ lookup('amazon.aws.aws_secret', 'secrets.environments.production.password', region=region, profile=aws_profile,
   access_key=aws_access_key, secret_key=aws_secret_key, nested=true) }}"
  # The secret can be queried using the following syntax: `aws_secret_object_name.key1.key2.key3`.
  # If an object is of the form `{"key1":{"key2":{"key3":1}}}` the query would return the value `1`.
  # Region is the AWS region where the AWS secret is stored.
  # AWS_profile is the aws profile to use, that has access to the AWS secret.
zU
_raw:
  description: Returns the value of the secret stored in AWS Secrets Manager.
    N)AnsibleLookupError)	to_native)string_types)is_boto3_error_code)is_boto3_error_message)AWSRetry)AWSLookupBasec                 R    | j                  d      }|j                  d|gdg      S )Nlist_secretsname)KeyValues)Filters)get_paginatorpaginate)clientterm	paginators      s/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/lookup/secretsmanager_secret.py_list_secretsr      s0    $$^4Iv$'H&IJJ    c                   2     e Zd Z fdZ	 	 	 	 	 	 ddZ xZS )LookupModulec                    t        |   ||fi | | j                  d      }| j                  d      }| j                  d      }|0t        |t              r|j                         dvrt        d|       |0t        |t              r|j                         dvrt        d|       |0t        |t              r|j                         dvrt        d|       | j                  d	t        j                               }| j                  d
      r[i }|D ]R  }		 t        ||	      D ]=  }
d|
v s|
d   D ].  }|j                  |d   | j                  |d   |||      i       0 ? |g}T |S g }|D ]\  }	| j                  |	|| j                  d      | j                  d      |||| j                  d            }|sL|j%                  |       ^ | j                  d      r$g }|j%                  dj'                  |             |S |S # t        j                  j                  t        j                  j                   f$ r}t        dt#        |             d}~ww xY w)a  
        :arg terms: a list of lookups to run.
            e.g. ['example_secret_name', 'example_secret_too' ]
        :variables: ansible variables active at the time of the lookup
        :returns: A list of parameter values or a list of dictionaries if bypath=True.
        
on_missing	on_denied
on_deletedN)errorwarnskipzH"on_missing" must be a string and one of "error", "warn" or "skip", not zG"on_denied" must be a string and one of "error", "warn" or "skip", not zH"on_deleted" must be a string and one of "error", "warn" or "skip", not secretsmanagerbypath
SecretListName)r   r   Failed to retrieve secret: version_stage
version_idnested)r&   r'   r   r   r   r(   join )superrun
get_option
isinstancer   lowerr   r   r   jittered_backoffr   updateget_secret_valuebotocore
exceptionsClientErrorBotoCoreErrorr   appendr)   )selfterms	variableskwargsr   r   r   r   secretsr   secret_wrapper
secret_objevaluejoined_secret	__class__s                  r   r,   zLookupModule.run   s    	E9//__\2
OOK0	__\2
 !:|4
8H8H8JRk8k$Z[eZfg   9l3y7HPi7i$YZcYde  !:|4
8H8H8JRk8k$Z[eZfg  -x/H/H/JK??8$G [[*7*E 	"'>9.<\.J "
 '(26(:D<Q<Q,6v,>S]ir =R =*%&!""	"  'iG[H ' G *--"&///"B#|<)')??84 . 	 NN5)* v& "$$RWWW%56$$- !++779L9L9Z9Z[ [,/J9UV<.-YZZ[s   H-;H7I=IIc	                    i }	||	d<   |r||	d<   |r||	d<   |rAt        |j                  d            dk  rt        d      |j                  d      d   }
|
|	d<   	  |j                  ddd	i|	}d
|v r|d
   S d|v r|r|j                  d      dd  }d }t	        j
                  |d         }|}|rc|j                  d      }|s|n|dz   |z   }||v r||   }n9|dk(  r | j                  j                  d| d       y |dk(  rt        d| d      |rct        |      S |d   S 	 y # t        d      $ r: |dk(  rt        d| d      |dk(  r| j                  j                  d|        Y y t        d      $ r: |dk(  rt        d| d      |dk(  r| j                  j                  d|        Y y t        d      $ r: |dk(  rt        d| d      |dk(  r| j                  j                  d|        Y y t        j                  j                  t        j                  j                  f$ r}t        dt!        |             d }~ww xY w)NSecretId	VersionIdVersionStage.   zRNested query must use the following syntax: `aws_secret_name.<key_name>.<key_name>r   	aws_retryTSecretBinarySecretString   r   z@Skipping, Successfully retrieved secret but there exists no key z in the secretr   z6Successfully retrieved secret but there exists no key zmarked for deletionzFailed to find secret z (marked for deletion)z4Skipping, did not find secret (marked for deletion) ResourceNotFoundExceptionz (ResourceNotFound)zSkipping, did not find secret AccessDeniedExceptionzFailed to access secret z (AccessDenied)z#Skipping, access denied for secret r%    )lensplitr   r2   jsonloadspop_displaywarningstrr   r   r3   r4   r5   r6   r   )r8   r   r   r&   r'   r   r   r   r(   paramssecret_nameresponsequerypathsecret_stringret_valkeyr?   s                     r   r2   zLookupModule.get_secret_value   s    !z",F;%2F>"4::c?#a'(h  **S/!,K!,F:.	S.v..HHHH)//) JJsOAB/ED$(JJx/G$HM+G#iil*.sD3J4D'>&-clG'61 MM11"bcgbhhv w $('72"4"XY]X^^l m#    w<'#N33- *X + &&;< 	eW$(+A$G])^__v%%%(\]a\b&cd" ! ##>? 	OW$(+A$GZ)[\\v%%%(Ftf&MN  ##:; 	TG#(+CD6)YZZf$%%(KD6&RS  ++--
 	S %'B9Q<.%QRR		SsF   D$ 7BD$ ;D$ 
D$ D$ $AI	+AI	1AI	76I	-II	)NNNNNF)__name__
__module____qualname__r,   r2   __classcell__)rB   s   @r   r   r      s$    J` Ir   r   )DOCUMENTATIONEXAMPLESRETURNrR   r3   ImportErroransible.errorsr   ansible.module_utils._textr   ansible.module_utils.sixr   <ansible_collections.amazon.aws.plugins.module_utils.botocorer   r   ;ansible_collections.amazon.aws.plugins.module_utils.retriesr   :ansible_collections.amazon.aws.plugins.plugin_utils.lookupr	   r   r   rO   r   r   <module>rn      si   HT!F

 	 . 0 1 \ _ P TK
V= V%  		s   A	 	AA