| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright 2017 Michael De La Rue | Ansible |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
"""This module adds shared support for generic Amazon AWS modules |
| 7 |
|
| 8 |
In order to use this module, include it as part of a custom |
| 9 |
module as shown below. |
| 10 |
|
| 11 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 12 |
module = AnsibleAWSModule(argument_spec=dictionary, supports_check_mode=boolean |
| 13 |
mutually_exclusive=list1, required_together=list2) |
| 14 |
|
| 15 |
The 'AnsibleAWSModule' module provides similar, but more restricted, |
| 16 |
interfaces to the normal Ansible module. It also includes the |
| 17 |
additional methods for connecting to AWS using the standard module arguments |
| 18 |
|
| 19 |
m.resource('lambda') # - get an AWS connection as a boto3 resource. |
| 20 |
|
| 21 |
or |
| 22 |
|
| 23 |
m.client('sts') # - get an AWS connection as a boto3 client. |
| 24 |
|
| 25 |
To make use of AWSRetry easier, it can now be wrapped around any call from a |
| 26 |
module-created client. To add retries to a client, create a client: |
| 27 |
|
| 28 |
m.client('ec2', retry_decorator=AWSRetry.jittered_backoff(retries=10)) |
| 29 |
|
| 30 |
Any calls from that client can be made to use the decorator passed at call-time |
| 31 |
using the `aws_retry` argument. By default, no retries are used. |
| 32 |
|
| 33 |
ec2 = m.client('ec2', retry_decorator=AWSRetry.jittered_backoff(retries=10)) |
| 34 |
ec2.describe_instances(InstanceIds=['i-123456789'], aws_retry=True) |
| 35 |
|
| 36 |
The call will be retried the specified number of times, so the calling functions |
| 37 |
don't need to be wrapped in the backoff decorator. |
| 38 |
""" |
| 39 |
|
| 40 |
import logging |
| 41 |
import re |
| 42 |
import traceback |
| 43 |
from io import StringIO |
| 44 |
from typing import Any |
| 45 |
from typing import Dict |
| 46 |
from typing import NoReturn |
| 47 |
from typing import Optional |
| 48 |
|
| 49 |
from ansible.module_utils.ansible_release import __version__ as _ANSIBLE_CORE_VERSION |
| 50 |
from ansible.module_utils.basic import AnsibleModule |
| 51 |
from ansible.module_utils.basic import env_fallback |
| 52 |
from ansible.module_utils.basic import missing_required_lib |
| 53 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 54 |
from ansible.module_utils.common.text.converters import to_native |
| 55 |
|
| 56 |
from .botocore import boto3_at_least |
| 57 |
from .botocore import boto3_conn |
| 58 |
from .botocore import botocore_at_least |
| 59 |
from .botocore import check_sdk_version_supported |
| 60 |
from .botocore import gather_sdk_versions |
| 61 |
from .botocore import get_aws_connection_info |
| 62 |
from .botocore import get_aws_region |
| 63 |
from .exceptions import AnsibleBotocoreError |
| 64 |
from .retries import RetryingBotoClientWrapper |
| 65 |
|
| 66 |
# Currently only AnsibleAWSModule. However we have a lot of Copy and Paste code |
| 67 |
# for Inventory and Lookup modules which we should refactor |
| 68 |
|
| 69 |
|
| 70 |
class AnsibleAWSModule: |
| 71 |
"""An ansible module class for AWS modules |
| 72 |
|
| 73 |
AnsibleAWSModule provides an a class for building modules which |
| 74 |
connect to Amazon Web Services. The interface is currently more |
| 75 |
restricted than the basic module class with the aim that later the |
| 76 |
basic module class can be reduced. If you find that any key |
| 77 |
feature is missing please contact the author/Ansible AWS team |
| 78 |
(available on #ansible-aws on IRC) to request the additional |
| 79 |
features needed. |
| 80 |
""" |
| 81 |
|
| 82 |
default_settings = {"default_args": True, "check_boto3": True, "auto_retry": True, "module_class": AnsibleModule} |
| 83 |
|
| 84 |
def __init__(self, **kwargs): |
| 85 |
local_settings = {} |
| 86 |
for key, default_value in AnsibleAWSModule.default_settings.items(): |
| 87 |
try: |
| 88 |
local_settings[key] = kwargs.pop(key) |
| 89 |
except KeyError: |
| 90 |
local_settings[key] = default_value |
| 91 |
self.settings = local_settings |
| 92 |
|
| 93 |
if local_settings["default_args"]: |
| 94 |
argument_spec_full = aws_argument_spec() |
| 95 |
try: |
| 96 |
argument_spec_full.update(kwargs["argument_spec"]) |
| 97 |
except (TypeError, NameError): |
| 98 |
pass |
| 99 |
kwargs["argument_spec"] = argument_spec_full |
| 100 |
|
| 101 |
self._module = AnsibleAWSModule.default_settings["module_class"](**kwargs) |
| 102 |
# Initialize warnings buffer early, before any code invokes self.warn() |
| 103 |
self._warnings = [] |
| 104 |
|
| 105 |
if local_settings["check_boto3"]: |
| 106 |
try: |
| 107 |
check_sdk_version_supported(warn=self.warn) |
| 108 |
except AnsibleBotocoreError as e: |
| 109 |
self._module.fail_json(to_native(e)) |
| 110 |
|
| 111 |
self.check_mode = self._module.check_mode |
| 112 |
self._diff = self._module._diff |
| 113 |
self._name = self._module._name |
| 114 |
|
| 115 |
self._botocore_endpoint_log_stream = StringIO() |
| 116 |
self.logger = None |
| 117 |
if self.params.get("debug_botocore_endpoint_logs"): |
| 118 |
self.logger = logging.getLogger("botocore.endpoint") |
| 119 |
self.logger.setLevel(logging.DEBUG) |
| 120 |
self.logger.addHandler(logging.StreamHandler(self._botocore_endpoint_log_stream)) |
| 121 |
|
| 122 |
def _should_inject_warnings(self) -> bool: |
| 123 |
# Inject warnings into the JSON result for ansible-core versions that |
| 124 |
# do not include them automatically (>=2.19 based on CI behavior). |
| 125 |
try: |
| 126 |
parts = [int(p) for p in _ANSIBLE_CORE_VERSION.split(".")[:2]] |
| 127 |
major, minor = (parts + [0, 0])[:2] |
| 128 |
return (major, minor) >= (2, 19) |
| 129 |
except Exception: |
| 130 |
return False |
| 131 |
|
| 132 |
@property |
| 133 |
def params(self) -> Dict[str, Any]: |
| 134 |
return self._module.params |
| 135 |
|
| 136 |
def _get_resource_action_list(self): |
| 137 |
actions = [] |
| 138 |
for ln in self._botocore_endpoint_log_stream.getvalue().split("\n"): |
| 139 |
ln = ln.strip() |
| 140 |
if not ln: |
| 141 |
continue |
| 142 |
try: |
| 143 |
found_operational_request = re.search(r"OperationModel\(name=.*?\)", ln) |
| 144 |
operation_request = found_operational_request.group(0)[ # pyright: ignore[reportOptionalMemberAccess] |
| 145 |
20:-1 |
| 146 |
] |
| 147 |
resource = re.search(r"https://.*?\.", ln).group(0)[8:-1] # pyright: ignore[reportOptionalMemberAccess] |
| 148 |
actions.append(f"{resource}:{operation_request}") |
| 149 |
except AttributeError: |
| 150 |
pass |
| 151 |
return list(set(actions)) |
| 152 |
|
| 153 |
def exit_json(self, *args, **kwargs) -> NoReturn: |
| 154 |
if self.params.get("debug_botocore_endpoint_logs"): |
| 155 |
kwargs["resource_actions"] = self._get_resource_action_list() |
| 156 |
if self._should_inject_warnings() and getattr(self, "_warnings", None) and "warnings" not in kwargs: |
| 157 |
kwargs["warnings"] = list(dict.fromkeys(self._warnings)) |
| 158 |
self._module.exit_json(*args, **kwargs) |
| 159 |
|
| 160 |
def fail_json(self, *args, **kwargs) -> NoReturn: |
| 161 |
if self.params.get("debug_botocore_endpoint_logs"): |
| 162 |
kwargs["resource_actions"] = self._get_resource_action_list() |
| 163 |
if self._should_inject_warnings() and getattr(self, "_warnings", None) and "warnings" not in kwargs: |
| 164 |
kwargs["warnings"] = list(dict.fromkeys(self._warnings)) |
| 165 |
self._module.fail_json(*args, **kwargs) |
| 166 |
|
| 167 |
def debug(self, *args, **kwargs) -> None: |
| 168 |
return self._module.debug(*args, **kwargs) |
| 169 |
|
| 170 |
def warn(self, *args, **kwargs) -> None: |
| 171 |
# Record warnings so unit tests can assert on them and include in JSON result |
| 172 |
if args and isinstance(args[0], str): |
| 173 |
if not hasattr(self, "_warnings"): |
| 174 |
self._warnings = [] |
| 175 |
self._warnings.append(args[0]) |
| 176 |
# Forward to underlying AnsibleModule.warn to emit warnings |
| 177 |
return self._module.warn(*args, **kwargs) |
| 178 |
|
| 179 |
def __getattr__(self, attr): |
| 180 |
if hasattr(self._module, attr): |
| 181 |
return getattr(self._module, attr) |
| 182 |
raise AttributeError(f"AnsibleAWSModule has no attribute '{attr}'") |
| 183 |
|
| 184 |
def boolean(self, *args, **kwargs) -> bool: |
| 185 |
return self._module.boolean(*args, **kwargs) |
| 186 |
|
| 187 |
def md5(self, *args, **kwargs) -> str: |
| 188 |
return self._module.md5(*args, **kwargs) |
| 189 |
|
| 190 |
def client(self, service: str, retry_decorator=None, **extra_params): |
| 191 |
region, endpoint_url, aws_connect_kwargs = get_aws_connection_info(self) |
| 192 |
kw_args = dict(region=region, endpoint=endpoint_url, **aws_connect_kwargs) |
| 193 |
kw_args.update(extra_params) |
| 194 |
conn = boto3_conn(self, conn_type="client", resource=service, **kw_args) |
| 195 |
return conn if retry_decorator is None else RetryingBotoClientWrapper(conn, retry_decorator) |
| 196 |
|
| 197 |
def resource(self, service: str, **extra_params): |
| 198 |
region, endpoint_url, aws_connect_kwargs = get_aws_connection_info(self) |
| 199 |
kw_args = dict(region=region, endpoint=endpoint_url, **aws_connect_kwargs) |
| 200 |
kw_args.update(extra_params) |
| 201 |
return boto3_conn(self, conn_type="resource", resource=service, **kw_args) |
| 202 |
|
| 203 |
@property |
| 204 |
def region(self) -> Optional[str]: |
| 205 |
return get_aws_region(self) |
| 206 |
|
| 207 |
def fail_json_aws(self, exception: BaseException, msg: Optional[str] = None, **kwargs) -> NoReturn: |
| 208 |
"""call fail_json with processed exception |
| 209 |
|
| 210 |
function for converting exceptions thrown by AWS SDK modules, |
| 211 |
botocore, boto3 and boto, into nice error messages. |
| 212 |
""" |
| 213 |
last_traceback = traceback.format_exc() |
| 214 |
|
| 215 |
# to_native is trusted to handle exceptions that str() could |
| 216 |
# convert to text. |
| 217 |
try: |
| 218 |
except_msg = to_native(exception.message) # pyright: ignore[reportAttributeAccessIssue] |
| 219 |
except AttributeError: |
| 220 |
except_msg = to_native(exception) |
| 221 |
|
| 222 |
if msg is not None: |
| 223 |
message = f"{msg}: {except_msg}" |
| 224 |
else: |
| 225 |
message = except_msg |
| 226 |
|
| 227 |
try: |
| 228 |
response = exception.response # pyright: ignore[reportAttributeAccessIssue] |
| 229 |
except AttributeError: |
| 230 |
response = None |
| 231 |
|
| 232 |
failure = dict(msg=message, exception=last_traceback, **self._gather_versions()) |
| 233 |
|
| 234 |
failure.update(kwargs) |
| 235 |
|
| 236 |
if response is not None: |
| 237 |
failure.update(**camel_dict_to_snake_dict(response)) |
| 238 |
|
| 239 |
self.fail_json(**failure) |
| 240 |
|
| 241 |
def fail_json_aws_error(self, exception) -> NoReturn: |
| 242 |
"""A helper to call the right failure mode after catching an AnsibleAWSError""" |
| 243 |
if exception.exception: |
| 244 |
self.fail_json_aws(exception.exception, msg=exception.message) |
| 245 |
self.fail_json(msg=exception.message) |
| 246 |
|
| 247 |
def _gather_versions(self) -> Dict[str, Any]: |
| 248 |
"""Gather AWS SDK (boto3 and botocore) dependency versions |
| 249 |
|
| 250 |
Returns {'boto3_version': str, 'botocore_version': str} |
| 251 |
Returns {} if either is not installed |
| 252 |
""" |
| 253 |
return gather_sdk_versions() |
| 254 |
|
| 255 |
def require_boto3_at_least(self, desired: str, **kwargs) -> None: |
| 256 |
"""Check if the available boto3 version is greater than or equal to a desired version. |
| 257 |
|
| 258 |
calls fail_json() when the boto3 version is less than the desired |
| 259 |
version |
| 260 |
|
| 261 |
Usage: |
| 262 |
module.require_boto3_at_least("1.2.3", reason="to update tags") |
| 263 |
module.require_boto3_at_least("1.1.1") |
| 264 |
|
| 265 |
:param desired the minimum desired version |
| 266 |
:param reason why the version is required (optional) |
| 267 |
""" |
| 268 |
if not self.boto3_at_least(desired): |
| 269 |
self._module.fail_json( |
| 270 |
msg=missing_required_lib(f"boto3>={desired}", **kwargs), |
| 271 |
**self._gather_versions(), |
| 272 |
) |
| 273 |
|
| 274 |
def boto3_at_least(self, desired: str) -> bool: |
| 275 |
return boto3_at_least(desired) |
| 276 |
|
| 277 |
def require_botocore_at_least(self, desired: str, **kwargs) -> None: |
| 278 |
"""Check if the available botocore version is greater than or equal to a desired version. |
| 279 |
|
| 280 |
calls fail_json() when the botocore version is less than the desired |
| 281 |
version |
| 282 |
|
| 283 |
Usage: |
| 284 |
module.require_botocore_at_least("1.2.3", reason="to update tags") |
| 285 |
module.require_botocore_at_least("1.1.1") |
| 286 |
|
| 287 |
:param desired the minimum desired version |
| 288 |
:param reason why the version is required (optional) |
| 289 |
""" |
| 290 |
if not self.botocore_at_least(desired): |
| 291 |
self._module.fail_json( |
| 292 |
msg=missing_required_lib(f"botocore>={desired}", **kwargs), |
| 293 |
**self._gather_versions(), |
| 294 |
) |
| 295 |
|
| 296 |
def botocore_at_least(self, desired: str) -> bool: |
| 297 |
return botocore_at_least(desired) |
| 298 |
|
| 299 |
|
| 300 |
def _aws_common_argument_spec() -> Dict["str", Any]: |
| 301 |
""" |
| 302 |
This does not include 'region' as some AWS APIs don't require a |
| 303 |
region. However, it's not recommended to do this as it means module_defaults |
| 304 |
can't include the region parameter. |
| 305 |
""" |
| 306 |
return dict( |
| 307 |
access_key=dict( |
| 308 |
aliases=["aws_access_key_id", "aws_access_key"], |
| 309 |
fallback=(env_fallback, ["AWS_ACCESS_KEY_ID", "AWS_ACCESS_KEY"]), |
| 310 |
no_log=False, |
| 311 |
), |
| 312 |
secret_key=dict( |
| 313 |
aliases=["aws_secret_access_key", "aws_secret_key"], |
| 314 |
fallback=(env_fallback, ["AWS_SECRET_ACCESS_KEY", "AWS_SECRET_KEY"]), |
| 315 |
no_log=True, |
| 316 |
), |
| 317 |
session_token=dict( |
| 318 |
aliases=["aws_session_token"], |
| 319 |
fallback=(env_fallback, ["AWS_SESSION_TOKEN"]), |
| 320 |
no_log=True, |
| 321 |
), |
| 322 |
profile=dict( |
| 323 |
aliases=["aws_profile"], |
| 324 |
fallback=(env_fallback, ["AWS_PROFILE", "AWS_DEFAULT_PROFILE"]), |
| 325 |
), |
| 326 |
endpoint_url=dict( |
| 327 |
aliases=["aws_endpoint_url"], |
| 328 |
fallback=(env_fallback, ["AWS_URL"]), |
| 329 |
), |
| 330 |
validate_certs=dict( |
| 331 |
type="bool", |
| 332 |
default=True, |
| 333 |
), |
| 334 |
aws_ca_bundle=dict( |
| 335 |
type="path", |
| 336 |
fallback=(env_fallback, ["AWS_CA_BUNDLE"]), |
| 337 |
), |
| 338 |
aws_config=dict( |
| 339 |
type="dict", |
| 340 |
), |
| 341 |
debug_botocore_endpoint_logs=dict( |
| 342 |
type="bool", |
| 343 |
default=False, |
| 344 |
fallback=(env_fallback, ["ANSIBLE_DEBUG_BOTOCORE_LOGS"]), |
| 345 |
), |
| 346 |
) |
| 347 |
|
| 348 |
|
| 349 |
def aws_argument_spec() -> Dict["str", Any]: |
| 350 |
""" |
| 351 |
Returns a dictionary containing the argument_spec common to all AWS modules. |
| 352 |
""" |
| 353 |
region_spec = dict( |
| 354 |
region=dict( |
| 355 |
aliases=["aws_region"], |
| 356 |
fallback=(env_fallback, ["AWS_REGION", "AWS_DEFAULT_REGION"]), |
| 357 |
), |
| 358 |
) |
| 359 |
spec = _aws_common_argument_spec() |
| 360 |
spec.update(region_spec) |
| 361 |
return spec |