
    VhJ                        d Z dZd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
 Zd ZddZd Zd Zd Zd Zd ZdddgdZ ej6                  di edd       Z ej6                  di ed        Z ej6                  di edd       Z ej6                  di ed        Z ej6                  di ed        Z  ej6                  di ed        Z!e"dk(  r e        yy# e$ r Y w xY w)a  
---
module: api_gateway
version_added: 1.0.0
short_description: Manage AWS API Gateway APIs
description:
  - Allows for the management of API Gateway APIs.
  - Normally you should give the api_id since there is no other
    stable guaranteed unique identifier for the API.  If you do
    not give api_id then a new API will be created each time
    this is run.
  - swagger_file and swagger_text are passed directly on to AWS
    transparently whilst swagger_dict is an ansible dict which is
    converted to JSON before the API definitions are uploaded.
  - Prior to release 5.0.0 this module was called C(community.aws.aws_api_gateway).
    The usage did not change.
options:
  api_id:
    description:
      - The ID of the API you want to manage.
    type: str
  state:
    description: Create or delete API Gateway.
    default: present
    choices: [ 'present', 'absent' ]
    type: str
  swagger_file:
    description:
      - JSON or YAML file containing swagger definitions for API.
        Exactly one of I(swagger_file), I(swagger_text) or I(swagger_dict) must
        be present.
    type: path
    aliases: ['src', 'api_file']
  swagger_text:
    description:
      - Swagger definitions for API in JSON or YAML as a string direct
        from playbook.
    type: str
  swagger_dict:
    description:
      - Swagger definitions API ansible dictionary which will be
        converted to JSON and uploaded.
    type: json
  stage:
    description:
      - The name of the stage the API should be deployed to.
    type: str
  deploy_desc:
    description:
      - Description of the deployment.
      - Recorded and visible in the AWS console.
    default: Automatic deployment by Ansible.
    type: str
  cache_enabled:
    description:
      - Enable API GW caching of backend responses.
    type: bool
    default: false
  cache_size:
    description:
      - Size in GB of the API GW cache, becomes effective when cache_enabled is true.
    choices: ['0.5', '1.6', '6.1', '13.5', '28.4', '58.2', '118', '237']
    type: str
    default: '0.5'
  stage_variables:
    description:
      - ENV variables for the stage. Define a dict of key values pairs for variables.
    type: dict
    default: {}
  stage_canary_settings:
    description:
      - Canary settings for the deployment of the stage.
      - 'Dict with following settings:'
      - 'C(percentTraffic): The percent (0-100) of traffic diverted to a canary deployment.'
      - 'C(deploymentId): The ID of the canary deployment.'
      - 'C(stageVariableOverrides): Stage variables overridden for a canary release deployment.'
      - 'C(useStageCache): A Boolean flag to indicate whether the canary deployment uses the stage cache or not.'
      - See docs U(https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/apigateway.html#APIGateway.Client.create_stage)
    type: dict
    default: {}
  tracing_enabled:
    description:
      - Specifies whether active tracing with X-ray is enabled for the API GW stage.
    type: bool
    default: false
  endpoint_type:
    description:
      - Type of endpoint configuration.
      - Use C(EDGE) for an edge optimized API endpoint,
        C(REGIONAL) for just a regional deploy or C(PRIVATE) for a private API.
      - This flag will only be used when creating a new API Gateway setup, not for updates.
    choices: ['EDGE', 'REGIONAL', 'PRIVATE']
    type: str
    default: EDGE
  name:
    description:
      - The name of the RestApi.
    type: str
    version_added: 6.2.0
  lookup:
    description:
      - Look up API gateway by either I(tags) (and I(name) if supplied) or by I(api_id).
      - If I(lookup=tag) and I(tags) is not specified then no lookup for an existing API gateway
        is performed and a new API gateway will be created.
      - When using I(lookup=tag), multiple matches being found will result in a failure and no changes will be made.
      - To change the tags of a API gateway use I(lookup=id).
    default: tag
    choices: [ 'tag', 'id' ]
    type: str
    version_added: 6.2.0
author:
  - 'Michael De La Rue (@mikedlr)'
notes:
  - 'Tags are used to uniquely identify API gateway when the I(api_id) is not supplied. version_added=6.2.0'
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.boto3
  - amazon.aws.tags
a  
- name: Setup AWS API Gateway setup on AWS and deploy API definition
  community.aws.api_gateway:
    swagger_file: my_api.yml
    stage: production
    cache_enabled: true
    cache_size: '1.6'
    tracing_enabled: true
    endpoint_type: EDGE
    state: present

- name: Update API definition to deploy new version
  community.aws.api_gateway:
    api_id: 'abc123321cba'
    swagger_file: my_api.yml
    deploy_desc: Make auth fix available.
    cache_enabled: true
    cache_size: '1.6'
    endpoint_type: EDGE
    state: present

- name: Update API definitions and settings and deploy as canary
  community.aws.api_gateway:
    api_id: 'abc123321cba'
    swagger_file: my_api.yml
    cache_enabled: true
    cache_size: '6.1'
    canary_settings:
      percentTraffic: 50.0
      deploymentId: '123'
      useStageCache: true
    state: present

- name: Delete API gateway
  amazon.aws.api_gateway:
    name: ansible-rest-api
    tags:
      automation: ansible
    lookup: tags
    state: absent
a  
api_id:
    description: API id of the API endpoint created
    returned: success
    type: str
    sample: '0ln4zq7p86'
configure_response:
    description: AWS response from the API configure call
    returned: success
    type: dict
    sample: { api_key_source: "HEADER", created_at: "2020-01-01T11:37:59+00:00", id: "0ln4zq7p86" }
deploy_response:
    description: AWS response from the API deploy call
    returned: success
    type: dict
    sample: { created_date: "2020-01-01T11:36:59+00:00", id: "rptv4b", description: "Automatic deployment by Ansible." }
resource_actions:
    description: Actions performed against AWS API
    returned: always
    type: list
    sample: ["apigateway:CreateRestApi", "apigateway:CreateDeployment", "apigateway:PutRestApi"]
    N)camel_dict_to_snake_dict)is_boto3_error_code)AWSRetry)compare_aws_tags)AnsibleCommunityAWSModulec                     t        d?i dt        dd      dt        ddddg      d	t        d
d ddg      dt        dd       dt        dd       dt        dd       dt        dd      dt        dd      dt        ddg d      dt        di       dt        di       dt        dd      dt        ddg d       d!t        d"      d#t        dd$d%gd$&      d't        dd(g)      d*t        d+d,      } g d-g}t        | 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#      }|j	                  d/      }d+}d }d }d }|dk(  r||
r|d$k(  rt        |||	|
      }|r|d%   }|j                  r|j                  d+d01       |/t        ||||-      }t        |||	||
      }t        ||||      \  }}|j                  j                  d'      }
|j                  j                  d*      }|
r<|st        |||2      }t        ||||j                  d'      |
|3      \  }}|r||z  }|}|dk(  r|B|d$k7  s|
s|j                  d45       t        |||	|
      }|s|j                  dd61       |d%   }n$t        |||      s|j                  dd7| d81       |j                  r|j                  d+d9|:       t        |||      }||d;}|t!        |      |d<<   |t!        |      |d=<   |t!        |      |d><    |j                  d?i | y )@Napi_idstrF)typerequiredstatepresentabsent)r   defaultchoicesswagger_filepathsrcapi_file)r   r   aliasesswagger_dictjson)r   r   swagger_textstagedeploy_descz Automatic deployment by Ansible.cache_enabledbool
cache_size0.5)r   z1.6z6.1z13.5z28.4z58.2118237stage_variablesdictstage_canary_settingstracing_enabledendpoint_typeEDGE)r'   REGIONALPRIVATEname)r   lookuptagid)r   r   r   tagsresource_tags)r   r   
purge_tagsT)r   r   )r   r   r   )argument_specsupports_check_modemutually_exclusive
apigatewayz8Create/update operation skipped - running in check mode.)changedmsgr	   )r	   current_tagsnew_tagsr0   zqAPI gateway id must be supplied to delete API gateway or provided tag with lookup=tag to identify API gateway id.r6   z,No API gateway identified with tags providedzAPI gateway id 'z' does not exist.z1Delete operation skipped - running in check mode.)r5   r6   r	   )r5   r	   configure_responsedeploy_responsedelete_response )r#   AnsibleAWSModuleparamsgetclientget_api_by_tags
check_mode	exit_jsonget_api_definitionscreate_empty_apiensure_api_in_correct_stateget_rest_apiensure_apigateway_tags	fail_jsondescribe_apidelete_rest_apir   )r1   r3   moduler	   r   r   r   r   r&   r*   r.   r+   rB   r5   conf_resdep_resdel_resrest_apiapi_datar0   tag_changed
tag_result	exit_argss                          m/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/aws/plugins/modules/api_gateway.pymainrX      s]    /y9h:OP vteZ=PQ vt4	
 ud3 t, e-OP 6 UE;vw &"5 #; &%8 v?^_ u uE  v'89!" 62#M( KK# -F ]]x(FMMg&E==$$^4L==$$^4L==$$^4LMM%%o6M==V$D==V$D]]x(F]]<(FGHGG	>%*664F%d^FT/ij>*\[gH &ffdM4PF ;FFFT\ ]Hg}}  (]]&&|4
'vF&<vHLL<P[_lv'#K ;&%>d   L !  'vvtTBH  4b cd^Ffff5U2B6(J[0\]T/bkqr!&&&9#v6I*B8*L	&''?'H	#$'?'H	#$F!y!    c                     d}i }t        |||      \  }}	|s|	rLd}d| j                   d| }
|	r|j                  |
|	       |r|j                  |
|       t	        | ||      }||fS )NFTzarn:aws:apigateway:z::/restapis/)resourceArntagKeys)r[   r.   r7   )r   regionuntag_resourcetag_resourcerI   )rN   rB   r	   r8   r9   r0   r5   rU   tags_to_settags_to_deleteapigateway_arns              rW   rJ   rJ   9  s    GJ"2<:"VKn.v}}o\&R!!nn!UNM!&&@
JrY   c                 x   d }|%	 t        |      5 }|j                         }d d d        |t        j                  |      }||}|| j	                  d       |S # 1 sw Y   :xY w# t        $ rI}dt        |       dt        |       }| j	                  |t        j                                Y d }~d }~ww xY w)Nz#Failed trying to read swagger file z: )r6   	exceptionz'module error - no swagger info providedr:   )	openreadOSErrorr
   rK   	traceback
format_excr   dumps)rN   r   r   r   apidatafer6   s           rW   rF   rF   K  s    G	Hl# #q&&(#
 **\*FGN# # 	H7L8I7J"SQRVHUC	0D0D0FGG	Hs-   A' AA' A$ A' '	B90?B44B9c                    	 |j                  |      }|j                  dd        |S # t        j                  j                  t        j                  j
                  f$ r }| j                  |d|        Y d }~y d }~ww xY w)N	restApiIdResponseMetadataz#failed to get REST API with api_id=r:   )rI   popbotocore
exceptionsClientErrorBotoCoreErrorfail_json_aws)rN   rB   r	   responserm   s        rW   rI   rI   ^  s|    T&&&8'.++X-@-@-N-NO TQ&I&$RSSTs   %( 7A?A::A?c                     d}	 |xs d}t        |||||      }|d   S # t        j                  j                  t        j                  j                  f$ r!}| j                  |d       Y d}~d   S d}~ww xY w)z
    creates a new empty API ready to be configured. The description is
    temporarily set to show the API as incomplete but should be
    updated when the API is configured.
    z5Incomplete API creation by ansible api_gateway modulezansible-temp-api)r*   descriptionr&   r.   zcreating APIr:   Nr-   )
create_apirs   rt   ru   EndpointConnectionErrorrw   )	rN   rB   r*   r&   r.   descrest_api_nameawsretrm   s	            rW   rG   rG   g  s     CD42 2FDXelpq $< ++X-@-@-X-XY 4QN33$<4s    7A7A22A7c                     	 t        ||      }|S # t        j                  j                  t        j                  j                  f$ r!}| j                  |d|        Y d}~S d}~ww xY w)z'
    Deletes entire REST API setup
    zdeleting API r:   N)
delete_apirs   rt   ru   r|   rw   )rN   rB   r	   r=   rm   s        rW   rM   rM   v  sm    >$VV4  ++X-@-@-X-XY >QmF8$<==>s    7A(A##A(c                 `   d}	 t        |||      }|j                  dd       d}| j                  j                  d      }|r.	 t        ||fi | j                  }|j                  dd       ||fS ||fS # 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'}d| d| }| j                  ||       Y d}~||fS d}~ww xY w)	a  Make sure that we have the API configured and deployed as instructed.

    This function first configures the API correctly uploading the
    swagger definitions and then deploys those.  Configuration and
    deployment should be closely tied because there is only one set of
    definitions so if we stop, they may be updated by someone else and
    then we deploy the wrong configuration.
    N)rS   rq   zconfiguring API r:   r   zdeploying api z
 to stage )
configure_apirr   rs   rt   ru   r|   rw   r@   rA   create_deployment)	rN   rB   r	   rS   r;   rm   r<   r   r6   s	            rW   rH   rH     s>    A*66HM148 OMMg&E	)/P&--PO 2D9
 .... ++X-@-@-X-XY AQ&6vh$?@@A ##//1D1D1\1\] 	)"6(*UG<C  C((..		)s/    A5 )C 57C,CC7D-D((D-c                    d}d }t        |       D ]I  }|r	|d   |k7  r|j                  di       t        fd|j                         D              sC|}|dz  }K |dkD  rd}|r|dz  }|j	                  | d	       |S )
Nr   r*   r.   c              3   @   K   | ]  \  }}|v xr |   |k(    y w)Nr>   ).0tag_key	tag_valueapi_tagss      rW   	<genexpr>z"get_api_by_tags.<locals>.<genexpr>  s.     nK]7T]8#F(9Y(FFns      Tagsz	 and namez. provided do not identify a unique API gatewayr:   )	list_apisrA   allitemsrK   )	rB   rN   r*   r.   countresultapiargsr   s	           @rW   rC   rC     s    EF  CK4'7762&naeakakamnoFQJE qyKDv%STUMrY   
   TooManyRequestsException)retriesdelaycatch_extra_error_codesc                 ^    d|i}|r||d<   |rd|gi|d<   |r||d<    | j                   di |S )Nr*   rz   typesendpointConfigurationr.   r>   )create_rest_api)rB   r*   rz   r&   r.   r@   s         rW   r{   r{     sO    d^F +}+2]O*D&'v!6!!+F++rY   c                 &    | j                  |      S )Nro   )rM   )rB   r	   s     rW   r   r     s    !!F!33rY   c                 *    | j                  |||      S )N)rp   modebody)put_rest_api)rB   r	   rS   r   s       rW   r   r     s    dJJrY   c                    |j                  d      }|rt        |      dkD  ru| j                  ||j                  d      |j                  d      |j                  d      |j                  d      |j                  d      ||j                  d      	      }|S | j                  ||j                  d      |j                  d      |j                  d      |j                  d      |j                  d      |j                  d      
      }|S )Nr$   r   r   r   r   r   r"   r%   )rp   	stageNamerz   cacheClusterEnabledcacheClusterSize	variablescanarySettingstracingEnabled)rp   r   rz   r   r   r   r   )rA   lenr   )rB   rest_api_idr@   canary_settingsr   s        rW   r   r     s    jj!89O3/!3))!jj)

=1 &

? ;#ZZ5jj!23*!::&78 * 	
* M ))!jj)

=1 &

? ;#ZZ5jj!23!::&78 * 
 MrY   c                     | j                  d      }|j                         j                         j                  dg       S )Nget_rest_apisr   )get_paginatorpaginatebuild_full_resultrA   )rB   	paginators     rW   r   r     s7    $$_5I11377DDrY   c                 *   	 | j                  |      }|j                  d       |S # t        d      $ r i }Y |S t        j                  j
                  t        j                  j                  f$ r"}|j                  |d| d       Y d }~S d }~ww xY w)Nro   rq   ResourceNotFoundExceptionzTrying to get Rest API 'z'.r:   )rI   rr   r   rs   rt   ru   rv   rw   )rB   rN   r   rx   rm   s        rW   rL   rL     s    	P&&&='( O :;  O	 	'')) P 	Q&>{m2$NOOOPs   #' B6B0BB__main__)NNNr>   )N	overwrite)#DOCUMENTATIONEXAMPLESRETURNr   rh   rs   ImportError0ansible.module_utils.common.dict_transformationsr   <ansible_collections.amazon.aws.plugins.module_utils.botocorer   ;ansible_collections.amazon.aws.plugins.module_utils.retriesr   ;ansible_collections.amazon.aws.plugins.module_utils.taggingr   >ansible_collections.community.aws.plugins.module_utils.modulesr   r?   rX   rJ   rF   rI   rG   rM   rH   rC   retry_paramsjittered_backoffr{   r   r   r   r   rL   __name__r>   rY   rW   <module>r      s  wr(T
.  	 V \ P X xd"N$&T/>& HbGcd *\*, +, *\*4 +4 *\*K +K *\* +8 *\*E +E
 *\* + zF q	  		s   C2 2C:9C: