| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: (c) 2018, Ansible Project |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
from collections import namedtuple |
| 7 |
from time import sleep |
| 8 |
from typing import Any |
| 9 |
from typing import Dict |
| 10 |
from typing import List |
| 11 |
from typing import Optional |
| 12 |
from typing import Tuple |
| 13 |
|
| 14 |
try: |
| 15 |
from botocore.exceptions import BotoCoreError |
| 16 |
from botocore.exceptions import ClientError |
| 17 |
from botocore.exceptions import WaiterError |
| 18 |
except ImportError: |
| 19 |
pass |
| 20 |
|
| 21 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 22 |
from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict |
| 23 |
from ansible.module_utils.common.text.converters import to_text |
| 24 |
|
| 25 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import get_boto3_client_method_parameters |
| 26 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code |
| 27 |
from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule |
| 28 |
from ansible_collections.amazon.aws.plugins.module_utils.errors import AWSErrorHandler |
| 29 |
from ansible_collections.amazon.aws.plugins.module_utils.exceptions import AnsibleAWSError |
| 30 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 31 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list |
| 32 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict |
| 33 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags |
| 34 |
from ansible_collections.amazon.aws.plugins.module_utils.waiters import get_waiter |
| 35 |
|
| 36 |
Boto3ClientMethod = namedtuple( |
| 37 |
"Boto3ClientMethod", ["name", "waiter", "operation_description", "resource", "retry_codes"] |
| 38 |
) |
| 39 |
# Whitelist boto3 client methods for cluster and instance resources |
| 40 |
cluster_method_names = [ |
| 41 |
"create_db_cluster", |
| 42 |
"restore_db_cluster_from_snapshot", |
| 43 |
"restore_db_cluster_from_s3", |
| 44 |
"restore_db_cluster_to_point_in_time", |
| 45 |
"modify_db_cluster", |
| 46 |
"delete_db_cluster", |
| 47 |
"add_tags_to_resource", |
| 48 |
"remove_tags_from_resource", |
| 49 |
"list_tags_for_resource", |
| 50 |
"promote_read_replica_db_cluster", |
| 51 |
"stop_db_cluster", |
| 52 |
"start_db_cluster", |
| 53 |
] |
| 54 |
instance_method_names = [ |
| 55 |
"create_db_instance", |
| 56 |
"restore_db_instance_to_point_in_time", |
| 57 |
"restore_db_instance_from_s3", |
| 58 |
"restore_db_instance_from_db_snapshot", |
| 59 |
"create_db_instance_read_replica", |
| 60 |
"modify_db_instance", |
| 61 |
"delete_db_instance", |
| 62 |
"add_tags_to_resource", |
| 63 |
"remove_tags_from_resource", |
| 64 |
"list_tags_for_resource", |
| 65 |
"promote_read_replica", |
| 66 |
"stop_db_instance", |
| 67 |
"start_db_instance", |
| 68 |
"reboot_db_instance", |
| 69 |
"add_role_to_db_instance", |
| 70 |
"remove_role_from_db_instance", |
| 71 |
] |
| 72 |
|
| 73 |
cluster_snapshot_method_names = [ |
| 74 |
"create_db_cluster_snapshot", |
| 75 |
"delete_db_cluster_snapshot", |
| 76 |
"add_tags_to_resource", |
| 77 |
"remove_tags_from_resource", |
| 78 |
"list_tags_for_resource", |
| 79 |
"copy_db_cluster_snapshot", |
| 80 |
] |
| 81 |
|
| 82 |
instance_snapshot_method_names = [ |
| 83 |
"create_db_snapshot", |
| 84 |
"delete_db_snapshot", |
| 85 |
"add_tags_to_resource", |
| 86 |
"remove_tags_from_resource", |
| 87 |
"copy_db_snapshot", |
| 88 |
"list_tags_for_resource", |
| 89 |
] |
| 90 |
|
| 91 |
|
| 92 |
class AnsibleRDSError(AnsibleAWSError): |
| 93 |
pass |
| 94 |
|
| 95 |
|
| 96 |
class RDSErrorHandler(AWSErrorHandler): |
| 97 |
_CUSTOM_EXCEPTION = AnsibleRDSError |
| 98 |
|
| 99 |
@classmethod |
| 100 |
def _is_missing(cls): |
| 101 |
return is_boto3_error_code( |
| 102 |
["DBInstanceNotFound", "DBSnapshotNotFound", "DBClusterNotFound", "DBClusterSnapshotNotFoundFault"] |
| 103 |
) |
| 104 |
|
| 105 |
|
| 106 |
@RDSErrorHandler.list_error_handler("describe db cluster snapshots", []) |
| 107 |
@AWSRetry.jittered_backoff() |
| 108 |
def describe_db_cluster_snapshots(client, **params: Dict) -> List[Dict[str, Any]]: |
| 109 |
paginator = client.get_paginator("describe_db_cluster_snapshots") |
| 110 |
return paginator.paginate(**params).build_full_result()["DBClusterSnapshots"] |
| 111 |
|
| 112 |
|
| 113 |
@RDSErrorHandler.list_error_handler("describe db instances", []) |
| 114 |
@AWSRetry.jittered_backoff() |
| 115 |
def describe_db_instances(client, **params: Dict) -> List[Dict[str, Any]]: |
| 116 |
paginator = client.get_paginator("describe_db_instances") |
| 117 |
return paginator.paginate(**params).build_full_result()["DBInstances"] |
| 118 |
|
| 119 |
|
| 120 |
@RDSErrorHandler.list_error_handler("describe db snapshots", []) |
| 121 |
@AWSRetry.jittered_backoff() |
| 122 |
def describe_db_snapshots(client, **params: Dict) -> List[Dict]: |
| 123 |
paginator = client.get_paginator("describe_db_snapshots") |
| 124 |
return paginator.paginate(**params).build_full_result()["DBSnapshots"] |
| 125 |
|
| 126 |
|
| 127 |
@RDSErrorHandler.list_error_handler("list tags for resource", []) |
| 128 |
@AWSRetry.jittered_backoff() |
| 129 |
def list_tags_for_resource(client, resource_arn: str) -> List[Dict[str, str]]: |
| 130 |
return client.list_tags_for_resource(ResourceName=resource_arn)["TagList"] |
| 131 |
|
| 132 |
|
| 133 |
def get_rds_method_attribute(method_name: str, module: AnsibleAWSModule) -> Boto3ClientMethod: |
| 134 |
""" |
| 135 |
Returns rds attributes of the specified method. |
| 136 |
|
| 137 |
Parameters: |
| 138 |
method_name (str): RDS method to call |
| 139 |
module: AnsibleAWSModule |
| 140 |
|
| 141 |
Returns: |
| 142 |
Boto3ClientMethod (dict): |
| 143 |
name (str): Name of method |
| 144 |
waiter (str): Name of waiter associated with given method |
| 145 |
operation_description (str): Description of method |
| 146 |
resource (str): Type of resource this method applies to |
| 147 |
One of ['instance', 'cluster', 'instance_snapshot', 'cluster_snapshot'] |
| 148 |
retry_codes (list): List of extra error codes to retry on |
| 149 |
|
| 150 |
Raises: |
| 151 |
NotImplementedError if wait is True but no waiter can be found for specified method |
| 152 |
""" |
| 153 |
waiter = "" |
| 154 |
readable_op = method_name.replace("_", " ").replace("db", "DB") |
| 155 |
resource = "" |
| 156 |
retry_codes = [] |
| 157 |
if method_name in cluster_method_names and "new_db_cluster_identifier" in module.params: |
| 158 |
resource = "cluster" |
| 159 |
if method_name == "delete_db_cluster": |
| 160 |
waiter = "cluster_deleted" |
| 161 |
else: |
| 162 |
waiter = "cluster_available" |
| 163 |
# Handle retry codes |
| 164 |
if method_name == "restore_db_cluster_from_snapshot": |
| 165 |
retry_codes = ["InvalidDBClusterSnapshotState"] |
| 166 |
else: |
| 167 |
retry_codes = ["InvalidDBClusterState"] |
| 168 |
elif method_name in instance_method_names and "new_db_instance_identifier" in module.params: |
| 169 |
resource = "instance" |
| 170 |
if method_name == "delete_db_instance": |
| 171 |
waiter = "db_instance_deleted" |
| 172 |
elif method_name == "stop_db_instance": |
| 173 |
waiter = "db_instance_stopped" |
| 174 |
elif method_name == "add_role_to_db_instance": |
| 175 |
waiter = "role_associated" |
| 176 |
elif method_name == "remove_role_from_db_instance": |
| 177 |
waiter = "role_disassociated" |
| 178 |
elif method_name == "promote_read_replica": |
| 179 |
waiter = "read_replica_promoted" |
| 180 |
elif method_name == "db_cluster_promoting": |
| 181 |
waiter = "db_cluster_promoting" |
| 182 |
else: |
| 183 |
waiter = "db_instance_available" |
| 184 |
# Handle retry codes |
| 185 |
if method_name == "restore_db_instance_from_db_snapshot": |
| 186 |
retry_codes = ["InvalidDBSnapshotState"] |
| 187 |
else: |
| 188 |
retry_codes = ["InvalidDBInstanceState", "InvalidDBSecurityGroupState"] |
| 189 |
elif method_name in cluster_snapshot_method_names and "db_cluster_snapshot_identifier" in module.params: |
| 190 |
resource = "cluster_snapshot" |
| 191 |
if method_name == "delete_db_cluster_snapshot": |
| 192 |
waiter = "db_cluster_snapshot_deleted" |
| 193 |
retry_codes = ["InvalidDBClusterSnapshotState"] |
| 194 |
elif method_name == "create_db_cluster_snapshot": |
| 195 |
waiter = "db_cluster_snapshot_available" |
| 196 |
retry_codes = ["InvalidDBClusterState"] |
| 197 |
else: |
| 198 |
# Tagging |
| 199 |
waiter = "db_cluster_snapshot_available" |
| 200 |
retry_codes = ["InvalidDBClusterSnapshotState"] |
| 201 |
elif method_name in instance_snapshot_method_names and "db_snapshot_identifier" in module.params: |
| 202 |
resource = "instance_snapshot" |
| 203 |
if method_name == "delete_db_snapshot": |
| 204 |
waiter = "db_snapshot_deleted" |
| 205 |
retry_codes = ["InvalidDBSnapshotState"] |
| 206 |
elif method_name == "create_db_snapshot": |
| 207 |
waiter = "db_snapshot_available" |
| 208 |
retry_codes = ["InvalidDBInstanceState"] |
| 209 |
else: |
| 210 |
# Tagging |
| 211 |
waiter = "db_snapshot_available" |
| 212 |
retry_codes = ["InvalidDBSnapshotState"] |
| 213 |
else: |
| 214 |
if module.params.get("wait"): |
| 215 |
raise NotImplementedError( |
| 216 |
f"method {method_name} hasn't been added to the list of accepted methods to use a waiter in module_utils/rds.py", |
| 217 |
) |
| 218 |
|
| 219 |
return Boto3ClientMethod( |
| 220 |
name=method_name, waiter=waiter, operation_description=readable_op, resource=resource, retry_codes=retry_codes |
| 221 |
) |
| 222 |
|
| 223 |
|
| 224 |
def get_final_identifier(method_name: str, module: AnsibleAWSModule) -> str: |
| 225 |
""" |
| 226 |
Returns the final identifier for the resource to which the specified method applies. |
| 227 |
|
| 228 |
Parameters: |
| 229 |
method_name (str): RDS method whose target resource final identifier is returned |
| 230 |
module: AnsibleAWSModule |
| 231 |
|
| 232 |
Returns: |
| 233 |
updated_identifier (str): The new resource identifier from module params if not in check mode, there is a new identifier in module params, and |
| 234 |
apply_immediately is True; otherwise returns the original resource identifier from module params |
| 235 |
|
| 236 |
Raises: |
| 237 |
NotImplementedError if the provided method is not supported |
| 238 |
""" |
| 239 |
updated_identifier = None |
| 240 |
apply_immediately = module.params.get("apply_immediately") |
| 241 |
resource = get_rds_method_attribute(method_name, module).resource |
| 242 |
if resource == "cluster": |
| 243 |
identifier = module.params["db_cluster_identifier"] |
| 244 |
updated_identifier = module.params["new_db_cluster_identifier"] |
| 245 |
elif resource == "instance": |
| 246 |
identifier = module.params["db_instance_identifier"] |
| 247 |
updated_identifier = module.params["new_db_instance_identifier"] |
| 248 |
elif resource == "instance_snapshot": |
| 249 |
identifier = module.params["db_snapshot_identifier"] |
| 250 |
elif resource == "cluster_snapshot": |
| 251 |
identifier = module.params["db_cluster_snapshot_identifier"] |
| 252 |
else: |
| 253 |
raise NotImplementedError( |
| 254 |
f"method {method_name} hasn't been added to the list of accepted methods in module_utils/rds.py", |
| 255 |
) |
| 256 |
if not module.check_mode and updated_identifier and apply_immediately: |
| 257 |
identifier = updated_identifier |
| 258 |
return identifier |
| 259 |
|
| 260 |
|
| 261 |
def handle_errors(module: AnsibleAWSModule, exception: Any, method_name: str, parameters: Dict[str, Any]) -> bool: |
| 262 |
""" |
| 263 |
Fails the module with an appropriate error message given the provided exception. |
| 264 |
|
| 265 |
Parameters: |
| 266 |
module: AnsibleAWSModule |
| 267 |
exception: Botocore exception to be handled |
| 268 |
method_name (str): Name of boto3 rds client method |
| 269 |
parameters (dict): Parameters provided to boto3 client method |
| 270 |
|
| 271 |
Returns: |
| 272 |
changed (bool): False if provided exception indicates that no modifications were requested or a read replica promotion was attempted on an |
| 273 |
instance/cluseter that is not a read replica; should never return True (the module should always fail instead) |
| 274 |
""" |
| 275 |
if not isinstance(exception, ClientError): |
| 276 |
module.fail_json_aws(exception, msg=f"Unexpected failure for method {method_name} with parameters {parameters}") |
| 277 |
|
| 278 |
changed = True |
| 279 |
error_code = exception.response["Error"]["Code"] |
| 280 |
if method_name in ("modify_db_instance", "modify_db_cluster") and error_code == "InvalidParameterCombination": |
| 281 |
if "No modifications were requested" in to_text(exception): |
| 282 |
changed = False |
| 283 |
elif "ModifyDbCluster API" in to_text(exception): |
| 284 |
module.fail_json_aws( |
| 285 |
exception, |
| 286 |
msg="It appears you are trying to modify attributes that are managed at the cluster level. Please see rds_cluster", |
| 287 |
) |
| 288 |
else: |
| 289 |
module.fail_json_aws( |
| 290 |
exception, |
| 291 |
msg=f"Unable to {get_rds_method_attribute(method_name, module).operation_description}", |
| 292 |
) |
| 293 |
elif method_name == "promote_read_replica" and error_code == "InvalidDBInstanceState": |
| 294 |
if "DB Instance is not a read replica" in to_text(exception): |
| 295 |
changed = False |
| 296 |
else: |
| 297 |
module.fail_json_aws( |
| 298 |
exception, |
| 299 |
msg=f"Unable to {get_rds_method_attribute(method_name, module).operation_description}", |
| 300 |
) |
| 301 |
elif method_name == "promote_read_replica_db_cluster" and error_code == "InvalidDBClusterStateFault": |
| 302 |
if "DB Cluster that is not a read replica" in to_text(exception): |
| 303 |
changed = False |
| 304 |
else: |
| 305 |
module.fail_json_aws( |
| 306 |
exception, |
| 307 |
msg=f"Unable to {get_rds_method_attribute(method_name, module).operation_description}", |
| 308 |
) |
| 309 |
elif method_name == "create_db_cluster" and error_code == "InvalidParameterValue": |
| 310 |
accepted_engines = ["aurora", "aurora-mysql", "aurora-postgresql", "mysql", "postgres"] |
| 311 |
if parameters.get("Engine") not in accepted_engines: |
| 312 |
module.fail_json_aws( |
| 313 |
exception, msg=f"DB engine {parameters.get('Engine')} should be one of {accepted_engines}" |
| 314 |
) |
| 315 |
else: |
| 316 |
module.fail_json_aws( |
| 317 |
exception, |
| 318 |
msg=f"Unable to {get_rds_method_attribute(method_name, module).operation_description}", |
| 319 |
) |
| 320 |
else: |
| 321 |
module.fail_json_aws( |
| 322 |
exception, |
| 323 |
msg=f"Unable to {get_rds_method_attribute(method_name, module).operation_description}", |
| 324 |
) |
| 325 |
|
| 326 |
return changed |
| 327 |
|
| 328 |
|
| 329 |
def call_method(client, module: AnsibleAWSModule, method_name: str, parameters: Dict[str, Any]) -> Tuple[Any, bool]: |
| 330 |
"""Calls the provided boto3 rds client method with the provided parameters. |
| 331 |
|
| 332 |
Handles check mode determination, whether or not to wait for resource status, and method-specific retry codes. |
| 333 |
|
| 334 |
Parameters: |
| 335 |
client: boto3 rds client |
| 336 |
module: Ansible AWS module |
| 337 |
method_name (str): Name of the boto3 rds client method to call |
| 338 |
parameters (dict): Parameters to pass to the boto3 client method; these must already match expected parameters for the method and |
| 339 |
be formatted correctly (CamelCase, Tags and other attributes converted to lists of dicts as needed) |
| 340 |
|
| 341 |
Returns: |
| 342 |
tuple (any, bool): |
| 343 |
result (any): Result value from method call |
| 344 |
changed (bool): True if changes were made to the resource, False otherwise |
| 345 |
""" |
| 346 |
result = {} |
| 347 |
changed = True |
| 348 |
if not module.check_mode: |
| 349 |
wait = module.params.get("wait") |
| 350 |
retry_codes = get_rds_method_attribute(method_name, module).retry_codes |
| 351 |
method = getattr(client, method_name) |
| 352 |
try: |
| 353 |
result = AWSRetry.jittered_backoff(catch_extra_error_codes=retry_codes)(method)(**parameters) |
| 354 |
except (BotoCoreError, ClientError) as e: |
| 355 |
changed = handle_errors(module, e, method_name, parameters) |
| 356 |
|
| 357 |
if wait and changed: |
| 358 |
identifier = get_final_identifier(method_name, module) |
| 359 |
wait_for_status(client, module, identifier, method_name) |
| 360 |
return result, changed |
| 361 |
|
| 362 |
|
| 363 |
def wait_for_instance_status(client, module: AnsibleAWSModule, db_instance_id: str, waiter_name: str) -> None: |
| 364 |
""" |
| 365 |
Waits until provided instance has reached the expected status for provided waiter. |
| 366 |
|
| 367 |
Fails the module if an exception is raised while waiting. |
| 368 |
|
| 369 |
Parameters: |
| 370 |
client: boto3 rds client |
| 371 |
module: AnsibleAWSModule |
| 372 |
db_instance_id (str): DB instance identifier |
| 373 |
waiter_name (str): Name of either a boto3 rds client waiter or an RDS waiter defined in module_utils/waiters.py |
| 374 |
""" |
| 375 |
|
| 376 |
def wait(client, db_instance_id, waiter_name): |
| 377 |
try: |
| 378 |
waiter = client.get_waiter(waiter_name) |
| 379 |
except ValueError: |
| 380 |
# using a waiter in module_utils/waiters.py |
| 381 |
waiter = get_waiter(client, waiter_name) |
| 382 |
waiter.wait(WaiterConfig={"Delay": 60, "MaxAttempts": 60}, DBInstanceIdentifier=db_instance_id) |
| 383 |
|
| 384 |
waiter_expected_status = { |
| 385 |
"db_instance_deleted": "deleted", |
| 386 |
"db_instance_stopped": "stopped", |
| 387 |
} |
| 388 |
expected_status = waiter_expected_status.get(waiter_name, "available") |
| 389 |
for _wait_attempts in range(0, 10): |
| 390 |
try: |
| 391 |
wait(client, db_instance_id, waiter_name) |
| 392 |
break |
| 393 |
except WaiterError as e: |
| 394 |
# Instance may be renamed and AWSRetry doesn't handle WaiterError |
| 395 |
if e.last_response.get("Error", {}).get("Code") == "DBInstanceNotFound": |
| 396 |
sleep(10) |
| 397 |
continue |
| 398 |
module.fail_json_aws(e, msg=f"Error while waiting for DB instance {db_instance_id} to be {expected_status}") |
| 399 |
except (BotoCoreError, ClientError) as e: |
| 400 |
module.fail_json_aws( |
| 401 |
e, msg=f"Unexpected error while waiting for DB instance {db_instance_id} to be {expected_status}" |
| 402 |
) |
| 403 |
|
| 404 |
|
| 405 |
def wait_for_cluster_status(client, module: AnsibleAWSModule, db_cluster_id: str, waiter_name: str) -> None: |
| 406 |
""" |
| 407 |
Waits until provided cluster has reached the expected status for provided waiter. |
| 408 |
|
| 409 |
Fails the module if an exception is raised while waiting. |
| 410 |
|
| 411 |
Parameters: |
| 412 |
client: boto3 rds client |
| 413 |
module: AnsibleAWSModule |
| 414 |
db_cluster_id (str): DB cluster identifier |
| 415 |
waiter_name (str): Name of either a boto3 rds client waiter or an RDS waiter defined in module_utils/waiters.py |
| 416 |
""" |
| 417 |
try: |
| 418 |
get_waiter(client, waiter_name).wait(DBClusterIdentifier=db_cluster_id) |
| 419 |
except WaiterError as e: |
| 420 |
if waiter_name == "cluster_deleted": |
| 421 |
msg = f"Failed to wait for DB cluster {db_cluster_id} to be deleted" |
| 422 |
else: |
| 423 |
msg = f"Failed to wait for DB cluster {db_cluster_id} to be available" |
| 424 |
module.fail_json_aws(e, msg=msg) |
| 425 |
except (BotoCoreError, ClientError) as e: |
| 426 |
module.fail_json_aws(e, msg=f"Failed with an unexpected error while waiting for the DB cluster {db_cluster_id}") |
| 427 |
|
| 428 |
|
| 429 |
def wait_for_instance_snapshot_status(client, module: AnsibleAWSModule, db_snapshot_id: str, waiter_name: str) -> None: |
| 430 |
""" |
| 431 |
Waits until provided instance snapshot has reached the expected status for provided waiter. |
| 432 |
|
| 433 |
Fails the module if an exception is raised while waiting. |
| 434 |
|
| 435 |
Parameters: |
| 436 |
client: boto3 rds client |
| 437 |
module: AnsibleAWSModule |
| 438 |
db_snapshot_id (str): DB instance snapshot identifier |
| 439 |
waiter_name (str): Name of a boto3 rds client waiter |
| 440 |
""" |
| 441 |
try: |
| 442 |
client.get_waiter(waiter_name).wait(DBSnapshotIdentifier=db_snapshot_id) |
| 443 |
except WaiterError as e: |
| 444 |
if waiter_name == "db_snapshot_deleted": |
| 445 |
msg = f"Failed to wait for DB snapshot {db_snapshot_id} to be deleted" |
| 446 |
else: |
| 447 |
msg = f"Failed to wait for DB snapshot {db_snapshot_id} to be available" |
| 448 |
module.fail_json_aws(e, msg=msg) |
| 449 |
except (BotoCoreError, ClientError) as e: |
| 450 |
module.fail_json_aws( |
| 451 |
e, msg=f"Failed with an unexpected error while waiting for the DB snapshot {db_snapshot_id}" |
| 452 |
) |
| 453 |
|
| 454 |
|
| 455 |
def wait_for_cluster_snapshot_status(client, module: AnsibleAWSModule, db_snapshot_id: str, waiter_name: str) -> None: |
| 456 |
""" |
| 457 |
Waits until provided cluster snapshot has reached the expected status for provided waiter. |
| 458 |
|
| 459 |
Fails the module if an exception is raised while waiting. |
| 460 |
|
| 461 |
Parameters: |
| 462 |
client: boto3 rds client |
| 463 |
module: AnsibleAWSModule |
| 464 |
db_snapshot_id (str): DB cluster snapshot identifier |
| 465 |
waiter_name (str): Name of a boto3 rds client waiter |
| 466 |
""" |
| 467 |
try: |
| 468 |
client.get_waiter(waiter_name).wait(DBClusterSnapshotIdentifier=db_snapshot_id) |
| 469 |
except WaiterError as e: |
| 470 |
if waiter_name == "db_cluster_snapshot_deleted": |
| 471 |
msg = f"Failed to wait for DB cluster snapshot {db_snapshot_id} to be deleted" |
| 472 |
else: |
| 473 |
msg = f"Failed to wait for DB cluster snapshot {db_snapshot_id} to be available" |
| 474 |
module.fail_json_aws(e, msg=msg) |
| 475 |
except (BotoCoreError, ClientError) as e: |
| 476 |
module.fail_json_aws( |
| 477 |
e, |
| 478 |
msg=f"Failed with an unexpected error while waiting for the DB cluster snapshot {db_snapshot_id}", |
| 479 |
) |
| 480 |
|
| 481 |
|
| 482 |
def wait_for_status(client, module: AnsibleAWSModule, identifier: str, method_name: str) -> None: |
| 483 |
""" |
| 484 |
Waits until provided resource has reached the expected final status for provided method. |
| 485 |
|
| 486 |
Parameters: |
| 487 |
client: boto3 rds client |
| 488 |
module: AnsibleAWSModule |
| 489 |
identifier (str): resource identifier |
| 490 |
method_name (str): Name of boto3 rds client method on whose final status to wait |
| 491 |
""" |
| 492 |
rds_method_attributes = get_rds_method_attribute(method_name, module) |
| 493 |
waiter_name = rds_method_attributes.waiter |
| 494 |
resource = rds_method_attributes.resource |
| 495 |
|
| 496 |
if resource == "cluster": |
| 497 |
wait_for_cluster_status(client, module, identifier, waiter_name) |
| 498 |
elif resource == "instance": |
| 499 |
wait_for_instance_status(client, module, identifier, waiter_name) |
| 500 |
elif resource == "instance_snapshot": |
| 501 |
wait_for_instance_snapshot_status(client, module, identifier, waiter_name) |
| 502 |
elif resource == "cluster_snapshot": |
| 503 |
wait_for_cluster_snapshot_status(client, module, identifier, waiter_name) |
| 504 |
|
| 505 |
|
| 506 |
def get_snapshot(client, snapshot_identifier: str, snapshot_type: str, convert_tags: bool = True) -> Dict[str, Any]: |
| 507 |
""" |
| 508 |
Returns instance or cluster snapshot attributes given the snapshot identifier. |
| 509 |
|
| 510 |
Parameters: |
| 511 |
client: boto3 rds client |
| 512 |
snapshot_identifier (str): Unique snapshot identifier |
| 513 |
snapshot_type (str): Which type of snapshot to get, one of: cluster, instance |
| 514 |
convert_tags (bool): Whether to convert the snapshot tags from boto3 list of dicts to Ansible dict; defaults to True |
| 515 |
|
| 516 |
Returns: |
| 517 |
snapshot (dict): Snapshot attributes. If snapshot with provided id is not found, returns an empty dict |
| 518 |
|
| 519 |
Raises: |
| 520 |
ValueError if an invalid snapshot_type is passed |
| 521 |
""" |
| 522 |
valid_types = ("cluster", "instance") |
| 523 |
if snapshot_type not in valid_types: |
| 524 |
raise ValueError(f"Invalid snapshot_type. Expected one of: {valid_types}") |
| 525 |
|
| 526 |
snapshot = {} |
| 527 |
if snapshot_type == "cluster": |
| 528 |
snapshots = describe_db_cluster_snapshots(client, DBClusterSnapshotIdentifier=snapshot_identifier) |
| 529 |
elif snapshot_type == "instance": |
| 530 |
snapshots = describe_db_snapshots(client, DBSnapshotIdentifier=snapshot_identifier) |
| 531 |
if snapshots: |
| 532 |
snapshot = snapshots[0] |
| 533 |
|
| 534 |
if snapshot and convert_tags: |
| 535 |
snapshot["Tags"] = boto3_tag_list_to_ansible_dict(snapshot.pop("TagList", None)) |
| 536 |
|
| 537 |
return snapshot |
| 538 |
|
| 539 |
|
| 540 |
def get_tags(client, module: AnsibleAWSModule, resource_arn: str) -> Dict[str, str]: |
| 541 |
""" |
| 542 |
Returns tags for provided RDS resource, formatted as an Ansible dict. |
| 543 |
|
| 544 |
Fails the module if an error is raised while retrieving resource tags. |
| 545 |
|
| 546 |
Parameters: |
| 547 |
client: boto3 rds client |
| 548 |
module: AnsibleAWSModule |
| 549 |
resource_arn (str): AWS resource ARN |
| 550 |
|
| 551 |
Returns: |
| 552 |
tags (dict): Tags for resource, formatted as an Ansible dict. An empty list is returned if the resource has no tags. |
| 553 |
""" |
| 554 |
try: |
| 555 |
tags = list_tags_for_resource(client, resource_arn) |
| 556 |
except AnsibleRDSError as e: |
| 557 |
module.fail_json_aws(e, msg=f"Unable to list tags for resource {resource_arn}") |
| 558 |
return boto3_tag_list_to_ansible_dict(tags) |
| 559 |
|
| 560 |
|
| 561 |
def arg_spec_to_rds_params(options_dict: Dict[str, Any]) -> Dict[str, Any]: |
| 562 |
""" |
| 563 |
Converts snake_cased rds module options to CamelCased parameter formats expected by boto3 rds client. |
| 564 |
|
| 565 |
Does not alter case for keys or values in the following attributes: tags, processor_features. |
| 566 |
Includes special handling of certain boto3 params that do not follow standard CamelCase. |
| 567 |
|
| 568 |
Parameters: |
| 569 |
options_dict (dict): Snake-cased options for a boto3 rds client method |
| 570 |
|
| 571 |
Returns: |
| 572 |
camel_options (dct): Options formatted for boto3 rds client |
| 573 |
""" |
| 574 |
tags = options_dict.pop("tags") |
| 575 |
has_processor_features = False |
| 576 |
if "processor_features" in options_dict: |
| 577 |
has_processor_features = True |
| 578 |
processor_features = options_dict.pop("processor_features") |
| 579 |
camel_options = snake_dict_to_camel_dict(options_dict, capitalize_first=True) |
| 580 |
aws_replace_keys = ( |
| 581 |
("Db", "DB"), |
| 582 |
("Iam", "IAM"), |
| 583 |
("Az", "AZ"), |
| 584 |
("Ca", "CA"), |
| 585 |
("PerformanceInsightsKmsKeyId", "PerformanceInsightsKMSKeyId"), |
| 586 |
) |
| 587 |
for key in list(camel_options.keys()): |
| 588 |
for old, new in aws_replace_keys: |
| 589 |
if old in key: |
| 590 |
camel_options[key.replace(old, new)] = camel_options.pop(key) |
| 591 |
camel_options["Tags"] = tags |
| 592 |
if has_processor_features: |
| 593 |
camel_options["ProcessorFeatures"] = processor_features |
| 594 |
return camel_options |
| 595 |
|
| 596 |
|
| 597 |
def format_rds_client_method_parameters( |
| 598 |
client, module: AnsibleAWSModule, parameters: Dict[str, Any], method_name: str, format_tags: bool |
| 599 |
) -> Dict[str, Any]: |
| 600 |
""" |
| 601 |
Returns a dict of parameters validated and formatted for the provided boto3 client method. |
| 602 |
|
| 603 |
Performs the following parameters checks and updates: |
| 604 |
- Converts parameters supplied as snake_cased module options to CamelCase |
| 605 |
- Ensures that all required parameters for the provided method are present |
| 606 |
- Ensures that only parameters allowed for the provided method are present, removing any that are not relevant |
| 607 |
- Removes parameters with None values |
| 608 |
- If format_tags is True, converts "Tags" param from an Ansible dict to boto3 list of dicts |
| 609 |
|
| 610 |
Parameters: |
| 611 |
client: boto3 rds client |
| 612 |
module: AnsibleAWSModule |
| 613 |
parameters (dict): Parameter options as provided to module |
| 614 |
method_name (str): boto3 client method for which to validate parameters |
| 615 |
format_tags (bool): Whether to convert tags from an Ansible dict to boto3 list of dicts |
| 616 |
|
| 617 |
Returns: |
| 618 |
Dict of client parameters formatted for the provided method |
| 619 |
|
| 620 |
Raises: |
| 621 |
Fails the module if any parameters required by the provided method are not provided in module options |
| 622 |
""" |
| 623 |
required_options = get_boto3_client_method_parameters(client, method_name, required=True) |
| 624 |
if any(parameters.get(k) is None for k in required_options): |
| 625 |
method_description = get_rds_method_attribute(method_name, module).operation_description |
| 626 |
module.fail_json(msg=f"To {method_description} requires the parameters: {required_options}") |
| 627 |
options = get_boto3_client_method_parameters(client, method_name) |
| 628 |
parameters = dict((k, v) for k, v in parameters.items() if k in options and v is not None) |
| 629 |
if format_tags and parameters.get("Tags"): |
| 630 |
parameters["Tags"] = ansible_dict_to_boto3_tag_list(parameters["Tags"]) |
| 631 |
|
| 632 |
return parameters |
| 633 |
|
| 634 |
|
| 635 |
def ensure_tags( |
| 636 |
client, |
| 637 |
module: AnsibleAWSModule, |
| 638 |
resource_arn: str, |
| 639 |
existing_tags: Dict[str, str], |
| 640 |
tags: Optional[Dict[str, str]], |
| 641 |
purge_tags: bool, |
| 642 |
) -> bool: |
| 643 |
""" |
| 644 |
Compares current resource tages to desired tags and adds/removes tags to ensure desired tags are present. |
| 645 |
|
| 646 |
A value of None for desired tags results in resource tags being left as is. |
| 647 |
|
| 648 |
Parameters: |
| 649 |
client: boto3 rds client |
| 650 |
module: AnsibleAWSModule |
| 651 |
resource_arn (str): AWS resource ARN |
| 652 |
existing_tags (dict): Current resource tags formatted as an Ansible dict |
| 653 |
tags (dict): Desired resource tags formatted as an Ansible dict |
| 654 |
purge_tags (bool): Whether to remove any existing resource tags not present in desired tags |
| 655 |
|
| 656 |
Returns: |
| 657 |
True if resource tags are updated, False if not. |
| 658 |
""" |
| 659 |
if tags is None: |
| 660 |
return False |
| 661 |
tags_to_add, tags_to_remove = compare_aws_tags(existing_tags, tags, purge_tags) |
| 662 |
changed = bool(tags_to_add or tags_to_remove) |
| 663 |
if tags_to_add: |
| 664 |
call_method( |
| 665 |
client, |
| 666 |
module, |
| 667 |
method_name="add_tags_to_resource", |
| 668 |
parameters={"ResourceName": resource_arn, "Tags": ansible_dict_to_boto3_tag_list(tags_to_add)}, |
| 669 |
) |
| 670 |
if tags_to_remove: |
| 671 |
call_method( |
| 672 |
client, |
| 673 |
module, |
| 674 |
method_name="remove_tags_from_resource", |
| 675 |
parameters={"ResourceName": resource_arn, "TagKeys": tags_to_remove}, |
| 676 |
) |
| 677 |
return changed |
| 678 |
|
| 679 |
|
| 680 |
def compare_iam_roles( |
| 681 |
existing_roles: List[Dict[str, str]], target_roles: List[Dict[str, str]], purge_roles: bool |
| 682 |
) -> Tuple[List[Dict[str, str]], List[Dict[str, str]]]: |
| 683 |
""" |
| 684 |
Returns differences between target and existing IAM roles. |
| 685 |
|
| 686 |
Parameters: |
| 687 |
existing_roles (list): Existing IAM roles as a list of snake-cased dicts |
| 688 |
target_roles (list): Target IAM roles as a list of snake-cased dicts |
| 689 |
purge_roles (bool): Remove roles not in target_roles if True |
| 690 |
|
| 691 |
Returns: |
| 692 |
roles_to_add (list): List of IAM roles to add |
| 693 |
roles_to_delete (list): List of IAM roles to delete |
| 694 |
""" |
| 695 |
existing_roles = [dict((k, v) for k, v in role.items() if k != "status") for role in existing_roles] |
| 696 |
roles_to_add = [role for role in target_roles if role not in existing_roles] |
| 697 |
roles_to_remove = [role for role in existing_roles if role not in target_roles] if purge_roles else [] |
| 698 |
return roles_to_add, roles_to_remove |
| 699 |
|
| 700 |
|
| 701 |
def update_iam_roles( |
| 702 |
client, |
| 703 |
module: AnsibleAWSModule, |
| 704 |
instance_id: str, |
| 705 |
roles_to_add: List[Dict[str, str]], |
| 706 |
roles_to_remove: List[Dict[str, str]], |
| 707 |
) -> bool: |
| 708 |
""" |
| 709 |
Update a DB instance's associated IAM roles |
| 710 |
|
| 711 |
Parameters: |
| 712 |
client: RDS client |
| 713 |
module: AnsibleAWSModule |
| 714 |
instance_id (str): DB's instance ID |
| 715 |
roles_to_add (list): List of IAM roles to add in snake-cased dict format |
| 716 |
roles_to_delete (list): List of IAM roles to delete in snake-cased dict format |
| 717 |
|
| 718 |
Returns: |
| 719 |
changed (bool): True if changes were successfully made to DB instance's IAM roles; False if not |
| 720 |
""" |
| 721 |
for role in roles_to_remove: |
| 722 |
params = {"DBInstanceIdentifier": instance_id, "RoleArn": role["role_arn"], "FeatureName": role["feature_name"]} |
| 723 |
_result, changed = call_method(client, module, method_name="remove_role_from_db_instance", parameters=params) |
| 724 |
for role in roles_to_add: |
| 725 |
params = {"DBInstanceIdentifier": instance_id, "RoleArn": role["role_arn"], "FeatureName": role["feature_name"]} |
| 726 |
_result, changed = call_method(client, module, method_name="add_role_to_db_instance", parameters=params) |
| 727 |
return changed |
| 728 |
|
| 729 |
|
| 730 |
@AWSRetry.jittered_backoff() |
| 731 |
def describe_db_cluster_parameter_groups( |
| 732 |
module: AnsibleAWSModule, connection: Any, group_name: Optional[str] |
| 733 |
) -> List[Dict[str, Any]]: |
| 734 |
result = [] |
| 735 |
try: |
| 736 |
params = {} |
| 737 |
if group_name is not None: |
| 738 |
params["DBClusterParameterGroupName"] = group_name |
| 739 |
paginator = connection.get_paginator("describe_db_cluster_parameter_groups") |
| 740 |
result = paginator.paginate(**params).build_full_result()["DBClusterParameterGroups"] |
| 741 |
except is_boto3_error_code("DBParameterGroupNotFound"): |
| 742 |
pass |
| 743 |
except ClientError as e: # pylint: disable=duplicate-except |
| 744 |
module.fail_json_aws(e, msg="Couldn't access parameter groups information") |
| 745 |
return result |
| 746 |
|
| 747 |
|
| 748 |
@AWSRetry.jittered_backoff() |
| 749 |
def describe_db_instance_parameter_groups( |
| 750 |
connection: Any, module: AnsibleAWSModule, db_parameter_group_name: str = None |
| 751 |
) -> List[dict]: |
| 752 |
try: |
| 753 |
if db_parameter_group_name: |
| 754 |
result = connection.describe_db_parameter_groups(DBParameterGroupName=db_parameter_group_name)[ |
| 755 |
"DBParameterGroups" |
| 756 |
] |
| 757 |
else: |
| 758 |
result = connection.describe_db_parameter_groups()["DBParameterGroups"] |
| 759 |
|
| 760 |
# Get tags |
| 761 |
for parameter_group in result: |
| 762 |
existing_tags = connection.list_tags_for_resource(ResourceName=parameter_group["DBParameterGroupArn"])[ |
| 763 |
"TagList" |
| 764 |
] |
| 765 |
parameter_group["tags"] = boto3_tag_list_to_ansible_dict(existing_tags) |
| 766 |
|
| 767 |
return [camel_dict_to_snake_dict(group, ignore_list=["tags"]) for group in result] if result else [] |
| 768 |
except is_boto3_error_code("DBParameterGroupNotFound"): |
| 769 |
return [] |
| 770 |
except ClientError as e: |
| 771 |
module.fail_json_aws(e, msg="Couldn't access parameter group information") |
| 772 |
return result |
| 773 |
|
| 774 |
|
| 775 |
@AWSRetry.jittered_backoff() |
| 776 |
def describe_db_cluster_parameters( |
| 777 |
module: AnsibleAWSModule, connection: Any, group_name: str, source: str = "all" |
| 778 |
) -> List[Dict[str, Any]]: |
| 779 |
result = [] |
| 780 |
try: |
| 781 |
paginator = connection.get_paginator("describe_db_cluster_parameters") |
| 782 |
params = {"DBClusterParameterGroupName": group_name} |
| 783 |
if source != "all": |
| 784 |
params["Source"] = source |
| 785 |
result = paginator.paginate(**params).build_full_result()["Parameters"] |
| 786 |
except is_boto3_error_code("DBParameterGroupNotFound"): |
| 787 |
pass |
| 788 |
except ClientError as e: # pylint: disable=duplicate-except |
| 789 |
module.fail_json_aws(e, msg="Couldn't access RDS cluster parameters information") |
| 790 |
return result |