
    Vhc=                     L   d Z ddlZddl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 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      Z de	def   fdZ!de	def   fdZ"y)a  This module adds shared support for generic Amazon AWS modules

In order to use this module, include it as part of a custom
module as shown below.

  from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
  module = AnsibleAWSModule(argument_spec=dictionary, supports_check_mode=boolean
                            mutually_exclusive=list1, required_together=list2)

The 'AnsibleAWSModule' module provides similar, but more restricted,
interfaces to the normal Ansible module.  It also includes the
additional methods for connecting to AWS using the standard module arguments

    m.resource('lambda') # - get an AWS connection as a boto3 resource.

or

    m.client('sts') # - get an AWS connection as a boto3 client.

To make use of AWSRetry easier, it can now be wrapped around any call from a
module-created client. To add retries to a client, create a client:

    m.client('ec2', retry_decorator=AWSRetry.jittered_backoff(retries=10))

Any calls from that client can be made to use the decorator passed at call-time
using the `aws_retry` argument. By default, no retries are used.

    ec2 = m.client('ec2', retry_decorator=AWSRetry.jittered_backoff(retries=10))
    ec2.describe_instances(InstanceIds=['i-123456789'], aws_retry=True)

The call will be retried the specified number of times, so the calling functions
don't need to be wrapped in the backoff decorator.
    N)StringIO)Any)Dict)NoReturn)Optional)	to_native)AnsibleModule)env_fallback)missing_required_lib)camel_dict_to_snake_dict   boto3_at_least)
boto3_connbotocore_at_least)check_sdk_version_supportedgather_sdk_versions)get_aws_connection_infoget_aws_region)AnsibleBotocoreError)RetryingBotoClientWrapperc                   D   e Zd ZdZdddedZd Zedee	e
f   fd       Zd ZdefdZdefd	ZddZddZd ZdefdZde	fdZdde	fdZde	fdZedee	   fd       Zddedee	   defdZdefdZdee	e
f   fdZde	dd
fdZde	defdZde	dd
fdZ de	defdZ!y
) AnsibleAWSModulea  An ansible module class for AWS modules

    AnsibleAWSModule provides an a class for building modules which
    connect to Amazon Web Services.  The interface is currently more
    restricted than the basic module class with the aim that later the
    basic module class can be reduced.  If you find that any key
    feature is missing please contact the author/Ansible AWS team
    (available on #ansible-aws on IRC) to request the additional
    features needed.
    T)default_argscheck_boto3
auto_retrymodule_classc                 D   i }t         j                  j                         D ]  \  }}	 |j                  |      ||<    || _        |d   r$t               }	 |j                  |d          ||d<   t        j                  d   di || _
        |d   r	 t        | j                         h d}|j!                  t#        t$        j&                  j)                                     r| j                  j+                  ddd	
       dt$        j&                  j)                         v r| j                  j+                  ddd	
       | j                  j,                  | _        | j                  j.                  | _        | j                  j0                  | _        t3               | _        d | _        | j8                  j;                  d      r|t=        j>                  d      | _        | j6                  jA                  t<        jB                         | j6                  jE                  t=        jF                  | j4                               y y # t        $ r	 |||<   Y ,w xY w# t        t        f$ r Y w xY w# t        $ r/}| j                  j                  t        |             Y d }~d }~ww xY w)Nr   argument_specr    r   )warn>   S3_URLEC2_URL
EC2_REGIONEC2_ACCESS_KEYEC2_SECRET_KEYEC2_SECURITY_TOKENa  Support for the 'EC2_REGION', 'EC2_ACCESS_KEY', 'EC2_SECRET_KEY', 'EC2_SECURITY_TOKEN', 'EC2_URL', and 'S3_URL' environment variables has been deprecated.  These variables are currently used for all AWS services which can cause confusion.  We recomend using the relevant module parameters or alternatively the 'AWS_REGION', 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN', and 'AWS_URL' environment variables can be used instead.z10.0.0
amazon.aws)versioncollection_nameAWS_SECURITY_TOKENa5  Support for the 'AWS_SECURITY_TOKEN' environment variable has been deprecated.  This variable was based on the original boto SDK, support for which has now been dropped.  We recommend using the 'session_token' module parameter or alternatively the 'AWS_SESSION_TOKEN' environment variable can be used instead.debug_botocore_endpoint_logszbotocore.endpoint )$r   default_settingsitemspopKeyErrorsettingsaws_argument_specupdate	TypeError	NameError_moduler   r#   r   	fail_jsonr   intersectionsetosenvironkeys	deprecate
check_mode_diff_namer   _botocore_endpoint_log_streamloggerparamsgetlogging	getLoggersetLevelDEBUG
addHandlerStreamHandler)selfkwargslocal_settingskeydefault_valueargument_spec_fulledeprecated_varss           k/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/module_utils/modules.py__init__zAnsibleAWSModule.__init__T   s<   "2"C"C"I"I"K 	4C4&,jjos#	4
 '.)!2!4"))&*AB '9F?#'88HR6R-(5+; x''BJJOO,=(>?LL""A ! , #   2::??#44LL""+ ! , #  ,,11\\''
\\''
-5Z*;;??9:!++,?@DKKK  /KK""7#8#89[9[#\] ;s  4&3s#4 y)  ( 5&&y|445s;   H<I I' <III$#I$'	J0$JJreturnc                 .    | j                   j                  S N)r9   rF   rN   s    rV   rF   zAnsibleAWSModule.params   s    ||"""    c                    g }| j                   j                         j                  d      D ]~  }|j                         }|s	 t	        j
                  d|      }|j                  d      dd }t	        j
                  d|      j                  d      dd }|j                  | d|         t        t        |            S # t        $ r Y w xY w)	N
zOperationModel\(name=.*?\)r      zhttps://.*?\.   :)rD   getvaluesplitstripresearchgroupappendAttributeErrorlistr<   )rN   actionslnfound_operational_requestoperation_requestresources         rV   _get_resource_action_listz*AnsibleAWSModule._get_resource_action_list   s    44==?EEdK 	BB,.II6SUW,X)$=$C$CA$Fr%! 99%5r:@@CAbI(1->,?@A	 CL!! " s   A(C	CCc                     | j                   j                  d      r| j                         |d<    | j                  j                  |i | y Nr.   resource_actions)rF   rG   rq   r9   	exit_jsonrN   argsrO   s      rV   ru   zAnsibleAWSModule.exit_json   @    ;;??9:)-)G)G)IF%&//r\   c                     | j                   j                  d      r| j                         |d<    | j                  j                  |i | y rs   )rF   rG   rq   r9   r:   rv   s      rV   r:   zAnsibleAWSModule.fail_json   rx   r\   Nc                 :     | j                   j                  |i |S rZ   )r9   debugrv   s      rV   r{   zAnsibleAWSModule.debug   s    !t||!!42622r\   c                 :     | j                   j                  |i |S rZ   )r9   r#   rv   s      rV   r#   zAnsibleAWSModule.warn   s     t||  $1&11r\   c                 x    t        | j                  |      rt        | j                  |      S t        d| d      )Nz#AnsibleAWSModule has no attribute '')hasattrr9   getattrrj   )rN   attrs     rV   __getattr__zAnsibleAWSModule.__getattr__   s6    4<<&4<<..B4&JKKr\   c                 :     | j                   j                  |i |S rZ   )r9   booleanrv   s      rV   r   zAnsibleAWSModule.boolean   s    #t||##T4V44r\   c                 :     | j                   j                  |i |S rZ   )r9   md5rv   s      rV   r   zAnsibleAWSModule.md5   s    t||000r\   servicec                     t        |       \  }}}t        d||d|}|j                  |       t        | fd|d|}||S t	        ||      S )Nregionendpointclient	conn_typerp   r/   )r   dictr6   r   r   )	rN   r   retry_decoratorextra_paramsr   endpoint_urlaws_connect_kwargskw_argsconns	            rV   r   zAnsibleAWSModule.client   sd    3J43P00Rf|R?QR|$$P(WPP&.td4MdTc4ddr\   c                 |    t        |       \  }}}t        d||d|}|j                  |       t        | fd|d|S )Nr   rp   r   r/   )r   r   r6   r   )rN   r   r   r   r   r   r   s          rV   rp   zAnsibleAWSModule.resource   sL    3J43P00Rf|R?QR|$$R*wR'RRr\   c                     t        |       S rZ   r   r[   s    rV   r   zAnsibleAWSModule.region   s    d##r\   	exceptionmsgc                    t        j                         }	 t        |j                        }|| d| }n|}	 |j
                  }t        d||d| j                         }|j                  |       | |j                  di t        |        | j                  di | y# t        $ r t        |      }Y w xY w# t        $ r d}Y w xY w)zcall fail_json with processed exception

        function for converting exceptions thrown by AWS SDK modules,
        botocore, boto3 and boto, into nice error messages.
        Nz: )r   r   r/   )	traceback
format_excr   messagerj   responser   _gather_versionsr6   r   r:   )	rN   r   r   rO   last_traceback
except_msgr   r   failures	            rV   fail_json_awszAnsibleAWSModule.fail_json_aws   s     #--/	."9#4#45J ?R
|,G G	 ))H X7nX@U@U@WXvGNN@5h?@!!)  	."9-J	.  	H	s"   B! B; !B87B8;C	C	c                     |j                   r'| j                  |j                   |j                         | j                  |j                         y)zIA helper to call the right failure mode after catching an AnsibleAWSError)r   N)r   r   r   r:   )rN   r   s     rV   fail_json_aws_errorz$AnsibleAWSModule.fail_json_aws_error   s>    y22	8I8IJ9,,-r\   c                     t               S )zGather AWS SDK (boto3 and botocore) dependency versions

        Returns {'boto3_version': str, 'botocore_version': str}
        Returns {} if either is not installed
        r   r[   s    rV   r   z!AnsibleAWSModule._gather_versions   s     #$$r\   desiredc           	          | j                  |      s: | j                  j                  ddt        d| fi |i| j	                          yy)a  Check if the available boto3 version is greater than or equal to a desired version.

        calls fail_json() when the boto3 version is less than the desired
        version

        Usage:
            module.require_boto3_at_least("1.2.3", reason="to update tags")
            module.require_boto3_at_least("1.1.1")

        :param desired the minimum desired version
        :param reason why the version is required (optional)
        r   zboto3>=Nr/   )r   r9   r:   r   r   rN   r   rO   s      rV   require_boto3_at_leastz'AnsibleAWSModule.require_boto3_at_least  sU     ""7+"DLL"" (77))<GG'') ,r\   c                     t        |      S rZ   r   rN   r   s     rV   r   zAnsibleAWSModule.boto3_at_least  s    g&&r\   c           	          | j                  |      s: | j                  j                  ddt        d| fi |i| j	                          yy)a  Check if the available botocore version is greater than or equal to a desired version.

        calls fail_json() when the botocore version is less than the desired
        version

        Usage:
            module.require_botocore_at_least("1.2.3", reason="to update tags")
            module.require_botocore_at_least("1.1.1")

        :param desired the minimum desired version
        :param reason why the version is required (optional)
        r   z
botocore>=Nr/   )r   r9   r:   r   r   r   s      rV   require_botocore_at_leastz*AnsibleAWSModule.require_botocore_at_least  sU     %%g."DLL"" (:gY)?J6J'') /r\   c                     t        |      S rZ   r   r   s     rV   r   z"AnsibleAWSModule.botocore_at_least1  s     ))r\   )rX   NrZ   )"__name__
__module____qualname____doc__r	   r0   rW   propertyr   strr   rF   rq   r   ru   r:   r{   r#   r   boolr   r   r   rp   r   r   BaseExceptionr   r   r   r   r   r   r   r/   r\   rV   r   r   F   sQ   	 )-TQUgtuA^F #S#X # #""0H 0
0H 0
32L
5$ 51c 1ec eS S $ $ $ "}  "8C=  "^f  "D. .%$sCx. %c  &'c 'd ' 4 &* * *r\   r   rX   r   c                  2   t        t        g dt        ddd      gt        g dfd      t        g d	t        d
dd      gt        g dfd      t        g dt        ddd      t        ddd      t        ddd      gt        g dfd      t        dgt        ddgf      t        g dt        ddd      t        ddd      gt        g df      t        dd      t        dt        dgf      t        d !      t        ddt        d"gf#      $	      S )%z
    This does not include 'region' as some AWS APIs don't require a
    region.  However, it's not recommended to do this as it means module_defaults
    can't include the region parameter.
    )aws_access_key_idaws_access_keyec2_access_keyr   
2024-12-01r*   namedater,   )AWS_ACCESS_KEY_IDAWS_ACCESS_KEYr'   F)aliasesdeprecated_aliasesfallbackno_log)aws_secret_access_keyaws_secret_keyec2_secret_keyr   )AWS_SECRET_ACCESS_KEYAWS_SECRET_KEYr(   T)aws_session_tokensecurity_tokenaccess_tokenaws_security_tokenr   r   r   )AWS_SESSION_TOKENr-   r)   aws_profileAWS_PROFILEAWS_DEFAULT_PROFILE)r   r   )aws_endpoint_urlec2_urls3_urlr   r   )AWS_URLr%   r$   r   r   r   r   )typedefaultpathAWS_CA_BUNDLE)r   r   r   )r   ANSIBLE_DEBUG_BOTOCORE_LOGS)r   r   r   )	
access_key
secret_keysession_tokenprofiler   validate_certsaws_ca_bundle
aws_configr.   )r   r
   r/   r\   rV   _aws_common_argument_specr   5  sT    M*|\  #$]^
 Q*|\  #$ab
 a.|\Z*|\.\S_` 
 #$ef	
 "O"]4I$JK
 =),U(|T  #$DE
 
 "_$56
 
 &*"%B$CD&
e7 7r\   c            
          t        t        ddgt        ddd      gt        g df            } t               }|j                  |        |S )	zV
    Returns a dictionary containing the argument_spec common to all AWS modules.
    
aws_region
ec2_regionr   r*   r   )
AWS_REGIONAWS_DEFAULT_REGIONr&   r   )r   )r   r
   r   r6   )region_specspecs     rV   r5   r5   u  sU     !<0,\<X  #$VW
K %&DKKKr\   )#r   rH   r=   rf   r   ior   typingr   r   r   r   ansible.module_utils._textr   ansible.module_utils.basicr	   r
   r   0ansible.module_utils.common.dict_transformationsr   botocorer   r   r   r   r   r   r   
exceptionsr   retriesr   r   r   r5   r/   r\   rV   <module>r      s    D  	 	       0 4 3 ; U $   ' 1 ) - $ , .l* l*^=4s
#3 =@4s
+ r\   