Debian Codegraph @

ansible_collections/community/aws/plugins/modules/api_gateway.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: api_gateway
10 version_added: 1.0.0
11 short_description: Manage AWS API Gateway APIs
12 description:
13 - Allows for the management of API Gateway APIs.
14 - Normally you should give the api_id since there is no other
15 stable guaranteed unique identifier for the API. If you do
16 not give api_id then a new API will be created each time
17 this is run.
18 - swagger_file and swagger_text are passed directly on to AWS
19 transparently whilst swagger_dict is an ansible dict which is
20 converted to JSON before the API definitions are uploaded.
21 - Prior to release 5.0.0 this module was called C(community.aws.aws_api_gateway).
22 The usage did not change.
23 options:
24 api_id:
25 description:
26 - The ID of the API you want to manage.
27 type: str
28 state:
29 description: Create or delete API Gateway.
30 default: present
31 choices: [ 'present', 'absent' ]
32 type: str
33 swagger_file:
34 description:
35 - JSON or YAML file containing swagger definitions for API.
36 Exactly one of I(swagger_file), I(swagger_text) or I(swagger_dict) must
37 be present.
38 type: path
39 aliases: ['src', 'api_file']
40 swagger_text:
41 description:
42 - Swagger definitions for API in JSON or YAML as a string direct
43 from playbook.
44 type: str
45 swagger_dict:
46 description:
47 - Swagger definitions API ansible dictionary which will be
48 converted to JSON and uploaded.
49 type: json
50 stage:
51 description:
52 - The name of the stage the API should be deployed to.
53 type: str
54 deploy_desc:
55 description:
56 - Description of the deployment.
57 - Recorded and visible in the AWS console.
58 default: Automatic deployment by Ansible.
59 type: str
60 cache_enabled:
61 description:
62 - Enable API GW caching of backend responses.
63 type: bool
64 default: false
65 cache_size:
66 description:
67 - Size in GB of the API GW cache, becomes effective when cache_enabled is true.
68 choices: ['0.5', '1.6', '6.1', '13.5', '28.4', '58.2', '118', '237']
69 type: str
70 default: '0.5'
71 stage_variables:
72 description:
73 - ENV variables for the stage. Define a dict of key values pairs for variables.
74 type: dict
75 default: {}
76 stage_canary_settings:
77 description:
78 - Canary settings for the deployment of the stage.
79 - 'Dict with following settings:'
80 - 'C(percentTraffic): The percent (0-100) of traffic diverted to a canary deployment.'
81 - 'C(deploymentId): The ID of the canary deployment.'
82 - 'C(stageVariableOverrides): Stage variables overridden for a canary release deployment.'
83 - 'C(useStageCache): A Boolean flag to indicate whether the canary deployment uses the stage cache or not.'
84 - See docs U(https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/apigateway.html#APIGateway.Client.create_stage)
85 type: dict
86 default: {}
87 tracing_enabled:
88 description:
89 - Specifies whether active tracing with X-ray is enabled for the API GW stage.
90 type: bool
91 default: false
92 endpoint_type:
93 description:
94 - Type of endpoint configuration.
95 - Use C(EDGE) for an edge optimized API endpoint,
96 C(REGIONAL) for just a regional deploy or C(PRIVATE) for a private API.
97 - This flag will only be used when creating a new API Gateway setup, not for updates.
98 choices: ['EDGE', 'REGIONAL', 'PRIVATE']
99 type: str
100 default: EDGE
101 name:
102 description:
103 - The name of the RestApi.
104 type: str
105 version_added: 6.2.0
106 lookup:
107 description:
108 - Look up API gateway by either I(tags) (and I(name) if supplied) or by I(api_id).
109 - If I(lookup=tag) and I(tags) is not specified then no lookup for an existing API gateway
110 is performed and a new API gateway will be created.
111 - When using I(lookup=tag), multiple matches being found will result in a failure and no changes will be made.
112 - To change the tags of a API gateway use I(lookup=id).
113 default: tag
114 choices: [ 'tag', 'id' ]
115 type: str
116 version_added: 6.2.0
117 author:
118 - 'Michael De La Rue (@mikedlr)'
119 notes:
120 - 'Tags are used to uniquely identify API gateway when the I(api_id) is not supplied. version_added=6.2.0'
121 extends_documentation_fragment:
122 - amazon.aws.common.modules
123 - amazon.aws.region.modules
124 - amazon.aws.boto3
125 - amazon.aws.tags
126 """
127
128 EXAMPLES = r"""
129 - name: Setup AWS API Gateway setup on AWS and deploy API definition
130 community.aws.api_gateway:
131 swagger_file: my_api.yml
132 stage: production
133 cache_enabled: true
134 cache_size: '1.6'
135 tracing_enabled: true
136 endpoint_type: EDGE
137 state: present
138
139 - name: Update API definition to deploy new version
140 community.aws.api_gateway:
141 api_id: 'abc123321cba'
142 swagger_file: my_api.yml
143 deploy_desc: Make auth fix available.
144 cache_enabled: true
145 cache_size: '1.6'
146 endpoint_type: EDGE
147 state: present
148
149 - name: Update API definitions and settings and deploy as canary
150 community.aws.api_gateway:
151 api_id: 'abc123321cba'
152 swagger_file: my_api.yml
153 cache_enabled: true
154 cache_size: '6.1'
155 canary_settings:
156 percentTraffic: 50.0
157 deploymentId: '123'
158 useStageCache: true
159 state: present
160
161 - name: Delete API gateway
162 amazon.aws.api_gateway:
163 name: ansible-rest-api
164 tags:
165 automation: ansible
166 lookup: tags
167 state: absent
168 """
169
170 RETURN = r"""
171 api_id:
172 description: API id of the API endpoint created
173 returned: success
174 type: str
175 sample: '0ln4zq7p86'
176 configure_response:
177 description: AWS response from the API configure call
178 returned: success
179 type: dict
180 sample: { api_key_source: "HEADER", created_at: "2020-01-01T11:37:59+00:00", id: "0ln4zq7p86" }
181 deploy_response:
182 description: AWS response from the API deploy call
183 returned: success
184 type: dict
185 sample: { created_date: "2020-01-01T11:36:59+00:00", id: "rptv4b", description: "Automatic deployment by Ansible." }
186 resource_actions:
187 description: Actions performed against AWS API
188 returned: always
189 type: list
190 sample: ["apigateway:CreateRestApi", "apigateway:CreateDeployment", "apigateway:PutRestApi"]
191 """
192
193 import json
194 import traceback
195
196 try:
197 import botocore
198 except ImportError:
199 pass # Handled by AnsibleAWSModule
200
201 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
202
203 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
204 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
205 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
206
207 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
208
209
210 def main():
211 argument_spec = dict(
212 api_id=dict(type="str", required=False),
213 state=dict(type="str", default="present", choices=["present", "absent"]),
214 swagger_file=dict(type="path", default=None, aliases=["src", "api_file"]),
215 swagger_dict=dict(type="json", default=None),
216 swagger_text=dict(type="str", default=None),
217 stage=dict(type="str", default=None),
218 deploy_desc=dict(type="str", default="Automatic deployment by Ansible."),
219 cache_enabled=dict(type="bool", default=False),
220 cache_size=dict(type="str", default="0.5", choices=["0.5", "1.6", "6.1", "13.5", "28.4", "58.2", "118", "237"]),
221 stage_variables=dict(type="dict", default={}),
222 stage_canary_settings=dict(type="dict", default={}),
223 tracing_enabled=dict(type="bool", default=False),
224 endpoint_type=dict(type="str", default="EDGE", choices=["EDGE", "REGIONAL", "PRIVATE"]),
225 name=dict(type="str"),
226 lookup=dict(type="str", choices=["tag", "id"], default="tag"),
227 tags=dict(type="dict", aliases=["resource_tags"]),
228 purge_tags=dict(default=True, type="bool"),
229 )
230
231 mutually_exclusive = [["swagger_file", "swagger_dict", "swagger_text"]] # noqa: F841
232
233 module = AnsibleAWSModule(
234 argument_spec=argument_spec,
235 supports_check_mode=True,
236 mutually_exclusive=mutually_exclusive,
237 )
238
239 api_id = module.params.get("api_id")
240 state = module.params.get("state") # noqa: F841
241 swagger_file = module.params.get("swagger_file")
242 swagger_dict = module.params.get("swagger_dict")
243 swagger_text = module.params.get("swagger_text")
244 endpoint_type = module.params.get("endpoint_type")
245 name = module.params.get("name")
246 tags = module.params.get("tags")
247 lookup = module.params.get("lookup")
248
249 client = module.client("apigateway")
250
251 changed = True # for now it will stay that way until we can sometimes avoid change
252 conf_res = None
253 dep_res = None
254 del_res = None
255
256 if state == "present":
257 if api_id is None:
258 # lookup API gateway using tags
259 if tags and lookup == "tag":
260 rest_api = get_api_by_tags(client, module, name, tags)
261 if rest_api:
262 api_id = rest_api["id"]
263 if module.check_mode:
264 module.exit_json(changed=True, msg="Create/update operation skipped - running in check mode.")
265 if api_id is None:
266 api_data = get_api_definitions(
267 module, swagger_file=swagger_file, swagger_dict=swagger_dict, swagger_text=swagger_text
268 )
269 # create new API gateway as non were provided and/or found using lookup=tag
270 api_id = create_empty_api(module, client, name, endpoint_type, tags)
271 conf_res, dep_res = ensure_api_in_correct_state(module, client, api_id, api_data)
272 tags = module.params.get("tags")
273 purge_tags = module.params.get("purge_tags")
274 if tags:
275 if not conf_res:
276 conf_res = get_rest_api(module, client, api_id=api_id)
277 tag_changed, tag_result = ensure_apigateway_tags(
278 module, client, api_id=api_id, current_tags=conf_res.get("tags"), new_tags=tags, purge_tags=purge_tags
279 )
280 if tag_changed:
281 changed |= tag_changed
282 conf_res = tag_result
283 if state == "absent":
284 if api_id is None:
285 if lookup != "tag" or not tags:
286 module.fail_json(
287 msg="API gateway id must be supplied to delete API gateway or provided tag with lookup=tag to identify API gateway id."
288 )
289 rest_api = get_api_by_tags(client, module, name, tags)
290 if not rest_api:
291 module.exit_json(changed=False, msg="No API gateway identified with tags provided")
292 api_id = rest_api["id"]
293 elif not describe_api(client, module, api_id):
294 module.exit_json(changed=False, msg=f"API gateway id '{api_id}' does not exist.")
295
296 if module.check_mode:
297 module.exit_json(changed=True, msg="Delete operation skipped - running in check mode.", api_id=api_id)
298
299 del_res = delete_rest_api(module, client, api_id)
300
301 exit_args = {"changed": changed, "api_id": api_id}
302
303 if conf_res is not None:
304 exit_args["configure_response"] = camel_dict_to_snake_dict(conf_res)
305 if dep_res is not None:
306 exit_args["deploy_response"] = camel_dict_to_snake_dict(dep_res)
307 if del_res is not None:
308 exit_args["delete_response"] = camel_dict_to_snake_dict(del_res)
309
310 module.exit_json(**exit_args)
311
312
313 def ensure_apigateway_tags(module, client, api_id, current_tags, new_tags, purge_tags):
314 changed = False
315 tag_result = {}
316 tags_to_set, tags_to_delete = compare_aws_tags(current_tags, new_tags, purge_tags)
317 if tags_to_set or tags_to_delete:
318 changed = True
319 apigateway_arn = f"arn:aws:apigateway:{module.region}::/restapis/{api_id}"
320 # Remove tags from Resource
321 if tags_to_delete:
322 client.untag_resource(resourceArn=apigateway_arn, tagKeys=tags_to_delete)
323 # add new tags to resource
324 if tags_to_set:
325 client.tag_resource(resourceArn=apigateway_arn, tags=tags_to_set)
326 # Describe API gateway
327 tag_result = get_rest_api(module, client, api_id=api_id)
328 return changed, tag_result
329
330
331 def get_api_definitions(module, swagger_file=None, swagger_dict=None, swagger_text=None):
332 apidata = None
333 if swagger_file is not None:
334 try:
335 with open(swagger_file) as f:
336 apidata = f.read()
337 except OSError as e:
338 msg = f"Failed trying to read swagger file {str(swagger_file)}: {str(e)}"
339 module.fail_json(msg=msg, exception=traceback.format_exc())
340 if swagger_dict is not None:
341 apidata = json.dumps(swagger_dict)
342 if swagger_text is not None:
343 apidata = swagger_text
344
345 if apidata is None:
346 module.fail_json(msg="module error - no swagger info provided")
347 return apidata
348
349
350 def get_rest_api(module, client, api_id):
351 try:
352 response = client.get_rest_api(restApiId=api_id)
353 response.pop("ResponseMetadata", None)
354 return response
355 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
356 module.fail_json_aws(e, msg=f"failed to get REST API with api_id={api_id}")
357
358
359 def create_empty_api(module, client, name, endpoint_type, tags):
360 """
361 creates a new empty API ready to be configured. The description is
362 temporarily set to show the API as incomplete but should be
363 updated when the API is configured.
364 """
365 desc = "Incomplete API creation by ansible api_gateway module"
366 try:
367 rest_api_name = name or "ansible-temp-api"
368 awsret = create_api(client, name=rest_api_name, description=desc, endpoint_type=endpoint_type, tags=tags)
369 except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError) as e:
370 module.fail_json_aws(e, msg="creating API")
371 return awsret["id"]
372
373
374 def delete_rest_api(module, client, api_id):
375 """
376 Deletes entire REST API setup
377 """
378 try:
379 delete_response = delete_api(client, api_id)
380 except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError) as e:
381 module.fail_json_aws(e, msg=f"deleting API {api_id}")
382 return delete_response
383
384
385 def ensure_api_in_correct_state(module, client, api_id, api_data):
386 """Make sure that we have the API configured and deployed as instructed.
387
388 This function first configures the API correctly uploading the
389 swagger definitions and then deploys those. Configuration and
390 deployment should be closely tied because there is only one set of
391 definitions so if we stop, they may be updated by someone else and
392 then we deploy the wrong configuration.
393 """
394
395 configure_response = None
396 try:
397 configure_response = configure_api(client, api_id, api_data=api_data)
398 configure_response.pop("ResponseMetadata", None)
399 except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError) as e:
400 module.fail_json_aws(e, msg=f"configuring API {api_id}")
401
402 deploy_response = None
403
404 stage = module.params.get("stage")
405 if stage:
406 try:
407 deploy_response = create_deployment(client, api_id, **module.params)
408 deploy_response.pop("ResponseMetadata", None)
409 except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError) as e:
410 msg = f"deploying api {api_id} to stage {stage}"
411 module.fail_json_aws(e, msg)
412
413 return configure_response, deploy_response
414
415
416 def get_api_by_tags(client, module, name, tags):
417 count = 0
418 result = None
419 for api in list_apis(client):
420 if name and api["name"] != name:
421 continue
422 api_tags = api.get("tags", {})
423 if all((tag_key in api_tags and api_tags[tag_key] == tag_value for tag_key, tag_value in tags.items())):
424 result = api
425 count += 1
426
427 if count > 1:
428 args = "Tags"
429 if name:
430 args += " and name"
431 module.fail_json(msg=f"{args} provided do not identify a unique API gateway")
432 return result
433
434
435 retry_params = {"retries": 10, "delay": 10, "catch_extra_error_codes": ["TooManyRequestsException"]}
436
437
438 @AWSRetry.jittered_backoff(**retry_params)
439 def create_api(client, name, description=None, endpoint_type=None, tags=None):
440 params = {"name": name}
441 if description:
442 params["description"] = description
443 if endpoint_type:
444 params["endpointConfiguration"] = {"types": [endpoint_type]}
445 if tags:
446 params["tags"] = tags
447 return client.create_rest_api(**params)
448
449
450 @AWSRetry.jittered_backoff(**retry_params)
451 def delete_api(client, api_id):
452 return client.delete_rest_api(restApiId=api_id)
453
454
455 @AWSRetry.jittered_backoff(**retry_params)
456 def configure_api(client, api_id, api_data=None, mode="overwrite"):
457 return client.put_rest_api(restApiId=api_id, mode=mode, body=api_data)
458
459
460 @AWSRetry.jittered_backoff(**retry_params)
461 def create_deployment(client, rest_api_id, **params):
462 canary_settings = params.get("stage_canary_settings")
463
464 if canary_settings and len(canary_settings) > 0:
465 result = client.create_deployment(
466 restApiId=rest_api_id,
467 stageName=params.get("stage"),
468 description=params.get("deploy_desc"),
469 cacheClusterEnabled=params.get("cache_enabled"),
470 cacheClusterSize=params.get("cache_size"),
471 variables=params.get("stage_variables"),
472 canarySettings=canary_settings,
473 tracingEnabled=params.get("tracing_enabled"),
474 )
475 else:
476 result = client.create_deployment(
477 restApiId=rest_api_id,
478 stageName=params.get("stage"),
479 description=params.get("deploy_desc"),
480 cacheClusterEnabled=params.get("cache_enabled"),
481 cacheClusterSize=params.get("cache_size"),
482 variables=params.get("stage_variables"),
483 tracingEnabled=params.get("tracing_enabled"),
484 )
485
486 return result
487
488
489 @AWSRetry.jittered_backoff(**retry_params)
490 def list_apis(client):
491 paginator = client.get_paginator("get_rest_apis")
492 return paginator.paginate().build_full_result().get("items", [])
493
494
495 @AWSRetry.jittered_backoff(**retry_params)
496 def describe_api(client, module, rest_api_id):
497 try:
498 response = client.get_rest_api(restApiId=rest_api_id)
499 response.pop("ResponseMetadata")
500 except is_boto3_error_code("ResourceNotFoundException"):
501 response = {}
502 except (
503 botocore.exceptions.ClientError,
504 botocore.exceptions.BotoCoreError,
505 ) as e: # pylint: disable=duplicate-except
506 module.fail_json_aws(e, msg=f"Trying to get Rest API '{rest_api_id}'.")
507 return response
508
509
510 if __name__ == "__main__":
511 main()