Debian Codegraph @

ansible_collections/amazon/aws/plugins/plugin_utils/base.py

raw
1 # -*- coding: utf-8 -*-
2
3 # (c) 2022 Red Hat Inc.
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from typing import NoReturn
7 from typing import Optional
8
9 from ansible.errors import AnsibleError
10 from ansible.module_utils.basic import to_native
11 from ansible.utils.display import Display
12
13 from ansible_collections.amazon.aws.plugins.module_utils.botocore import check_sdk_version_supported
14 from ansible_collections.amazon.aws.plugins.module_utils.retries import RetryingBotoClientWrapper
15 from ansible_collections.amazon.aws.plugins.plugin_utils.botocore import boto3_conn
16 from ansible_collections.amazon.aws.plugins.plugin_utils.botocore import get_aws_connection_info
17 from ansible_collections.amazon.aws.plugins.plugin_utils.botocore import get_aws_region
18
19 display = Display()
20
21
22 class AWSPluginBase:
23 def warn(self, message: str):
24 display.warning(message)
25
26 def debug(self, message: str):
27 display.debug(message)
28
29 # Should be overridden with the plugin-type specific exception
30 def _do_fail(self, message: str) -> NoReturn:
31 raise AnsibleError(message)
32
33 # We don't know what the correct exception is to raise, so the actual "raise" is handled by
34 # _do_fail()
35 def fail_aws(self, message: str, exception: Optional[Exception] = None) -> NoReturn:
36 if not exception:
37 self._do_fail(to_native(message))
38 self._do_fail(f"{message}: {to_native(exception)}")
39
40 def client(self, service: str, retry_decorator=None, **extra_params):
41 region, endpoint_url, aws_connect_kwargs = get_aws_connection_info(self)
42 kw_args = dict(region=region, endpoint=endpoint_url, **aws_connect_kwargs)
43 kw_args.update(extra_params)
44 conn = boto3_conn(self, conn_type="client", resource=service, **kw_args)
45 return conn if retry_decorator is None else RetryingBotoClientWrapper(conn, retry_decorator)
46
47 def resource(self, service, **extra_params):
48 region, endpoint_url, aws_connect_kwargs = get_aws_connection_info(self)
49 kw_args = dict(region=region, endpoint=endpoint_url, **aws_connect_kwargs)
50 kw_args.update(extra_params)
51 return boto3_conn(self, conn_type="resource", resource=service, **kw_args)
52
53 @property
54 def region(self) -> Optional[str]:
55 return get_aws_region(self)
56
57 def require_aws_sdk(self, botocore_version: Optional[str] = None, boto3_version: Optional[str] = None) -> bool:
58 return check_sdk_version_supported(
59 botocore_version=botocore_version, boto3_version=boto3_version, warn=self.warn
60 )