Debian Codegraph @

ansible_collections/amazon/aws/plugins/module_utils/botocore.py

raw
1 # -*- coding: utf-8 -*-
2
3 # This code is part of Ansible, but is an independent component.
4 # This particular file snippet, and this file snippet only, is BSD licensed.
5 # Modules you write using this snippet, which is embedded dynamically by Ansible
6 # still belong to the author of the module, and may assign their own license
7 # to the complete work.
8 #
9 # Copyright (c), Michael DeHaan <[email protected]>, 2012-2013
10 # All rights reserved.
11 #
12 # Redistribution and use in source and binary forms, with or without modification,
13 # are permitted provided that the following conditions are met:
14 #
15 # * Redistributions of source code must retain the above copyright
16 # notice, this list of conditions and the following disclaimer.
17 # * Redistributions in binary form must reproduce the above copyright notice,
18 # this list of conditions and the following disclaimer in the documentation
19 # and/or other materials provided with the distribution.
20 #
21 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
22 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
29 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 """
32 A set of helper functions designed to help with initializing boto3/botocore
33 connections.
34 """
35
36 from __future__ import annotations
37
38 import json
39 import os
40 import sys
41 import traceback
42 import typing
43 from typing import Any
44 from typing import Callable
45 from typing import Dict
46 from typing import List
47 from typing import Optional
48 from typing import Set
49 from typing import Tuple
50 from typing import Type
51 from typing import Union
52
53 BOTO3_IMP_ERR = None
54 try:
55 import boto3
56 import botocore
57 from botocore.exceptions import ClientError
58
59 HAS_BOTO3 = True
60 except ImportError:
61 BOTO3_IMP_ERR = traceback.format_exc()
62 HAS_BOTO3 = False
63
64 if typing.TYPE_CHECKING:
65 from typing_extensions import TypeAlias
66
67 from .retries import RetryingBotoClientWrapper
68
69 ClientType: TypeAlias = Union[botocore.client.BaseClient, RetryingBotoClientWrapper]
70 ResourceType: TypeAlias = boto3.resources.base.ServiceResource
71 BotoConn = Union[ClientType, ResourceType, Tuple[ClientType, ResourceType]]
72 from .modules import AnsibleAWSModule
73
74 try:
75 from packaging.version import Version
76
77 HAS_PACKAGING = True
78 except ImportError:
79 HAS_PACKAGING = False
80
81 from ansible.module_utils.ansible_release import __version__
82 from ansible.module_utils.basic import missing_required_lib
83 from ansible.module_utils.common.text.converters import to_native
84
85 from .common import get_collection_info
86 from .exceptions import AnsibleBotocoreError
87 from .retries import AWSRetry
88
89 MINIMUM_BOTOCORE_VERSION = "1.35.0"
90 MINIMUM_BOTO3_VERSION = "1.35.0"
91
92
93 def _get_user_agent_string():
94 info = get_collection_info()
95 result = f"APN/1.0 Ansible/{__version__}"
96 if info["name"]:
97 if info["version"] is not None:
98 result += f" {info['name']}/{info['version']}"
99 else:
100 result += f" {info['name']}"
101 return result
102
103
104 def boto3_conn(
105 module: AnsibleAWSModule,
106 conn_type: str,
107 resource: Optional[str] = None,
108 region: Optional[str] = None,
109 endpoint: Optional[str] = None,
110 **params,
111 ) -> BotoConn:
112 """
113 Builds a boto3 resource/client connection cleanly wrapping the most common failures.
114 Handles:
115 ValueError, botocore.exceptions.BotoCoreError
116 """
117 try:
118 return _boto3_conn(conn_type=conn_type, resource=resource, region=region, endpoint=endpoint, **params)
119 except botocore.exceptions.NoRegionError:
120 module.fail_json(
121 # pylint: disable-next=protected-access
122 msg=f"The {module._name} module requires a region and none was found in configuration, "
123 "environment variables or module parameters",
124 )
125 except (ValueError, botocore.exceptions.BotoCoreError) as e:
126 if hasattr(module, "fail_json_aws"):
127 module.fail_json_aws(e, msg="Couldn't connect to AWS")
128 module.fail_json(msg=f"Couldn't connect to AWS: {to_native(e)}")
129
130
131 def _merge_botocore_config(
132 config_a: botocore.config.Config,
133 config_b: Union[botocore.config.Config, Dict],
134 ) -> botocore.config.Config:
135 """
136 Merges the extra configuration options from config_b into config_a.
137 Supports both botocore.config.Config objects and dicts
138 """
139 if not config_b:
140 return config_a
141 if not isinstance(config_b, botocore.config.Config):
142 config_b = botocore.config.Config(**config_b)
143 return config_a.merge(config_b)
144
145
146 def _boto3_conn(
147 conn_type: str,
148 resource: Optional[str] = None,
149 region: Optional[str] = None,
150 endpoint: Optional[str] = None,
151 **params,
152 ) -> BotoConn:
153 """
154 Builds a boto3 resource/client connection cleanly wrapping the most common failures.
155 No exceptions are caught/handled.
156 """
157 profile = params.pop("profile_name", None)
158
159 if conn_type not in ["both", "resource", "client"]:
160 raise ValueError(
161 "There is an issue in the calling code. You "
162 "must specify either both, resource, or client to "
163 "the conn_type parameter in the boto3_conn function "
164 "call"
165 )
166
167 # default config with user agent
168 config = botocore.config.Config(
169 user_agent=_get_user_agent_string(),
170 )
171
172 for param in ("config", "aws_config"):
173 config = _merge_botocore_config(config, params.pop(param, None))
174
175 session = boto3.session.Session(
176 profile_name=profile,
177 )
178
179 enable_placebo(session)
180
181 if conn_type == "resource":
182 return session.resource(resource, config=config, region_name=region, endpoint_url=endpoint, **params)
183 elif conn_type == "client":
184 return session.client(resource, config=config, region_name=region, endpoint_url=endpoint, **params)
185 else:
186 client = session.client(resource, config=config, region_name=region, endpoint_url=endpoint, **params)
187 boto3_resource = session.resource(resource, config=config, region_name=region, endpoint_url=endpoint, **params)
188 return client, boto3_resource
189
190
191 # Inventory plugins don't have access to the same 'module', they need to throw
192 # an exception rather than calling module.fail_json
193 boto3_inventory_conn = _boto3_conn
194
195
196 def boto_exception(err: Exception) -> str:
197 """
198 Extracts the error message from a boto exception.
199
200 :param err: Exception from boto
201 :return: Error message
202 """
203 if hasattr(err, "error_message"):
204 error = err.error_message # pyright: ignore[reportAttributeAccessIssue]
205 elif hasattr(err, "message"):
206 error = (
207 str(err.message) + " " + str(err) + " - " + str(type(err)) # pyright: ignore[reportAttributeAccessIssue]
208 )
209 else:
210 error = f"{Exception}: {err}"
211
212 return error
213
214
215 def _aws_region(params: Dict) -> Optional[str]:
216 region = params.get("region")
217
218 if region:
219 return region
220
221 if not HAS_BOTO3:
222 raise AnsibleBotocoreError(message=missing_required_lib("boto3 and botocore"), exception=BOTO3_IMP_ERR)
223
224 # here we don't need to make an additional call, will default to 'us-east-1' if the below evaluates to None.
225 try:
226 # Botocore doesn't like empty strings, make sure we default to None in the case of an empty
227 # string.
228 profile_name = params.get("profile") or None
229 return boto3.session.Session(profile_name=profile_name).region_name
230 except botocore.exceptions.BotoCoreError:
231 return None
232
233
234 def get_aws_region(
235 module: AnsibleAWSModule,
236 ) -> Optional[str]:
237 try:
238 return _aws_region(module.params)
239 except AnsibleBotocoreError as e:
240 if e.exception:
241 module.fail_json(msg=e.message, exception=e.exception)
242 else:
243 module.fail_json(msg=e.message)
244
245
246 def _aws_connection_info(params: Dict) -> Tuple[Optional[str], Optional[str], Dict[str, Any]]:
247 endpoint_url = params.get("endpoint_url")
248 access_key = params.get("access_key")
249 secret_key = params.get("secret_key")
250 session_token = params.get("session_token")
251 region = _aws_region(params)
252 profile_name = params.get("profile")
253 validate_certs = params.get("validate_certs")
254 ca_bundle = params.get("aws_ca_bundle")
255 config = params.get("aws_config")
256
257 # Caught here so that they can be deliberately set to '' to avoid conflicts when environment
258 # variables are also being used
259 if profile_name and (access_key or secret_key or session_token):
260 raise AnsibleBotocoreError(message="Passing both a profile and access tokens is not supported.")
261
262 # Botocore doesn't like empty strings, make sure we default to None in the case of an empty
263 # string.
264 if not access_key:
265 access_key = None
266 if not secret_key:
267 secret_key = None
268 if not session_token:
269 session_token = None
270
271 if profile_name:
272 boto_params = dict(
273 aws_access_key_id=None,
274 aws_secret_access_key=None,
275 aws_session_token=None,
276 profile_name=profile_name,
277 )
278 else:
279 boto_params = dict(
280 aws_access_key_id=access_key,
281 aws_secret_access_key=secret_key,
282 aws_session_token=session_token,
283 )
284
285 if validate_certs and ca_bundle:
286 boto_params["verify"] = ca_bundle
287 else:
288 boto_params["verify"] = validate_certs
289
290 if config is not None:
291 boto_params["aws_config"] = botocore.config.Config(**config)
292
293 for param, value in boto_params.items():
294 if isinstance(value, bytes):
295 boto_params[param] = str(value, "utf-8", "strict")
296
297 return region, endpoint_url, boto_params
298
299
300 def get_aws_connection_info(
301 module: AnsibleAWSModule,
302 ) -> Tuple[Optional[str], Optional[str], Dict]:
303 try:
304 return _aws_connection_info(module.params)
305 except AnsibleBotocoreError as e:
306 if e.exception:
307 module.fail_json(msg=e.message, exception=e.exception)
308 else:
309 module.fail_json(msg=e.message)
310
311
312 def _paginated_query(
313 client: ClientType,
314 paginator_name: str,
315 **params,
316 ) -> Any:
317 paginator = client.get_paginator(paginator_name)
318 result = paginator.paginate(**params).build_full_result()
319 return result
320
321
322 def paginated_query_with_retries(
323 client: ClientType,
324 paginator_name: str,
325 retry_decorator=None,
326 **params,
327 ) -> Any:
328 """
329 Performs a boto3 paginated query.
330 By default uses uses AWSRetry.jittered_backoff(retries=10) to retry queries
331 with temporary failures.
332
333 Examples:
334 tags = paginated_query_with_retries(client, "describe_tags", Filters=[])
335
336 decorator = AWSRetry.backoff(tries=5, delay=5, backoff=2.0,
337 catch_extra_error_codes=['RequestInProgressException'])
338 certificates = paginated_query_with_retries(client, "list_certificates", decorator)
339 """
340 if retry_decorator is None:
341 retry_decorator = AWSRetry.jittered_backoff(retries=10)
342 result = retry_decorator(_paginated_query)(client, paginator_name, **params)
343 return result
344
345
346 def gather_sdk_versions() -> Dict:
347 """Gather AWS SDK (boto3 and botocore) dependency versions
348
349 Returns {'boto3_version': str, 'botocore_version': str}
350 Returns {} if either module is not installed
351 """
352 if not HAS_BOTO3:
353 return {}
354
355 return dict(
356 boto3_version=boto3.__version__,
357 botocore_version=botocore.__version__,
358 )
359
360
361 def is_boto3_error_code(
362 code: Union[List, Tuple, Set, str],
363 e: Optional[BaseException] = None,
364 ) -> Type[Exception]:
365 """Check if the botocore exception is raised by a specific error code.
366
367 Returns ClientError if the error code matches, a dummy exception if it does not have an error code or does not match
368
369 Example:
370 try:
371 ec2.describe_instances(InstanceIds=['potato'])
372 except is_boto3_error_code('InvalidInstanceID.Malformed'):
373 # handle the error for that code case
374 except botocore.exceptions.ClientError as e:
375 # handle the generic error case for all other codes
376 """
377 if e is None:
378 e = sys.exc_info()[1]
379 if not isinstance(code, (list, tuple, set)):
380 code = [code]
381 try:
382 if isinstance(e, ClientError) and e.response["Error"]["Code"] in code:
383 return ClientError
384 except KeyError:
385 pass
386 return type("NeverEverRaisedException", (Exception,), {})
387
388
389 def is_boto3_error_httpstatus(
390 status: Union[List, Tuple, Set, int],
391 e: Optional[BaseException] = None,
392 ) -> Type[Exception]:
393 """Check if the botocore exception is raised by a specific HTTP status code.
394
395 Returns ClientError if the HTTP status code matches, a dummy exception if it does not have a status code or does not match
396
397 Example:
398 try:
399 ec2.describe_instances(InstanceIds=['potato'])
400 except is_boto3_error_httpstatus(501):
401 # handle the error for that status code case
402 except botocore.exceptions.ClientError as e:
403 # handle the generic error case for all other status codes
404 """
405 if e is None:
406 e = sys.exc_info()[1]
407 if not isinstance(status, (list, tuple, set)):
408 status = [status]
409 try:
410 if isinstance(e, ClientError) and e.response["ResponseMetadata"]["HTTPStatusCode"] in status:
411 return ClientError
412 except KeyError:
413 pass
414 return type("NeverEverRaisedException", (Exception,), {})
415
416
417 def is_boto3_error_message(
418 msg: str,
419 e: Optional[BaseException] = None,
420 ) -> Type[Exception]:
421 """Check if the botocore exception contains a specific error message.
422
423 Returns ClientError if the error code matches, a dummy exception if it does not have an error code or does not match
424
425 Example:
426 try:
427 ec2.describe_vpc_classic_link(VpcIds=[vpc_id])
428 except is_boto3_error_message('The functionality you requested is not available in this region.'):
429 # handle the error for that error message
430 except botocore.exceptions.ClientError as e:
431 # handle the generic error case for all other codes
432 """
433
434 if e is None:
435 e = sys.exc_info()[1]
436 try:
437 if isinstance(e, ClientError) and msg in e.response["Error"]["Message"]:
438 return ClientError
439 except KeyError:
440 pass
441 return type("NeverEverRaisedException", (Exception,), {})
442
443
444 def get_boto3_client_method_parameters(
445 client: ClientType,
446 method_name: str,
447 required=False,
448 ) -> List:
449 op = client.meta.method_to_api_mapping.get(method_name)
450 input_shape = client._service_model.operation_model(op).input_shape # pylint: disable=protected-access
451 if not input_shape:
452 parameters = []
453 elif required:
454 parameters = list(input_shape.required_members)
455 else:
456 parameters = list(input_shape.members.keys())
457 return parameters
458
459
460 # Used by normalize_boto3_result
461 def _boto3_handler(obj: Any) -> Any:
462 if hasattr(obj, "isoformat"):
463 return obj.isoformat()
464 else:
465 return obj
466
467
468 def normalize_boto3_result(
469 result: Union[List, Dict, Set],
470 ) -> Union[List, Dict, Set]:
471 """
472 Because Boto3 returns datetime objects where it knows things are supposed to
473 be dates we need to mass-convert them over to strings which Ansible/Jinja
474 handle better. This also makes it easier to compare complex objects which
475 include a mix of dates in string format (from parameters) and dates as
476 datetime objects. Boto3 is happy to be passed ISO8601 format strings.
477 """
478 return json.loads(json.dumps(result, default=_boto3_handler))
479
480
481 def enable_placebo(session: boto3.session.Session) -> None:
482 """
483 Helper to record or replay offline modules for testing purpose.
484 """
485 # pylint: disable=import-outside-toplevel
486 if "_ANSIBLE_PLACEBO_RECORD" in os.environ:
487 import placebo
488
489 recorded_entries = os.listdir(os.environ["_ANSIBLE_PLACEBO_RECORD"])
490 data_path = f"{os.environ['_ANSIBLE_PLACEBO_RECORD']}/{len(recorded_entries)}"
491 os.mkdir(data_path)
492 pill = placebo.attach(session, data_path=data_path)
493 pill.record()
494 if "_ANSIBLE_PLACEBO_REPLAY" in os.environ:
495 import shutil
496
497 import placebo
498
499 replay_entries = sorted([int(i) for i in os.listdir(os.environ["_ANSIBLE_PLACEBO_REPLAY"])])
500 data_path = f"{os.environ['_ANSIBLE_PLACEBO_REPLAY']}/{replay_entries[0]}"
501 try:
502 shutil.rmtree("_tmp")
503 except FileNotFoundError:
504 pass
505 shutil.move(data_path, "_tmp")
506 if len(replay_entries) == 1:
507 os.rmdir(os.environ["_ANSIBLE_PLACEBO_REPLAY"])
508 pill = placebo.attach(session, data_path="_tmp")
509 pill.playback()
510 # pylint: enable=import-outside-toplevel
511
512
513 def check_sdk_version_supported(
514 botocore_version: Optional[str] = None,
515 boto3_version: Optional[str] = None,
516 warn: Optional[Callable] = None,
517 ) -> bool:
518 """Checks to see if the available boto3 / botocore versions are supported
519 args:
520 botocore_version: (str) overrides the minimum version of botocore supported by the collection
521 boto3_version: (str) overrides the minimum version of boto3 supported by the collection
522 warn: (Callable) invoked with a string message if boto3/botocore are less than the
523 supported versions
524 raises:
525 AnsibleBotocoreError - If botocore/boto3 is missing
526 returns
527 False if boto3 or botocore is less than the minimum supported versions
528 True if boto3 and botocore are greater than or equal the the minimum supported versions
529 """
530
531 botocore_version = botocore_version or MINIMUM_BOTOCORE_VERSION
532 boto3_version = boto3_version or MINIMUM_BOTO3_VERSION
533
534 if not HAS_BOTO3:
535 raise AnsibleBotocoreError(message=missing_required_lib("botocore and boto3"))
536
537 supported = True
538
539 if not HAS_PACKAGING:
540 if warn:
541 warn("packaging.version Python module not installed, unable to check AWS SDK versions")
542 return True
543 if not botocore_at_least(botocore_version):
544 supported = False
545 if warn:
546 warn(f"botocore < {MINIMUM_BOTOCORE_VERSION} is not supported or tested. Some features may not work.")
547 if not boto3_at_least(boto3_version):
548 supported = False
549 if warn:
550 warn(f"boto3 < {MINIMUM_BOTO3_VERSION} is not supported or tested. Some features may not work.")
551
552 return supported
553
554
555 def _version_at_least(a: str, b: str) -> bool:
556 if not HAS_PACKAGING:
557 return True
558 return Version(a) >= Version(b)
559
560
561 def boto3_at_least(desired: str) -> bool:
562 """Check if the available boto3 version is greater than or equal to a desired version.
563
564 Usage:
565 if module.params.get('assign_ipv6_address') and not module.boto3_at_least('1.4.4'):
566 # conditionally fail on old boto3 versions if a specific feature is not supported
567 module.fail_json(msg="Boto3 can't deal with EC2 IPv6 addresses before version 1.4.4.")
568 """
569 existing = gather_sdk_versions()
570 return _version_at_least(existing["boto3_version"], desired)
571
572
573 def botocore_at_least(desired: str) -> bool:
574 """Check if the available botocore version is greater than or equal to a desired version.
575
576 Usage:
577 if not module.botocore_at_least('1.2.3'):
578 module.fail_json(msg='The Serverless Elastic Load Compute Service is not in botocore before v1.2.3')
579 if not module.botocore_at_least('1.5.3'):
580 module.warn('Botocore did not include waiters for Service X before 1.5.3. '
581 'To wait until Service X resources are fully available, update botocore.')
582 """
583 existing = gather_sdk_versions()
584 return _version_at_least(existing["botocore_version"], desired)