| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright (c) 2018 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: rds_instance |
| 10 |
version_added: 5.0.0 |
| 11 |
short_description: Manage RDS instances |
| 12 |
description: |
| 13 |
- Create, modify, and delete RDS instances. |
| 14 |
- This module was originally added to C(community.aws) in release 1.0.0. |
| 15 |
extends_documentation_fragment: |
| 16 |
- amazon.aws.common.modules |
| 17 |
- amazon.aws.region.modules |
| 18 |
- amazon.aws.tags |
| 19 |
- amazon.aws.boto3 |
| 20 |
author: |
| 21 |
- Sloane Hertel (@s-hertel) |
| 22 |
|
| 23 |
options: |
| 24 |
# General module options |
| 25 |
state: |
| 26 |
description: |
| 27 |
- Desired state of the RDS Instance. |
| 28 |
- O(state=rebooted) is not idempotent and will leave the DB instance in a running state |
| 29 |
and start it prior to rebooting if it was stopped. V(present) will leave the DB instance in the current running/stopped state, |
| 30 |
(running if creating the DB instance). |
| 31 |
- O(state=running) and I(state=started) are synonyms, as are O(state=rebooted) and O(state=restarted). |
| 32 |
choices: ['present', 'absent', 'terminated', 'running', 'started', 'stopped', 'rebooted', 'restarted'] |
| 33 |
default: 'present' |
| 34 |
type: str |
| 35 |
creation_source: |
| 36 |
description: Which source to use if restoring from a template (an existing instance, S3 bucket, or snapshot). |
| 37 |
choices: ['snapshot', 's3', 'instance'] |
| 38 |
type: str |
| 39 |
force_update_password: |
| 40 |
description: |
| 41 |
- Set to V(true) to update your instance password with O(master_user_password). Since comparing passwords to determine |
| 42 |
if it needs to be updated is not possible this is set to V(false) by default to allow idempotence. |
| 43 |
type: bool |
| 44 |
default: false |
| 45 |
purge_cloudwatch_logs_exports: |
| 46 |
description: |
| 47 |
- Set to V(false) to retain any enabled cloudwatch logs that aren't specified in the task and are associated with the instance. |
| 48 |
- Set O(enable_cloudwatch_logs_exports) to an empty list to disable all. |
| 49 |
type: bool |
| 50 |
default: true |
| 51 |
read_replica: |
| 52 |
description: |
| 53 |
- Set to V(false) to promote a read replica instance or V(true) to create one. When creating a read replica O(creation_source) should |
| 54 |
be set to 'instance' or not provided. O(source_db_instance_identifier) must be provided with this option. |
| 55 |
type: bool |
| 56 |
wait: |
| 57 |
description: |
| 58 |
- Whether to wait for the instance to be available, stopped, or deleted. At a later time a I(wait_timeout) option may be added. |
| 59 |
Following each API call to create/modify/delete the instance a waiter is used with a 60 second delay 30 times until the instance reaches |
| 60 |
the expected state (available/stopped/deleted). The total task time may also be influenced by AWSRetry which helps stabilize if the |
| 61 |
instance is in an invalid state to operate on to begin with (such as if you try to stop it when it is in the process of rebooting). |
| 62 |
If setting this to V(false) task retries and delays may make your playbook execution better handle timeouts for major modifications. |
| 63 |
type: bool |
| 64 |
default: true |
| 65 |
|
| 66 |
# Options that have a corresponding boto3 parameter |
| 67 |
allocated_storage: |
| 68 |
description: |
| 69 |
- The amount of storage (in gibibytes) to allocate for the DB instance. |
| 70 |
type: int |
| 71 |
allow_major_version_upgrade: |
| 72 |
description: |
| 73 |
- Whether to allow major version upgrades. |
| 74 |
type: bool |
| 75 |
apply_immediately: |
| 76 |
description: |
| 77 |
- A value that specifies whether modifying an instance with O(new_db_instance_identifier) and I(master_user_password) |
| 78 |
should be applied as soon as possible, regardless of the O(preferred_maintenance_window) setting. If V(false), changes |
| 79 |
are applied during the next maintenance window. |
| 80 |
type: bool |
| 81 |
default: false |
| 82 |
auto_minor_version_upgrade: |
| 83 |
description: |
| 84 |
- Whether minor version upgrades are applied automatically to the DB instance during the maintenance window. |
| 85 |
type: bool |
| 86 |
availability_zone: |
| 87 |
description: |
| 88 |
- A list of EC2 Availability Zones that the DB instance can be created in. |
| 89 |
May be used when creating an instance or when restoring from S3 or a snapshot. Mutually exclusive with O(multi_az). |
| 90 |
aliases: |
| 91 |
- az |
| 92 |
- zone |
| 93 |
type: str |
| 94 |
backup_retention_period: |
| 95 |
description: |
| 96 |
- The number of days for which automated backups are retained. |
| 97 |
- When set to V(0), automated backups will be disabled. (Not applicable if the DB instance is a source to read replicas) |
| 98 |
- May be used when creating a new instance, when restoring from S3, or when modifying an instance. |
| 99 |
type: int |
| 100 |
ca_certificate_identifier: |
| 101 |
description: |
| 102 |
- The identifier of the CA certificate for the DB instance. |
| 103 |
type: str |
| 104 |
character_set_name: |
| 105 |
description: |
| 106 |
- The character set to associate with the DB instance. |
| 107 |
type: str |
| 108 |
copy_tags_to_snapshot: |
| 109 |
description: |
| 110 |
- Whether or not to copy all tags from the DB instance to snapshots of the instance. When initially creating |
| 111 |
a DB instance the RDS API defaults this to V(false) if unspecified. |
| 112 |
type: bool |
| 113 |
db_cluster_identifier: |
| 114 |
description: |
| 115 |
- The DB cluster (lowercase) identifier to add the aurora DB instance to. The identifier must contain from 1 to |
| 116 |
63 letters, numbers, or hyphens and the first character must be a letter and may not end in a hyphen or |
| 117 |
contain consecutive hyphens. |
| 118 |
aliases: |
| 119 |
- cluster_id |
| 120 |
type: str |
| 121 |
db_instance_class: |
| 122 |
description: |
| 123 |
- The compute and memory capacity of the DB instance, for example V(db.t3.micro). |
| 124 |
aliases: |
| 125 |
- class |
| 126 |
- instance_type |
| 127 |
type: str |
| 128 |
db_instance_identifier: |
| 129 |
description: |
| 130 |
- The DB instance (lowercase) identifier. The identifier must contain from 1 to 63 letters, numbers, or |
| 131 |
hyphens and the first character must be a letter and may not end in a hyphen or contain consecutive hyphens. |
| 132 |
aliases: |
| 133 |
- instance_id |
| 134 |
- id |
| 135 |
required: true |
| 136 |
type: str |
| 137 |
db_name: |
| 138 |
description: |
| 139 |
- The name for your database. If a name is not provided Amazon RDS will not create a database. |
| 140 |
type: str |
| 141 |
db_parameter_group_name: |
| 142 |
description: |
| 143 |
- The name of the DB parameter group to associate with this DB instance. When creating the DB instance if this |
| 144 |
argument is omitted the default DBParameterGroup for the specified engine is used. |
| 145 |
type: str |
| 146 |
db_security_groups: |
| 147 |
description: |
| 148 |
- (EC2-Classic platform) A list of DB security groups to associate with this DB instance. |
| 149 |
type: list |
| 150 |
elements: str |
| 151 |
db_snapshot_identifier: |
| 152 |
description: |
| 153 |
- The identifier or ARN of the DB snapshot to restore from when using O(creation_source=snapshot). |
| 154 |
type: str |
| 155 |
aliases: |
| 156 |
- snapshot_identifier |
| 157 |
- snapshot_id |
| 158 |
db_subnet_group_name: |
| 159 |
description: |
| 160 |
- The DB subnet group name to use for the DB instance. |
| 161 |
aliases: |
| 162 |
- subnet_group |
| 163 |
type: str |
| 164 |
deletion_protection: |
| 165 |
description: |
| 166 |
- A value that indicates whether the DB instance has deletion protection enabled. |
| 167 |
The database can't be deleted when deletion protection is enabled. |
| 168 |
By default, deletion protection is disabled. |
| 169 |
type: bool |
| 170 |
version_added: 3.3.0 |
| 171 |
version_added_collection: community.aws |
| 172 |
domain: |
| 173 |
description: |
| 174 |
- The Active Directory Domain to restore the instance in. |
| 175 |
type: str |
| 176 |
domain_iam_role_name: |
| 177 |
description: |
| 178 |
- The name of the IAM role to be used when making API calls to the Directory Service. |
| 179 |
type: str |
| 180 |
enable_cloudwatch_logs_exports: |
| 181 |
description: |
| 182 |
- A list of log types that need to be enabled for exporting to CloudWatch Logs. |
| 183 |
aliases: |
| 184 |
- cloudwatch_log_exports |
| 185 |
type: list |
| 186 |
elements: str |
| 187 |
enable_iam_database_authentication: |
| 188 |
description: |
| 189 |
- Enable mapping of AWS Identity and Access Management (IAM) accounts to database accounts. |
| 190 |
If this option is omitted when creating the instance, Amazon RDS sets this to V(false). |
| 191 |
type: bool |
| 192 |
enable_performance_insights: |
| 193 |
description: |
| 194 |
- Whether to enable Performance Insights for the DB instance. |
| 195 |
type: bool |
| 196 |
engine: |
| 197 |
description: |
| 198 |
- The name of the database engine to be used for this DB instance. This is required to create an instance. |
| 199 |
choices: ['aurora', 'aurora-mysql', 'aurora-postgresql', 'mariadb', 'mysql', 'oracle-ee', 'oracle-ee-cdb', |
| 200 |
'oracle-se2', 'oracle-se2-cdb', 'postgres', 'sqlserver-ee', 'sqlserver-se', 'sqlserver-ex', 'sqlserver-web'] |
| 201 |
type: str |
| 202 |
engine_version: |
| 203 |
description: |
| 204 |
- The version number of the database engine to use. For Aurora MySQL that could be V(5.6.10a) , V(5.7.12). |
| 205 |
Aurora PostgreSQL example, V(9.6.3) |
| 206 |
type: str |
| 207 |
final_db_snapshot_identifier: |
| 208 |
description: |
| 209 |
- The DB instance snapshot identifier of the new DB instance snapshot created when O(skip_final_snapshot) is V(false). |
| 210 |
aliases: |
| 211 |
- final_snapshot_identifier |
| 212 |
type: str |
| 213 |
force_failover: |
| 214 |
description: |
| 215 |
- Set to V(true) to conduct the reboot through a MultiAZ failover. |
| 216 |
type: bool |
| 217 |
iam_roles: |
| 218 |
description: |
| 219 |
- List of Amazon Web Services Identity and Access Management (IAM) roles to associate with DB instance. |
| 220 |
type: list |
| 221 |
elements: dict |
| 222 |
suboptions: |
| 223 |
feature_name: |
| 224 |
description: |
| 225 |
- The name of the feature associated with the IAM role. |
| 226 |
type: str |
| 227 |
required: true |
| 228 |
role_arn: |
| 229 |
description: |
| 230 |
- The ARN of the IAM role to associate with the DB instance. |
| 231 |
type: str |
| 232 |
required: true |
| 233 |
version_added: 3.3.0 |
| 234 |
version_added_collection: community.aws |
| 235 |
iops: |
| 236 |
description: |
| 237 |
- The Provisioned IOPS (I/O operations per second) value. Is only set when using O(storage_type) is set to V(io1) or V(io2). |
| 238 |
type: int |
| 239 |
kms_key_id: |
| 240 |
description: |
| 241 |
- The ARN of the AWS KMS key identifier for an encrypted DB instance. If you are creating a DB instance with the |
| 242 |
same AWS account that owns the KMS encryption key used to encrypt the new DB instance, then you can use the KMS key |
| 243 |
alias instead of the ARN for the KM encryption key. |
| 244 |
- If O(storage_encrypted) is V(true) and and this option is not provided, the default encryption key is used. |
| 245 |
type: str |
| 246 |
license_model: |
| 247 |
description: |
| 248 |
- The license model for the DB instance. |
| 249 |
- Several options are license-included, bring-your-own-license, and general-public-license. |
| 250 |
- This option can also be omitted to default to an accepted value. |
| 251 |
type: str |
| 252 |
master_user_password: |
| 253 |
description: |
| 254 |
- An 8-41 character password for the master database user. The password can contain any printable ASCII character |
| 255 |
except V(/), V("), or V(@). To modify the password use I(force_update_password). Use O(apply_immediately) to change |
| 256 |
the password immediately, otherwise it is updated during the next maintenance window. |
| 257 |
aliases: |
| 258 |
- password |
| 259 |
type: str |
| 260 |
master_username: |
| 261 |
description: |
| 262 |
- The name of the master user for the DB instance. Must be 1-16 letters or numbers and begin with a letter. |
| 263 |
aliases: |
| 264 |
- username |
| 265 |
type: str |
| 266 |
max_allocated_storage: |
| 267 |
description: |
| 268 |
- The upper limit to which Amazon RDS can automatically scale the storage of the DB instance. |
| 269 |
type: int |
| 270 |
monitoring_interval: |
| 271 |
description: |
| 272 |
- The interval, in seconds, when Enhanced Monitoring metrics are collected for the DB instance. To disable collecting |
| 273 |
metrics, specify V(0). Amazon RDS defaults this to 0 if omitted when initially creating a DB instance. |
| 274 |
type: int |
| 275 |
monitoring_role_arn: |
| 276 |
description: |
| 277 |
- The ARN for the IAM role that permits RDS to send enhanced monitoring metrics to Amazon CloudWatch Logs. |
| 278 |
type: str |
| 279 |
multi_az: |
| 280 |
description: |
| 281 |
- Specifies if the DB instance is a Multi-AZ deployment. Mutually exclusive with O(availability_zone). |
| 282 |
type: bool |
| 283 |
multi_tenant: |
| 284 |
description: |
| 285 |
- Specifies whether to use the multi-tenant configuration or the single-tenant configuration (default). |
| 286 |
- This parameter only applies to RDS for Oracle container database (CDB) engines. |
| 287 |
- The DB engine that you specify in the request must support the multi-tenant configuration. |
| 288 |
- If the multi-tenant configuration is enabled during creation of the DB instance, it cannot be modified later. |
| 289 |
type: bool |
| 290 |
version_added: 9.0.0 |
| 291 |
new_db_instance_identifier: |
| 292 |
description: |
| 293 |
- The new DB instance (lowercase) identifier for the DB instance when renaming a DB instance. The identifier must contain |
| 294 |
from 1 to 63 letters, numbers, or hyphens and the first character must be a letter and may not end in a hyphen or |
| 295 |
contain consecutive hyphens. Use O(apply_immediately) to rename immediately, otherwise it is updated during the |
| 296 |
next maintenance window. |
| 297 |
aliases: |
| 298 |
- new_instance_id |
| 299 |
- new_id |
| 300 |
type: str |
| 301 |
option_group_name: |
| 302 |
description: |
| 303 |
- The option group to associate with the DB instance. |
| 304 |
type: str |
| 305 |
performance_insights_kms_key_id: |
| 306 |
description: |
| 307 |
- The AWS KMS key identifier (ARN, name, or alias) for encryption of Performance Insights data. |
| 308 |
type: str |
| 309 |
performance_insights_retention_period: |
| 310 |
description: |
| 311 |
- The amount of time, in days, to retain Performance Insights data. Valid values are 7 or 731. |
| 312 |
type: int |
| 313 |
port: |
| 314 |
description: |
| 315 |
- The port number on which the instances accept connections. |
| 316 |
type: int |
| 317 |
preferred_backup_window: |
| 318 |
description: |
| 319 |
- The daily time range (in UTC) of at least 30 minutes, during which automated backups are created if automated backups are |
| 320 |
enabled using O(backup_retention_period). The option must be in the format of "hh24:mi-hh24:mi" and not conflict with |
| 321 |
O(preferred_maintenance_window). |
| 322 |
aliases: |
| 323 |
- backup_window |
| 324 |
type: str |
| 325 |
preferred_maintenance_window: |
| 326 |
description: |
| 327 |
- The weekly time range (in UTC) of at least 30 minutes, during which system maintenance can occur. The option must |
| 328 |
be in the format "ddd:hh24:mi-ddd:hh24:mi" where ddd is one of Mon, Tue, Wed, Thu, Fri, Sat, Sun. |
| 329 |
aliases: |
| 330 |
- maintenance_window |
| 331 |
type: str |
| 332 |
processor_features: |
| 333 |
description: |
| 334 |
- A dictionary of Name, Value pairs to indicate the number of CPU cores and the number of threads per core for the |
| 335 |
DB instance class of the DB instance. Names are threadsPerCore and coreCount. |
| 336 |
Set this option to an empty dictionary to use the default processor features. |
| 337 |
suboptions: |
| 338 |
threadsPerCore: |
| 339 |
description: The number of threads per core |
| 340 |
coreCount: |
| 341 |
description: The number of CPU cores |
| 342 |
type: dict |
| 343 |
promotion_tier: |
| 344 |
description: |
| 345 |
- An integer that specifies the order in which an Aurora Replica is promoted to the primary instance after a failure of |
| 346 |
the existing primary instance. |
| 347 |
type: int |
| 348 |
publicly_accessible: |
| 349 |
description: |
| 350 |
- Specifies the accessibility options for the DB instance. A value of Vtrue) specifies an Internet-facing instance with |
| 351 |
a publicly resolvable DNS name, which resolves to a public IP address. A value of C(false) specifies an internal |
| 352 |
instance with a DNS name that resolves to a private IP address. |
| 353 |
type: bool |
| 354 |
purge_iam_roles: |
| 355 |
description: |
| 356 |
- Set to V(true) to remove any IAM roles that aren't specified in the task and are associated with the instance. |
| 357 |
type: bool |
| 358 |
default: false |
| 359 |
version_added: 3.3.0 |
| 360 |
version_added_collection: community.aws |
| 361 |
restore_time: |
| 362 |
description: |
| 363 |
- If using I(creation_source=instance) this indicates the UTC date and time to restore from the source instance. |
| 364 |
For example, "2009-09-07T23:45:00Z". |
| 365 |
- May alternatively set O(use_latest_restorable_time=true). |
| 366 |
- Only one of O(use_latest_restorable_time) and O(restore_time) may be provided. |
| 367 |
type: str |
| 368 |
s3_bucket_name: |
| 369 |
description: |
| 370 |
- The name of the Amazon S3 bucket that contains the data used to create the Amazon DB instance. |
| 371 |
type: str |
| 372 |
s3_ingestion_role_arn: |
| 373 |
description: |
| 374 |
- The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that authorizes Amazon RDS to access |
| 375 |
the Amazon S3 bucket on your behalf. |
| 376 |
type: str |
| 377 |
s3_prefix: |
| 378 |
description: |
| 379 |
- The prefix for all of the file names that contain the data used to create the Amazon DB instance. If you do not |
| 380 |
specify a SourceS3Prefix value, then the Amazon DB instance is created by using all of the files in the Amazon S3 bucket. |
| 381 |
type: str |
| 382 |
skip_final_snapshot: |
| 383 |
description: |
| 384 |
- Whether a final DB instance snapshot is created before the DB instance is deleted. If this is V(false) O(final_db_snapshot_identifier) |
| 385 |
must be provided. |
| 386 |
type: bool |
| 387 |
default: false |
| 388 |
source_db_instance_identifier: |
| 389 |
description: |
| 390 |
- The identifier or ARN of the source DB instance from which to restore when creating a read replica or spinning up a point-in-time |
| 391 |
DB instance using O(creation_source=instance). If the source DB is not in the same region this should be an ARN. |
| 392 |
type: str |
| 393 |
source_engine: |
| 394 |
description: |
| 395 |
- The identifier for the database engine that was backed up to create the files stored in the Amazon S3 bucket. |
| 396 |
choices: |
| 397 |
- mysql |
| 398 |
type: str |
| 399 |
source_engine_version: |
| 400 |
description: |
| 401 |
- The version of the database that the backup files were created from. |
| 402 |
type: str |
| 403 |
source_region: |
| 404 |
description: |
| 405 |
- The region of the DB instance from which the replica is created. |
| 406 |
type: str |
| 407 |
storage_encrypted: |
| 408 |
description: |
| 409 |
- Whether the DB instance is encrypted. |
| 410 |
type: bool |
| 411 |
storage_type: |
| 412 |
description: |
| 413 |
- The storage type to be associated with the DB instance. O(storage_type) does not apply to Aurora DB instances. |
| 414 |
choices: |
| 415 |
- standard |
| 416 |
- gp2 |
| 417 |
- gp3 |
| 418 |
- io1 |
| 419 |
- io2 |
| 420 |
type: str |
| 421 |
storage_throughput: |
| 422 |
description: |
| 423 |
- The storage throughput when the O(storage_type) is V(gp3). |
| 424 |
- When the allocated storage is below 400 GB, the storage throughput will always be 125 mb/s. |
| 425 |
- When the allocated storage is large than or equal 400 GB, the througput starts at 500 mb/s. |
| 426 |
type: int |
| 427 |
version_added: 5.2.0 |
| 428 |
tde_credential_arn: |
| 429 |
description: |
| 430 |
- The ARN from the key store with which to associate the instance for Transparent Data Encryption. This is |
| 431 |
supported by Oracle or SQL Server DB instances and may be used in conjunction with O(storage_encrypted) |
| 432 |
though it might slightly affect the performance of your database. |
| 433 |
aliases: |
| 434 |
- transparent_data_encryption_arn |
| 435 |
type: str |
| 436 |
tde_credential_password: |
| 437 |
description: |
| 438 |
- The password for the given ARN from the key store in order to access the device. |
| 439 |
aliases: |
| 440 |
- transparent_data_encryption_password |
| 441 |
type: str |
| 442 |
timezone: |
| 443 |
description: |
| 444 |
- The time zone of the DB instance. |
| 445 |
type: str |
| 446 |
use_latest_restorable_time: |
| 447 |
description: |
| 448 |
- Whether to restore the DB instance to the latest restorable backup time. |
| 449 |
- Only one of O(use_latest_restorable_time) and O(restore_time) may be provided. |
| 450 |
type: bool |
| 451 |
aliases: |
| 452 |
- restore_from_latest |
| 453 |
vpc_security_group_ids: |
| 454 |
description: |
| 455 |
- A list of EC2 VPC security groups to associate with the DB instance. |
| 456 |
type: list |
| 457 |
elements: str |
| 458 |
purge_security_groups: |
| 459 |
description: |
| 460 |
- Set to V(false) to retain any enabled security groups that aren't specified in the task and are associated with the instance. |
| 461 |
- Can be applied to O(vpc_security_group_ids) and O(db_security_groups) |
| 462 |
type: bool |
| 463 |
default: true |
| 464 |
version_added: 1.5.0 |
| 465 |
version_added_collection: community.aws |
| 466 |
""" |
| 467 |
|
| 468 |
EXAMPLES = r""" |
| 469 |
# Note: These examples do not set authentication details, see the AWS Guide for details. |
| 470 |
- name: Create minimal aurora instance in default VPC and default subnet group |
| 471 |
amazon.aws.rds_instance: |
| 472 |
engine: aurora |
| 473 |
db_instance_identifier: ansible-test-aurora-db-instance |
| 474 |
instance_type: db.t3.small |
| 475 |
password: "{{ password }}" |
| 476 |
username: "{{ username }}" |
| 477 |
cluster_id: ansible-test-cluster # This cluster must exist - see rds_cluster to manage it |
| 478 |
|
| 479 |
- name: Create a DB instance using the default AWS KMS encryption key |
| 480 |
amazon.aws.rds_instance: |
| 481 |
id: test-encrypted-db |
| 482 |
state: present |
| 483 |
engine: mariadb |
| 484 |
storage_encrypted: true |
| 485 |
db_instance_class: db.t3.medium |
| 486 |
username: "{{ username }}" |
| 487 |
password: "{{ password }}" |
| 488 |
allocated_storage: "{{ allocated_storage }}" |
| 489 |
|
| 490 |
- name: Remove the DB instance without a final snapshot |
| 491 |
amazon.aws.rds_instance: |
| 492 |
id: "{{ instance_id }}" |
| 493 |
state: absent |
| 494 |
skip_final_snapshot: true |
| 495 |
|
| 496 |
- name: Remove the DB instance with a final snapshot |
| 497 |
amazon.aws.rds_instance: |
| 498 |
id: "{{ instance_id }}" |
| 499 |
state: absent |
| 500 |
final_snapshot_identifier: "{{ snapshot_id }}" |
| 501 |
|
| 502 |
- name: Add a new security group without purge |
| 503 |
amazon.aws.rds_instance: |
| 504 |
id: "{{ instance_id }}" |
| 505 |
state: present |
| 506 |
vpc_security_group_ids: |
| 507 |
- sg-0be17ba10c9286b0b |
| 508 |
purge_security_groups: false |
| 509 |
register: result |
| 510 |
|
| 511 |
# Add IAM role to db instance |
| 512 |
- name: Create IAM policy |
| 513 |
amazon.aws.iam_managed_policy: |
| 514 |
policy_name: "my-policy" |
| 515 |
policy: "{{ lookup('file','files/policy.json') }}" |
| 516 |
state: present |
| 517 |
register: iam_policy |
| 518 |
|
| 519 |
- name: Create IAM role |
| 520 |
community.aws.iam_role: |
| 521 |
assume_role_policy_document: "{{ lookup('file','files/assume_policy.json') }}" |
| 522 |
name: "my-role" |
| 523 |
state: present |
| 524 |
managed_policy: "{{ iam_policy.policy.arn }}" |
| 525 |
register: iam_role |
| 526 |
|
| 527 |
- name: Create DB instance with added IAM role |
| 528 |
amazon.aws.rds_instance: |
| 529 |
id: "my-instance-id" |
| 530 |
state: present |
| 531 |
engine: postgres |
| 532 |
engine_version: 14.2 |
| 533 |
username: "{{ username }}" |
| 534 |
password: "{{ password }}" |
| 535 |
db_instance_class: db.m6g.large |
| 536 |
allocated_storage: "{{ allocated_storage }}" |
| 537 |
iam_roles: |
| 538 |
- role_arn: "{{ iam_role.arn }}" |
| 539 |
feature_name: 's3Export' |
| 540 |
|
| 541 |
- name: Remove IAM role from DB instance |
| 542 |
amazon.aws.rds_instance: |
| 543 |
id: "my-instance-id" |
| 544 |
state: present |
| 545 |
purge_iam_roles: true |
| 546 |
|
| 547 |
# Modify the DB instance type without waiting for a maintenance window |
| 548 |
- name: Modify an RDS Instance |
| 549 |
amazon.aws.rds_instance: |
| 550 |
db_instance_identifier: mydbinstance123 |
| 551 |
instance_class: db.t2.small |
| 552 |
apply_immediately: true |
| 553 |
register: rds_instance |
| 554 |
|
| 555 |
# Restore DB instance from snapshot |
| 556 |
- name: Create a snapshot and wait until completion |
| 557 |
amazon.aws.rds_instance_snapshot: |
| 558 |
instance_id: 'my-instance-id' |
| 559 |
snapshot_id: 'my-new-snapshot' |
| 560 |
state: present |
| 561 |
wait: true |
| 562 |
register: snapshot |
| 563 |
|
| 564 |
- name: Restore DB from snapshot |
| 565 |
amazon.aws.rds_instance: |
| 566 |
id: 'my-restored-db' |
| 567 |
creation_source: snapshot |
| 568 |
snapshot_identifier: 'my-new-snapshot' |
| 569 |
engine: mariadb |
| 570 |
state: present |
| 571 |
register: restored_db |
| 572 |
""" |
| 573 |
|
| 574 |
RETURN = r""" |
| 575 |
allocated_storage: |
| 576 |
description: The allocated storage size in gigabytes. This is always 1 for aurora database engines. |
| 577 |
returned: always |
| 578 |
type: int |
| 579 |
sample: 20 |
| 580 |
associated_roles: |
| 581 |
description: The list of currently associated roles. |
| 582 |
returned: always |
| 583 |
type: list |
| 584 |
sample: [] |
| 585 |
auto_minor_version_upgrade: |
| 586 |
description: Whether minor engine upgrades are applied automatically to the DB instance during the maintenance window. |
| 587 |
returned: always |
| 588 |
type: bool |
| 589 |
sample: true |
| 590 |
availability_zone: |
| 591 |
description: The availability zone for the DB instance. |
| 592 |
returned: always |
| 593 |
type: str |
| 594 |
sample: us-east-1f |
| 595 |
backup_retention_period: |
| 596 |
description: The number of days for which automated backups are retained. |
| 597 |
returned: always |
| 598 |
type: int |
| 599 |
sample: 1 |
| 600 |
ca_certificate_identifier: |
| 601 |
description: |
| 602 |
- The identifier of the CA certificate for the DB instance. |
| 603 |
returned: always |
| 604 |
type: str |
| 605 |
sample: rds-ca-2015 |
| 606 |
copy_tags_to_snapshot: |
| 607 |
description: Whether tags are copied from the DB instance to snapshots of the DB instance. |
| 608 |
returned: always |
| 609 |
type: bool |
| 610 |
sample: false |
| 611 |
db_instance_arn: |
| 612 |
description: The Amazon Resource Name (ARN) for the DB instance. |
| 613 |
returned: always |
| 614 |
type: str |
| 615 |
sample: arn:aws:rds:us-east-1:123456789012:db:ansible-test |
| 616 |
db_instance_class: |
| 617 |
description: The name of the compute and memory capacity class of the DB instance. |
| 618 |
returned: always |
| 619 |
type: str |
| 620 |
sample: db.m5.large |
| 621 |
db_instance_identifier: |
| 622 |
description: The identifier of the DB instance. |
| 623 |
returned: always |
| 624 |
type: str |
| 625 |
sample: ansible-test |
| 626 |
db_instance_port: |
| 627 |
description: The port that the DB instance listens on. |
| 628 |
returned: always |
| 629 |
type: int |
| 630 |
sample: 0 |
| 631 |
db_instance_status: |
| 632 |
description: The current state of this database. |
| 633 |
returned: always |
| 634 |
type: str |
| 635 |
sample: stopped |
| 636 |
db_parameter_groups: |
| 637 |
description: The list of DB parameter groups applied to this DB instance. |
| 638 |
returned: always |
| 639 |
type: complex |
| 640 |
contains: |
| 641 |
db_parameter_group_name: |
| 642 |
description: The name of the DP parameter group. |
| 643 |
returned: always |
| 644 |
type: str |
| 645 |
sample: default.mariadb10.0 |
| 646 |
parameter_apply_status: |
| 647 |
description: The status of parameter updates. |
| 648 |
returned: always |
| 649 |
type: str |
| 650 |
sample: in-sync |
| 651 |
db_security_groups: |
| 652 |
description: A list of DB security groups associated with this DB instance. |
| 653 |
returned: always |
| 654 |
type: list |
| 655 |
sample: [] |
| 656 |
db_subnet_group: |
| 657 |
description: The subnet group associated with the DB instance. |
| 658 |
returned: always |
| 659 |
type: complex |
| 660 |
contains: |
| 661 |
db_subnet_group_description: |
| 662 |
description: The description of the DB subnet group. |
| 663 |
returned: always |
| 664 |
type: str |
| 665 |
sample: default |
| 666 |
db_subnet_group_name: |
| 667 |
description: The name of the DB subnet group. |
| 668 |
returned: always |
| 669 |
type: str |
| 670 |
sample: default |
| 671 |
subnet_group_status: |
| 672 |
description: The status of the DB subnet group. |
| 673 |
returned: always |
| 674 |
type: str |
| 675 |
sample: Complete |
| 676 |
subnets: |
| 677 |
description: A list of Subnet elements. |
| 678 |
returned: always |
| 679 |
type: complex |
| 680 |
contains: |
| 681 |
subnet_availability_zone: |
| 682 |
description: The availability zone of the subnet. |
| 683 |
returned: always |
| 684 |
type: complex |
| 685 |
contains: |
| 686 |
name: |
| 687 |
description: The name of the Availability Zone. |
| 688 |
returned: always |
| 689 |
type: str |
| 690 |
sample: us-east-1c |
| 691 |
subnet_identifier: |
| 692 |
description: The ID of the subnet. |
| 693 |
returned: always |
| 694 |
type: str |
| 695 |
sample: subnet-12345678 |
| 696 |
subnet_status: |
| 697 |
description: The status of the subnet. |
| 698 |
returned: always |
| 699 |
type: str |
| 700 |
sample: Active |
| 701 |
vpc_id: |
| 702 |
description: The VpcId of the DB subnet group. |
| 703 |
returned: always |
| 704 |
type: str |
| 705 |
sample: vpc-12345678 |
| 706 |
dbi_resource_id: |
| 707 |
description: The AWS Region-unique, immutable identifier for the DB instance. |
| 708 |
returned: always |
| 709 |
type: str |
| 710 |
sample: db-UHV3QRNWX4KB6GALCIGRML6QFA |
| 711 |
deletion_protection: |
| 712 |
description: C(true) if the DB instance has deletion protection enabled, C(False) if not. |
| 713 |
returned: always |
| 714 |
type: bool |
| 715 |
sample: False |
| 716 |
version_added: 3.3.0 |
| 717 |
version_added_collection: community.aws |
| 718 |
domain_memberships: |
| 719 |
description: The Active Directory Domain membership records associated with the DB instance. |
| 720 |
returned: always |
| 721 |
type: list |
| 722 |
sample: [] |
| 723 |
endpoint: |
| 724 |
description: The connection endpoint. |
| 725 |
returned: always |
| 726 |
type: complex |
| 727 |
contains: |
| 728 |
address: |
| 729 |
description: The DNS address of the DB instance. |
| 730 |
returned: always |
| 731 |
type: str |
| 732 |
sample: ansible-test.cvlrtwiennww.us-east-1.rds.amazonaws.com |
| 733 |
hosted_zone_id: |
| 734 |
description: The ID that Amazon Route 53 assigns when you create a hosted zone. |
| 735 |
returned: always |
| 736 |
type: str |
| 737 |
sample: ZTR2ITUGPA61AM |
| 738 |
port: |
| 739 |
description: The port that the database engine is listening on. |
| 740 |
returned: always |
| 741 |
type: int |
| 742 |
sample: 3306 |
| 743 |
engine: |
| 744 |
description: The database engine version. |
| 745 |
returned: always |
| 746 |
type: str |
| 747 |
sample: mariadb |
| 748 |
engine_version: |
| 749 |
description: The database engine version. |
| 750 |
returned: always |
| 751 |
type: str |
| 752 |
sample: 10.0.35 |
| 753 |
iam_database_authentication_enabled: |
| 754 |
description: Whether mapping of AWS Identity and Access Management (IAM) accounts to database accounts is enabled. |
| 755 |
returned: always |
| 756 |
type: bool |
| 757 |
sample: false |
| 758 |
instance_create_time: |
| 759 |
description: The date and time the DB instance was created. |
| 760 |
returned: always |
| 761 |
type: str |
| 762 |
sample: '2018-07-04T16:48:35.332000+00:00' |
| 763 |
kms_key_id: |
| 764 |
description: The AWS KMS key identifier for the encrypted DB instance when storage_encrypted is true. |
| 765 |
returned: When storage_encrypted is true |
| 766 |
type: str |
| 767 |
sample: arn:aws:kms:us-east-1:123456789012:key/70c45553-ad2e-4a85-9f14-cfeb47555c33 |
| 768 |
latest_restorable_time: |
| 769 |
description: The latest time to which a database can be restored with point-in-time restore. |
| 770 |
returned: always |
| 771 |
type: str |
| 772 |
sample: '2018-07-04T16:50:50.642000+00:00' |
| 773 |
license_model: |
| 774 |
description: The License model information for this DB instance. |
| 775 |
returned: always |
| 776 |
type: str |
| 777 |
sample: general-public-license |
| 778 |
master_username: |
| 779 |
description: The master username for the DB instance. |
| 780 |
returned: always |
| 781 |
type: str |
| 782 |
sample: test |
| 783 |
max_allocated_storage: |
| 784 |
description: The upper limit to which Amazon RDS can automatically scale the storage of the DB instance. |
| 785 |
returned: When max allocated storage is present. |
| 786 |
type: int |
| 787 |
sample: 100 |
| 788 |
monitoring_interval: |
| 789 |
description: |
| 790 |
- The interval, in seconds, between points when Enhanced Monitoring metrics are collected for the DB instance. |
| 791 |
0 means collecting Enhanced Monitoring metrics is disabled. |
| 792 |
returned: always |
| 793 |
type: int |
| 794 |
sample: 0 |
| 795 |
multi_az: |
| 796 |
description: Whether the DB instance is a Multi-AZ deployment. |
| 797 |
returned: always |
| 798 |
type: bool |
| 799 |
sample: false |
| 800 |
multi_tenant: |
| 801 |
description: Specifies whether to use the multi-tenant configuration or the single-tenant configuration (default). |
| 802 |
returned: for Oracle container database (CDB) engines and boto3_version == "1.28.80" |
| 803 |
type: bool |
| 804 |
version_added: 9.0.0 |
| 805 |
sample: false |
| 806 |
option_group_memberships: |
| 807 |
description: The list of option group memberships for this DB instance. |
| 808 |
returned: always |
| 809 |
type: complex |
| 810 |
contains: |
| 811 |
option_group_name: |
| 812 |
description: The name of the option group that the instance belongs to. |
| 813 |
returned: always |
| 814 |
type: str |
| 815 |
sample: default:mariadb-10-0 |
| 816 |
status: |
| 817 |
description: The status of the DB instance's option group membership. |
| 818 |
returned: always |
| 819 |
type: str |
| 820 |
sample: in-sync |
| 821 |
pending_modified_values: |
| 822 |
description: The changes to the DB instance that are pending. |
| 823 |
returned: always |
| 824 |
type: complex |
| 825 |
contains: {} |
| 826 |
performance_insights_enabled: |
| 827 |
description: true if Performance Insights is enabled for the DB instance, and otherwise false. |
| 828 |
returned: always |
| 829 |
type: bool |
| 830 |
sample: false |
| 831 |
preferred_backup_window: |
| 832 |
description: The daily time range during which automated backups are created if automated backups are enabled. |
| 833 |
returned: always |
| 834 |
type: str |
| 835 |
sample: 07:01-07:31 |
| 836 |
preferred_maintenance_window: |
| 837 |
description: The weekly time range (in UTC) during which system maintenance can occur. |
| 838 |
returned: always |
| 839 |
type: str |
| 840 |
sample: sun:09:31-sun:10:01 |
| 841 |
publicly_accessible: |
| 842 |
description: |
| 843 |
- C(True) for an Internet-facing instance with a publicly resolvable DNS name, C(False) to indicate an |
| 844 |
internal instance with a DNS name that resolves to a private IP address. |
| 845 |
returned: always |
| 846 |
type: bool |
| 847 |
sample: true |
| 848 |
read_replica_db_instance_identifiers: |
| 849 |
description: Identifiers of the Read Replicas associated with this DB instance. |
| 850 |
returned: always |
| 851 |
type: list |
| 852 |
sample: [] |
| 853 |
storage_encrypted: |
| 854 |
description: Whether the DB instance is encrypted. |
| 855 |
returned: always |
| 856 |
type: bool |
| 857 |
sample: false |
| 858 |
storage_type: |
| 859 |
description: The storage type to be associated with the DB instance. |
| 860 |
returned: always |
| 861 |
type: str |
| 862 |
sample: standard |
| 863 |
tags: |
| 864 |
description: A dictionary of tags associated with the DB instance. |
| 865 |
returned: always |
| 866 |
type: complex |
| 867 |
contains: {} |
| 868 |
vpc_security_groups: |
| 869 |
description: A list of VPC security group elements that the DB instance belongs to. |
| 870 |
returned: always |
| 871 |
type: complex |
| 872 |
contains: |
| 873 |
status: |
| 874 |
description: The status of the VPC security group. |
| 875 |
returned: always |
| 876 |
type: str |
| 877 |
sample: active |
| 878 |
vpc_security_group_id: |
| 879 |
description: The name of the VPC security group. |
| 880 |
returned: always |
| 881 |
type: str |
| 882 |
sample: sg-12345678 |
| 883 |
""" |
| 884 |
|
| 885 |
from time import sleep |
| 886 |
from typing import Any |
| 887 |
from typing import Dict |
| 888 |
from typing import List |
| 889 |
from typing import Optional |
| 890 |
|
| 891 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 892 |
from ansible.module_utils.common.text.converters import to_text |
| 893 |
|
| 894 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_message |
| 895 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 896 |
from ansible_collections.amazon.aws.plugins.module_utils.rds import AnsibleRDSError |
| 897 |
from ansible_collections.amazon.aws.plugins.module_utils.rds import arg_spec_to_rds_params |
| 898 |
from ansible_collections.amazon.aws.plugins.module_utils.rds import call_method |
| 899 |
from ansible_collections.amazon.aws.plugins.module_utils.rds import compare_iam_roles |
| 900 |
from ansible_collections.amazon.aws.plugins.module_utils.rds import describe_db_instances |
| 901 |
from ansible_collections.amazon.aws.plugins.module_utils.rds import ensure_tags |
| 902 |
from ansible_collections.amazon.aws.plugins.module_utils.rds import format_rds_client_method_parameters |
| 903 |
from ansible_collections.amazon.aws.plugins.module_utils.rds import get_final_identifier |
| 904 |
from ansible_collections.amazon.aws.plugins.module_utils.rds import get_snapshot |
| 905 |
from ansible_collections.amazon.aws.plugins.module_utils.rds import update_iam_roles |
| 906 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list |
| 907 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict |
| 908 |
|
| 909 |
valid_engines = [ |
| 910 |
"aurora", |
| 911 |
"aurora-mysql", |
| 912 |
"aurora-postgresql", |
| 913 |
"mariadb", |
| 914 |
"mysql", |
| 915 |
"oracle-ee", |
| 916 |
"oracle-ee-cdb", |
| 917 |
"oracle-se2", |
| 918 |
"oracle-se2-cdb", |
| 919 |
"postgres", |
| 920 |
"sqlserver-ee", |
| 921 |
"sqlserver-se", |
| 922 |
"sqlserver-ex", |
| 923 |
"sqlserver-web", |
| 924 |
] |
| 925 |
|
| 926 |
valid_engines_iam_roles = [ |
| 927 |
"aurora-postgresql", |
| 928 |
"oracle-ee", |
| 929 |
"oracle-ee-cdb", |
| 930 |
"oracle-se2", |
| 931 |
"oracle-se2-cdb", |
| 932 |
"postgres", |
| 933 |
"sqlserver-ee", |
| 934 |
"sqlserver-se", |
| 935 |
"sqlserver-ex", |
| 936 |
"sqlserver-web", |
| 937 |
] |
| 938 |
|
| 939 |
|
| 940 |
def get_rds_method_attribute_name( |
| 941 |
instance: Dict, state: str, creation_source: str, read_replica: Optional[bool] |
| 942 |
) -> Optional[str]: |
| 943 |
""" |
| 944 |
Returns the target boto3 rds client method name given the provided module options and current instance state. |
| 945 |
|
| 946 |
Parameters: |
| 947 |
instance (dict): Current instance attributes as returned by get_instance() |
| 948 |
state (str): Desired instance state as provided to module options |
| 949 |
creation_source (str): Creation source to use for restoring an instance as provided to module options |
| 950 |
read_replica (bool): Whether to create (True) or promote (False) a read replica as provided to module options |
| 951 |
|
| 952 |
Returns: |
| 953 |
method_name (str): Name of boto3 rds client method needed to achieve desired state. Returns None if desired state is "absent" or "terminated" and |
| 954 |
current instance is None or the current instance status is "deleting" or "deleted" |
| 955 |
""" |
| 956 |
method_name = None |
| 957 |
if state == "absent" or state == "terminated": |
| 958 |
if instance and instance["DBInstanceStatus"] not in ["deleting", "deleted"]: |
| 959 |
method_name = "delete_db_instance" |
| 960 |
else: |
| 961 |
if instance: |
| 962 |
method_name = "modify_db_instance" |
| 963 |
elif read_replica is True: |
| 964 |
method_name = "create_db_instance_read_replica" |
| 965 |
elif creation_source == "snapshot": |
| 966 |
method_name = "restore_db_instance_from_db_snapshot" |
| 967 |
elif creation_source == "s3": |
| 968 |
method_name = "restore_db_instance_from_s3" |
| 969 |
elif creation_source == "instance": |
| 970 |
method_name = "restore_db_instance_to_point_in_time" |
| 971 |
else: |
| 972 |
method_name = "create_db_instance" |
| 973 |
return method_name |
| 974 |
|
| 975 |
|
| 976 |
def get_instance(client, module: AnsibleAWSModule, db_instance_id: str) -> Dict[str, Any]: |
| 977 |
""" |
| 978 |
Returns attributes for the provided db instance. |
| 979 |
|
| 980 |
Parameters: |
| 981 |
client: boto3 rds client |
| 982 |
module: AnsibleAWSModule |
| 983 |
db_instance_id (str): DB instance identifier |
| 984 |
|
| 985 |
Returns: |
| 986 |
instance (dict): DB instance attributes with the following boto3 attribute lists converted to dicts of key/value pairs: |
| 987 |
- PendingModifiedValues["ProcessorFeatures"] |
| 988 |
- ProcessorFeatures |
| 989 |
- Tags (from boto3 TagList attribute) |
| 990 |
If no matching instance is found, returns an empty dict. |
| 991 |
|
| 992 |
Raises: |
| 993 |
Fails the module if an exception is raised while retrieving the db instance attributes. |
| 994 |
""" |
| 995 |
instances = None |
| 996 |
try: |
| 997 |
instances = describe_db_instances(client, DBInstanceIdentifier=db_instance_id) |
| 998 |
except AnsibleRDSError as e: |
| 999 |
module.fail_json_aws(e, msg=f"Failed to get DB instance {db_instance_id}") |
| 1000 |
|
| 1001 |
if instances: |
| 1002 |
instance = instances[0] |
| 1003 |
else: |
| 1004 |
return {} |
| 1005 |
|
| 1006 |
instance["Tags"] = boto3_tag_list_to_ansible_dict(instance.pop("TagList")) |
| 1007 |
if instance.get("ProcessorFeatures"): |
| 1008 |
instance["ProcessorFeatures"] = dict( |
| 1009 |
(feature["Name"], feature["Value"]) for feature in instance["ProcessorFeatures"] |
| 1010 |
) |
| 1011 |
if instance.get("PendingModifiedValues", {}).get("ProcessorFeatures"): |
| 1012 |
instance["PendingModifiedValues"]["ProcessorFeatures"] = dict( |
| 1013 |
(feature["Name"], feature["Value"]) for feature in instance["PendingModifiedValues"]["ProcessorFeatures"] |
| 1014 |
) |
| 1015 |
|
| 1016 |
return instance |
| 1017 |
|
| 1018 |
|
| 1019 |
def get_parameters(client, module: AnsibleAWSModule, parameters: Dict[str, Any], method_name: str) -> Dict[str, Any]: |
| 1020 |
""" |
| 1021 |
Returns a dict of parameters validated and formatted for the provided boto3 client method. |
| 1022 |
|
| 1023 |
Performs the following parameters checks and updates: |
| 1024 |
- Formats provided parameters as expected by provided method |
| 1025 |
- Converts the following dict parameters to lists of dicts as expected by the boto3 rds client: ProcessorFeatures, Tags |
| 1026 |
- If method is "modify_db_instance", compares supplied parameters to current instance attributes, determines which parameters need to be modified, and |
| 1027 |
removes any parameters that do not need to be modified |
| 1028 |
|
| 1029 |
Parameters: |
| 1030 |
client: boto3 rds client |
| 1031 |
module: AnsibleAWSModule |
| 1032 |
parameters (dict): Parameter options from module argument_spec |
| 1033 |
method_name: boto3 client method for which to validate parameters |
| 1034 |
|
| 1035 |
Returns: |
| 1036 |
Dict of client parameters formatted for the provided method |
| 1037 |
|
| 1038 |
Raises: |
| 1039 |
Fails the module if any parameters required by the provided method are not provided in module options |
| 1040 |
""" |
| 1041 |
if method_name == "restore_db_instance_to_point_in_time": |
| 1042 |
parameters["TargetDBInstanceIdentifier"] = module.params["db_instance_identifier"] |
| 1043 |
parameters = format_rds_client_method_parameters(client, module, parameters, method_name, format_tags=False) |
| 1044 |
|
| 1045 |
if parameters.get("ProcessorFeatures") is not None: |
| 1046 |
parameters["ProcessorFeatures"] = [ |
| 1047 |
{"Name": k, "Value": to_text(v)} for k, v in parameters["ProcessorFeatures"].items() |
| 1048 |
] |
| 1049 |
|
| 1050 |
# If this parameter is an empty list it can only be used with modify_db_instance (as the parameter UseDefaultProcessorFeatures) |
| 1051 |
if parameters.get("ProcessorFeatures") == [] and not method_name == "modify_db_instance": |
| 1052 |
parameters.pop("ProcessorFeatures") |
| 1053 |
|
| 1054 |
if method_name in ["create_db_instance", "create_db_instance_read_replica", "restore_db_instance_from_db_snapshot"]: |
| 1055 |
if parameters.get("Tags"): |
| 1056 |
parameters["Tags"] = ansible_dict_to_boto3_tag_list(parameters["Tags"]) |
| 1057 |
|
| 1058 |
# For modify_db_instance method, update parameters to include all params that need to be modified by comparing them to current instance attributes |
| 1059 |
if method_name == "modify_db_instance": |
| 1060 |
parameters = get_options_with_changing_values(client, module, parameters) |
| 1061 |
|
| 1062 |
return parameters |
| 1063 |
|
| 1064 |
|
| 1065 |
def get_options_with_changing_values(client, module: AnsibleAWSModule, parameters: Dict[str, Any]) -> Dict[str, Any]: |
| 1066 |
""" |
| 1067 |
Compares current instance attributes to the provided parameters and module options and returns parameters with values to be modified. |
| 1068 |
|
| 1069 |
Parameters: |
| 1070 |
client: boto3 rds client |
| 1071 |
module: AnsibleAWSModule |
| 1072 |
parameters (dict): Parameters for boto3 client modify_db_instance method |
| 1073 |
|
| 1074 |
Returns: |
| 1075 |
parameters (dict): Updated parameters including only parameters that need to be modified, renamed and formatted as expected by boto3 client |
| 1076 |
modify_db_instance method |
| 1077 |
|
| 1078 |
Raises: |
| 1079 |
Fails the module if invalid changes are provided for iops or storage_throughput values |
| 1080 |
""" |
| 1081 |
instance_id = module.params["db_instance_identifier"] |
| 1082 |
purge_cloudwatch_logs = module.params["purge_cloudwatch_logs_exports"] |
| 1083 |
force_update_password = module.params["force_update_password"] |
| 1084 |
port = module.params["port"] |
| 1085 |
apply_immediately = parameters.pop("ApplyImmediately", None) |
| 1086 |
cloudwatch_logs_enabled = module.params["enable_cloudwatch_logs_exports"] |
| 1087 |
purge_security_groups = module.params["purge_security_groups"] |
| 1088 |
ca_certificate_identifier = module.params["ca_certificate_identifier"] |
| 1089 |
multi_tenant = module.params.get("multi_tenant") |
| 1090 |
|
| 1091 |
if ca_certificate_identifier: |
| 1092 |
parameters["CACertificateIdentifier"] = ca_certificate_identifier |
| 1093 |
if port: |
| 1094 |
parameters["DBPortNumber"] = port |
| 1095 |
if not force_update_password: |
| 1096 |
parameters.pop("MasterUserPassword", None) |
| 1097 |
if cloudwatch_logs_enabled is not None: |
| 1098 |
parameters["CloudwatchLogsExportConfiguration"] = cloudwatch_logs_enabled |
| 1099 |
if not module.params["storage_type"]: |
| 1100 |
parameters.pop("Iops", None) |
| 1101 |
|
| 1102 |
instance = get_instance(client, module, instance_id) |
| 1103 |
# Determine which parameters need to be modified |
| 1104 |
updated_parameters = get_changing_options_with_inconsistent_keys( |
| 1105 |
parameters, instance, purge_cloudwatch_logs, purge_security_groups |
| 1106 |
) |
| 1107 |
updated_parameters.update(get_changing_options_with_consistent_keys(parameters, instance)) |
| 1108 |
parameters = updated_parameters |
| 1109 |
|
| 1110 |
# Validate multi_tenant option |
| 1111 |
# Once set to True, it cannot be modified to False |
| 1112 |
if multi_tenant is False: # noqa: E712 |
| 1113 |
if instance.get("MultiTenant"): |
| 1114 |
module.fail_json( |
| 1115 |
msg="A DB which is configured to be a multi tenant cannot be modified to use single tenant configuration." |
| 1116 |
) |
| 1117 |
|
| 1118 |
# Validate changes to storage type options |
| 1119 |
if instance.get("StorageType") in ("io1", "io2"): |
| 1120 |
# Bundle Iops and AllocatedStorage while updating io1 RDS Instance |
| 1121 |
current_iops = instance.get("PendingModifiedValues", {}).get("Iops", instance["Iops"]) |
| 1122 |
current_allocated_storage = instance.get("PendingModifiedValues", {}).get( |
| 1123 |
"AllocatedStorage", instance["AllocatedStorage"] |
| 1124 |
) |
| 1125 |
new_iops = module.params.get("iops") |
| 1126 |
new_allocated_storage = module.params.get("allocated_storage") |
| 1127 |
|
| 1128 |
if current_iops != new_iops or current_allocated_storage != new_allocated_storage: |
| 1129 |
parameters["AllocatedStorage"] = new_allocated_storage |
| 1130 |
parameters["Iops"] = new_iops |
| 1131 |
|
| 1132 |
if instance.get("StorageType") == "gp3": |
| 1133 |
GP3_THROUGHPUT = True |
| 1134 |
current_storage_throughput = instance.get("PendingModifiedValues", {}).get( |
| 1135 |
"StorageThroughput", instance["StorageThroughput"] |
| 1136 |
) |
| 1137 |
new_storage_throughput = module.params.get("storage_throughput") or current_storage_throughput |
| 1138 |
if new_storage_throughput != current_storage_throughput: |
| 1139 |
parameters["StorageThroughput"] = new_storage_throughput |
| 1140 |
|
| 1141 |
current_iops = instance.get("PendingModifiedValues", {}).get("Iops", instance["Iops"]) |
| 1142 |
# when you just change from gp2 to gp3, you may not add the iops parameter |
| 1143 |
new_iops = module.params.get("iops") or current_iops |
| 1144 |
|
| 1145 |
new_allocated_storage = module.params.get("allocated_storage") |
| 1146 |
current_allocated_storage = instance.get("PendingModifiedValues", {}).get( |
| 1147 |
"AllocatedStorage", instance["AllocatedStorage"] |
| 1148 |
) |
| 1149 |
|
| 1150 |
if new_allocated_storage: |
| 1151 |
if current_allocated_storage != new_allocated_storage: |
| 1152 |
parameters["AllocatedStorage"] = new_allocated_storage |
| 1153 |
|
| 1154 |
if new_allocated_storage >= 400: |
| 1155 |
if new_iops < 12000: |
| 1156 |
module.fail_json( |
| 1157 |
msg="IOPS must be at least 12000 when the allocated storage is larger than or equal to 400 GB." |
| 1158 |
) |
| 1159 |
|
| 1160 |
if new_storage_throughput < 500 and GP3_THROUGHPUT: |
| 1161 |
module.fail_json( |
| 1162 |
msg=( |
| 1163 |
"Storage Throughput must be at least 500 when the allocated storage is larger than or equal" |
| 1164 |
" to 400 GB." |
| 1165 |
) |
| 1166 |
) |
| 1167 |
|
| 1168 |
if current_iops != new_iops: |
| 1169 |
parameters["Iops"] = new_iops |
| 1170 |
# must be always specified when changing iops |
| 1171 |
parameters["AllocatedStorage"] = new_allocated_storage |
| 1172 |
|
| 1173 |
instance_performance_insights_kms_key_id = instance.get("PerformanceInsightsKMSKeyId") |
| 1174 |
if instance_performance_insights_kms_key_id == module.params.get( |
| 1175 |
"performance_insights_kms_key_id" |
| 1176 |
) or instance_performance_insights_kms_key_id.split("/")[-1] == module.params.get( |
| 1177 |
"performance_insights_kms_key_id" |
| 1178 |
): |
| 1179 |
parameters.pop("PerformanceInsightsKMSKeyId", None) |
| 1180 |
|
| 1181 |
if parameters.get("NewDBInstanceIdentifier") and instance.get("PendingModifiedValues", {}).get( |
| 1182 |
"DBInstanceIdentifier" |
| 1183 |
): |
| 1184 |
if ( |
| 1185 |
parameters["NewDBInstanceIdentifier"] == instance["PendingModifiedValues"]["DBInstanceIdentifier"] |
| 1186 |
and not apply_immediately |
| 1187 |
): |
| 1188 |
parameters.pop("NewDBInstanceIdentifier") |
| 1189 |
|
| 1190 |
if parameters: |
| 1191 |
parameters["DBInstanceIdentifier"] = instance_id |
| 1192 |
if apply_immediately is not None: |
| 1193 |
parameters["ApplyImmediately"] = apply_immediately |
| 1194 |
|
| 1195 |
return parameters |
| 1196 |
|
| 1197 |
|
| 1198 |
def get_current_attributes_with_inconsistent_keys(instance: Dict[str, Any]) -> Dict[str, Any]: |
| 1199 |
""" |
| 1200 |
Returns current instance attributes whose formats differ from those expected by boto3 client modify_db_instance method, updated to match method options. |
| 1201 |
|
| 1202 |
Option formats for the boto3 client modify_db_instance method do not always match their corresponding attributes returned by describe_db_instances. |
| 1203 |
To ensure that we are accurately comparing the two dicts for changes, this function: |
| 1204 |
- Checks for pending modified values in these instance attributes and updates the corresponding current attributes to match the pending values |
| 1205 |
- Converts these instance attribute names and value formats to those expected by the modify_db_instance method |
| 1206 |
|
| 1207 |
Parameters: |
| 1208 |
instance (dict): Current instance attributes as returned by get_instance() |
| 1209 |
|
| 1210 |
Returns: |
| 1211 |
options (dict): Current instance attributes updated to match the boto3 client modify_db_instance method option formatting. Only returns attributes |
| 1212 |
whose format varies between the returned attributes and the method options (i.e., excludes any attributes whose formats already match what the |
| 1213 |
boto3 client method expects) |
| 1214 |
""" |
| 1215 |
options: Dict[str, Any] = {} |
| 1216 |
|
| 1217 |
# Check for any pending cloudwatch logs exports configuration changes and add them to CloudwatchLogsExportConfiguration option |
| 1218 |
if instance.get("PendingModifiedValues", {}).get("PendingCloudwatchLogsExports", {}).get("LogTypesToEnable", []): |
| 1219 |
current_enabled = instance["PendingModifiedValues"]["PendingCloudwatchLogsExports"]["LogTypesToEnable"] |
| 1220 |
current_disabled = instance["PendingModifiedValues"]["PendingCloudwatchLogsExports"]["LogTypesToDisable"] |
| 1221 |
options["CloudwatchLogsExportConfiguration"] = { |
| 1222 |
"LogTypesToEnable": current_enabled, |
| 1223 |
"LogTypesToDisable": current_disabled, |
| 1224 |
} |
| 1225 |
# If there are no pending cloudwatch logs exports configuration changes, set CloudwatchLogsExportConfiguration option to match current enabled cloudwatch |
| 1226 |
# logs exports attribute |
| 1227 |
else: |
| 1228 |
options["CloudwatchLogsExportConfiguration"] = { |
| 1229 |
"LogTypesToEnable": instance.get("EnabledCloudwatchLogsExports", []), |
| 1230 |
"LogTypesToDisable": [], |
| 1231 |
} |
| 1232 |
|
| 1233 |
# Check for pending changes on other attributes, if not then set options to current attribute values |
| 1234 |
if instance.get("PendingModifiedValues", {}).get("Port"): |
| 1235 |
options["DBPortNumber"] = instance["PendingModifiedValues"]["Port"] |
| 1236 |
else: |
| 1237 |
options["DBPortNumber"] = instance["Endpoint"]["Port"] |
| 1238 |
if instance.get("PendingModifiedValues", {}).get("DBSubnetGroupName"): |
| 1239 |
options["DBSubnetGroupName"] = instance["PendingModifiedValues"]["DBSubnetGroupName"] |
| 1240 |
else: |
| 1241 |
options["DBSubnetGroupName"] = instance["DBSubnetGroup"]["DBSubnetGroupName"] |
| 1242 |
if instance.get("PendingModifiedValues", {}).get("ProcessorFeatures"): |
| 1243 |
options["ProcessorFeatures"] = instance["PendingModifiedValues"]["ProcessorFeatures"] |
| 1244 |
else: |
| 1245 |
options["ProcessorFeatures"] = instance.get("ProcessorFeatures", {}) |
| 1246 |
|
| 1247 |
# Convert current instance's attributes that are lists of dicts to lists of string values for comparison and set the options to updated lists |
| 1248 |
options["OptionGroupName"] = [g["OptionGroupName"] for g in instance["OptionGroupMemberships"]] |
| 1249 |
options["DBSecurityGroups"] = [ |
| 1250 |
sg["DBSecurityGroupName"] for sg in instance["DBSecurityGroups"] if sg["Status"] in ["adding", "active"] |
| 1251 |
] |
| 1252 |
options["VpcSecurityGroupIds"] = [ |
| 1253 |
sg["VpcSecurityGroupId"] for sg in instance["VpcSecurityGroups"] if sg["Status"] in ["adding", "active"] |
| 1254 |
] |
| 1255 |
options["DBParameterGroupName"] = [ |
| 1256 |
parameter_group["DBParameterGroupName"] for parameter_group in instance["DBParameterGroups"] |
| 1257 |
] |
| 1258 |
options["EnableIAMDatabaseAuthentication"] = instance["IAMDatabaseAuthenticationEnabled"] |
| 1259 |
|
| 1260 |
# PerformanceInsightsEnabled is not returned on older RDS instances it seems |
| 1261 |
options["EnablePerformanceInsights"] = instance.get("PerformanceInsightsEnabled", False) |
| 1262 |
options["NewDBInstanceIdentifier"] = instance["DBInstanceIdentifier"] |
| 1263 |
|
| 1264 |
# Neither of these are returned via describe_db_instances, so if either is specified during a check_mode run, changed=True |
| 1265 |
options["AllowMajorVersionUpgrade"] = None |
| 1266 |
options["MasterUserPassword"] = None |
| 1267 |
|
| 1268 |
return options |
| 1269 |
|
| 1270 |
|
| 1271 |
def get_changing_options_with_inconsistent_keys( |
| 1272 |
modify_params: Dict[str, Any], instance: Dict[str, Any], purge_cloudwatch_logs: bool, purge_security_groups: bool |
| 1273 |
) -> Dict[str, Any]: |
| 1274 |
""" |
| 1275 |
Compares current instance attributes with provided parameters whose formats are inconsistent between describe_db_instances and modify_db_instance methods. |
| 1276 |
|
| 1277 |
Parameters: |
| 1278 |
modify_params (dict): Parameters to be supplied to boto3 client modify_db_instance method; should already be validated and formatted |
| 1279 |
instance (dict): Current instance attributes as returned by get_instance() |
| 1280 |
purge_cloudwatch_logs (bool): True if currently enabled cloudwatch logs exports should be removed from configuration when not in provided |
| 1281 |
parameters, False if they should be retained |
| 1282 |
purge_security_groups (bool): True if currently associated security groups should be removed from instance if not in provided parameters, False if |
| 1283 |
they should be retained |
| 1284 |
|
| 1285 |
Returns: |
| 1286 |
changing_params (dict): Parameters to be modified |
| 1287 |
""" |
| 1288 |
changing_params: Dict[str, Any] = {} |
| 1289 |
current_options = get_current_attributes_with_inconsistent_keys(instance) |
| 1290 |
for option, current_option in current_options.items(): |
| 1291 |
desired_option = modify_params.pop(option, None) |
| 1292 |
if desired_option is None: |
| 1293 |
continue |
| 1294 |
|
| 1295 |
# TODO: allow other purge_option module parameters rather than just checking for things to add |
| 1296 |
if isinstance(current_option, list): |
| 1297 |
# Compare lists |
| 1298 |
if isinstance(desired_option, list): |
| 1299 |
if ( |
| 1300 |
set(desired_option) < set(current_option) |
| 1301 |
and option in ["DBSecurityGroups", "VpcSecurityGroupIds"] |
| 1302 |
and purge_security_groups |
| 1303 |
): |
| 1304 |
# There are associated security groups to be purged |
| 1305 |
changing_params[option] = desired_option |
| 1306 |
elif set(desired_option) <= set(current_option): |
| 1307 |
# Desired option set is entirely contained within current option set and purge is False, nothing to change |
| 1308 |
continue |
| 1309 |
elif isinstance(desired_option, str): |
| 1310 |
# Current option is a list and desired option is a string |
| 1311 |
if desired_option in current_option: |
| 1312 |
# Desired option is in current options, nothing to change |
| 1313 |
continue |
| 1314 |
|
| 1315 |
# Current option and desired option are the same - continue loop |
| 1316 |
if option != "ProcessorFeatures" and current_option == desired_option: |
| 1317 |
continue |
| 1318 |
|
| 1319 |
if option == "ProcessorFeatures" and current_option == boto3_tag_list_to_ansible_dict( |
| 1320 |
desired_option, "Name", "Value" |
| 1321 |
): |
| 1322 |
# Processor features are the same, continue loop |
| 1323 |
continue |
| 1324 |
|
| 1325 |
# Current option and desired option are different - add to changing_params list |
| 1326 |
if option == "ProcessorFeatures" and desired_option == []: |
| 1327 |
# Update to use default processor features |
| 1328 |
changing_params["UseDefaultProcessorFeatures"] = True |
| 1329 |
elif option == "CloudwatchLogsExportConfiguration": |
| 1330 |
# Update cloudwatch logs enabled/disabled |
| 1331 |
current_option = set(current_option.get("LogTypesToEnable", [])) |
| 1332 |
desired_option = set(desired_option) |
| 1333 |
format_option: Dict[str, List] = {"EnableLogTypes": [], "DisableLogTypes": []} |
| 1334 |
# Set enable list to any items from desired not in current |
| 1335 |
format_option["EnableLogTypes"] = list(desired_option.difference(current_option)) |
| 1336 |
if purge_cloudwatch_logs: |
| 1337 |
# If purge is true, set disable list to difference between current and desired |
| 1338 |
format_option["DisableLogTypes"] = list(current_option.difference(desired_option)) |
| 1339 |
if format_option["EnableLogTypes"] or format_option["DisableLogTypes"]: |
| 1340 |
# Update cloudwatch logs configuration option to reflect changes |
| 1341 |
changing_params[option] = format_option |
| 1342 |
elif option in ["DBSecurityGroups", "VpcSecurityGroupIds"]: |
| 1343 |
if purge_security_groups: |
| 1344 |
changing_params[option] = desired_option |
| 1345 |
else: |
| 1346 |
changing_params[option] = list(set(current_option) | set(desired_option)) |
| 1347 |
else: |
| 1348 |
changing_params[option] = desired_option |
| 1349 |
return changing_params |
| 1350 |
|
| 1351 |
|
| 1352 |
def get_changing_options_with_consistent_keys( |
| 1353 |
modify_params: Dict[str, Any], instance: Dict[str, Any] |
| 1354 |
) -> Dict[str, Any]: |
| 1355 |
""" |
| 1356 |
Compares current instance attributes with provided parameters whose attribute and parameter formats match. |
| 1357 |
|
| 1358 |
Parameters: |
| 1359 |
modify_params (dict): Parameters to be supplied to boto3 client modify_db_instance method; should already be validated and formatted |
| 1360 |
instance (dict): Current instance attributes as returned by get_instance() |
| 1361 |
|
| 1362 |
Returns: |
| 1363 |
changing_params (dict): Parameters to be modified |
| 1364 |
""" |
| 1365 |
changing_params: Dict[str, Any] = {} |
| 1366 |
for param in modify_params: |
| 1367 |
current_option = instance.get("PendingModifiedValues", {}).get(param, None) |
| 1368 |
if current_option is None: |
| 1369 |
current_option = instance.get(param, None) |
| 1370 |
if modify_params[param] != current_option: |
| 1371 |
changing_params[param] = modify_params[param] |
| 1372 |
|
| 1373 |
return changing_params |
| 1374 |
|
| 1375 |
|
| 1376 |
def validate_options(client, module: AnsibleAWSModule, instance: Dict[str, Any]) -> None: |
| 1377 |
""" |
| 1378 |
Validates complex module option logic and fails the module with an error message if options are invalid. |
| 1379 |
|
| 1380 |
Parameters: |
| 1381 |
client: boto3 rds client |
| 1382 |
module: AnsibleAWSModule |
| 1383 |
instance (dict): Current instance attributes as returned by get_instance() |
| 1384 |
|
| 1385 |
Raises: |
| 1386 |
Fails the module if provided module options are incompatible with each other or with current instance attributes |
| 1387 |
""" |
| 1388 |
state = module.params["state"] |
| 1389 |
skip_final_snapshot = module.params["skip_final_snapshot"] |
| 1390 |
snapshot_id = module.params["final_db_snapshot_identifier"] |
| 1391 |
modified_id = module.params["new_db_instance_identifier"] |
| 1392 |
engine = module.params["engine"] |
| 1393 |
tde_options = bool(module.params["tde_credential_password"] or module.params["tde_credential_arn"]) |
| 1394 |
read_replica = module.params["read_replica"] |
| 1395 |
creation_source = module.params["creation_source"] |
| 1396 |
source_instance = module.params["source_db_instance_identifier"] |
| 1397 |
multi_tenant = module.params["multi_tenant"] |
| 1398 |
|
| 1399 |
if modified_id: |
| 1400 |
modified_instance = get_instance(client, module, modified_id) |
| 1401 |
else: |
| 1402 |
modified_instance = {} |
| 1403 |
|
| 1404 |
if modified_id and instance and modified_instance: |
| 1405 |
module.fail_json(msg=f"A new instance ID {modified_id} was provided but it already exists") |
| 1406 |
if modified_id and not instance and modified_instance: |
| 1407 |
module.fail_json( |
| 1408 |
msg=f"A new instance ID {modified_id} was provided but the instance to be renamed does not exist" |
| 1409 |
) |
| 1410 |
if state in ("absent", "terminated") and instance and not skip_final_snapshot and snapshot_id is None: |
| 1411 |
module.fail_json( |
| 1412 |
msg="skip_final_snapshot is false but all of the following are missing: final_db_snapshot_identifier" |
| 1413 |
) |
| 1414 |
if engine is not None and not (engine.startswith("mysql") or engine.startswith("oracle")) and tde_options: |
| 1415 |
module.fail_json(msg="TDE is available for MySQL and Oracle DB instances") |
| 1416 |
if read_replica is True and not instance and creation_source not in [None, "instance"]: |
| 1417 |
module.fail_json(msg=f"Cannot create a read replica from {creation_source}. You must use a source DB instance") |
| 1418 |
if read_replica is True and not instance and not source_instance: |
| 1419 |
module.fail_json( |
| 1420 |
msg=( |
| 1421 |
"read_replica is true and the instance does not exist yet but all of the following are missing:" |
| 1422 |
" source_db_instance_identifier" |
| 1423 |
) |
| 1424 |
) |
| 1425 |
if multi_tenant is not None and engine not in ["oracle-se2-cdb", "oracle-ee-cdb"]: |
| 1426 |
module.fail_json( |
| 1427 |
msg=( |
| 1428 |
f"Multi Tenant parameter only applies to RDS for Oracle container database (CDB) engines and not to {engine}." |
| 1429 |
) |
| 1430 |
) |
| 1431 |
|
| 1432 |
|
| 1433 |
def update_instance(client, module: AnsibleAWSModule, instance: Dict[str, Any], instance_id: str) -> bool: |
| 1434 |
""" |
| 1435 |
Ensures that an existing instance's tags, read replica status, and state match what is supplied in module options. |
| 1436 |
|
| 1437 |
Parameters: |
| 1438 |
client: boto3 rds client |
| 1439 |
module: AnsibleAWSModule |
| 1440 |
instance (dict): Current instance attributes as returned by get_instance() |
| 1441 |
instance_id (str): Existing instance identifier, used to retrieve instance attributes if provided instance dict is empty |
| 1442 |
|
| 1443 |
Returns: |
| 1444 |
changed (bool): True if instance was successfully updated, False if not |
| 1445 |
""" |
| 1446 |
changed = False |
| 1447 |
|
| 1448 |
# Get newly created DB instance |
| 1449 |
if not instance: |
| 1450 |
instance = get_instance(client, module, instance_id) |
| 1451 |
|
| 1452 |
# Check tagging/promoting/rebooting/starting/stopping instance |
| 1453 |
changed |= ensure_tags( |
| 1454 |
client, module, instance["DBInstanceArn"], instance["Tags"], module.params["tags"], module.params["purge_tags"] |
| 1455 |
) |
| 1456 |
changed |= promote_replication_instance(client, module, instance, module.params["read_replica"]) |
| 1457 |
changed |= update_instance_state(client, module, instance, module.params["state"]) |
| 1458 |
|
| 1459 |
return changed |
| 1460 |
|
| 1461 |
|
| 1462 |
def promote_replication_instance( |
| 1463 |
client, module: AnsibleAWSModule, instance: Dict[str, Any], read_replica: bool |
| 1464 |
) -> bool: |
| 1465 |
""" |
| 1466 |
Promotes the provided DB instance from a read replica to a standalone instance. |
| 1467 |
|
| 1468 |
Only promotes the instance if read_replica is False, which is confusing but is how the module is documented. |
| 1469 |
Returns changed=False without any warning or error message if the provided instance is not a read replica. |
| 1470 |
|
| 1471 |
Parameters: |
| 1472 |
client: boto3 rds client |
| 1473 |
module: AnsibleAWSModule |
| 1474 |
instance (dict): Current instance attributes as returned by get_instance() |
| 1475 |
read_replica (bool): False if instance should be promoted |
| 1476 |
|
| 1477 |
Returns: |
| 1478 |
changed (bool): True if provided instance was successfully promoted, False if not |
| 1479 |
""" |
| 1480 |
changed = False |
| 1481 |
if read_replica is False: |
| 1482 |
# 'StatusInfos' only exists when the instance is a read replica |
| 1483 |
# See https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-instances.html |
| 1484 |
if bool(instance.get("StatusInfos")): |
| 1485 |
try: |
| 1486 |
_result, changed = call_method( |
| 1487 |
client, |
| 1488 |
module, |
| 1489 |
method_name="promote_read_replica", |
| 1490 |
parameters={"DBInstanceIdentifier": instance["DBInstanceIdentifier"]}, |
| 1491 |
) |
| 1492 |
except is_boto3_error_message("DB Instance is not a read replica"): |
| 1493 |
pass |
| 1494 |
return changed |
| 1495 |
|
| 1496 |
|
| 1497 |
def ensure_iam_roles(client, module: AnsibleAWSModule, instance_id: str) -> bool: |
| 1498 |
""" |
| 1499 |
Ensure specified IAM roles are associated with DB instance. |
| 1500 |
|
| 1501 |
Parameters: |
| 1502 |
client: boto3 rds client |
| 1503 |
module: AnsibleAWSModule |
| 1504 |
instance_id (str): Existing DB instance identifier |
| 1505 |
|
| 1506 |
Returns: |
| 1507 |
changed (bool): True if changes were successfully made to DB instance's IAM roles; False if not |
| 1508 |
""" |
| 1509 |
instance = camel_dict_to_snake_dict( |
| 1510 |
get_instance(client, module, instance_id), ignore_list=["Tags", "ProcessorFeatures"] |
| 1511 |
) |
| 1512 |
|
| 1513 |
# Ensure engine type supports associating IAM roles |
| 1514 |
engine = instance.get("engine") |
| 1515 |
if engine not in valid_engines_iam_roles: |
| 1516 |
module.fail_json( |
| 1517 |
msg=f"DB engine {engine} is not valid for adding IAM roles. Valid engines are {valid_engines_iam_roles}" |
| 1518 |
) |
| 1519 |
|
| 1520 |
changed = False |
| 1521 |
purge_iam_roles = module.params.get("purge_iam_roles") |
| 1522 |
target_roles = module.params.get("iam_roles") if module.params.get("iam_roles") else [] |
| 1523 |
existing_roles = instance.get("associated_roles", []) |
| 1524 |
roles_to_add, roles_to_remove = compare_iam_roles(existing_roles, target_roles, purge_iam_roles) |
| 1525 |
if bool(roles_to_add or roles_to_remove): |
| 1526 |
changed = True |
| 1527 |
# Don't update on check_mode |
| 1528 |
if module.check_mode: |
| 1529 |
module.exit_json(changed=changed, **instance) |
| 1530 |
else: |
| 1531 |
update_iam_roles(client, module, instance_id, roles_to_add, roles_to_remove) |
| 1532 |
return changed |
| 1533 |
|
| 1534 |
|
| 1535 |
def update_instance_state(client, module: AnsibleAWSModule, instance: Dict[str, Any], state: str) -> bool: |
| 1536 |
""" |
| 1537 |
Starts, stops, or reboots an instance given the desired state and current instance attributes. |
| 1538 |
|
| 1539 |
Parameters: |
| 1540 |
client: boto3 rds client |
| 1541 |
module: AnsibleAWSModule |
| 1542 |
instance (dict): Current instance attributes as returned by get_instance() |
| 1543 |
state (str): Desired instance state as provided to module options |
| 1544 |
|
| 1545 |
Returns: |
| 1546 |
changed (bool): True if DB instance state was updated, False if not |
| 1547 |
""" |
| 1548 |
changed = False |
| 1549 |
if state in ["rebooted", "restarted"]: |
| 1550 |
changed |= reboot_running_db_instance(client, module, instance) |
| 1551 |
if state in ["started", "running", "stopped"]: |
| 1552 |
changed |= start_or_stop_instance(client, module, instance, state) |
| 1553 |
return changed |
| 1554 |
|
| 1555 |
|
| 1556 |
def reboot_running_db_instance(client, module: AnsibleAWSModule, instance: Dict[str, Any]) -> bool: |
| 1557 |
""" |
| 1558 |
Reboots provided instance. |
| 1559 |
|
| 1560 |
If the instance is currently stopped or stopping, restarts it first. |
| 1561 |
|
| 1562 |
Parameters: |
| 1563 |
client: boto3 rds client |
| 1564 |
module: AnsibleAWSModule |
| 1565 |
instance (dict): Current instance attributes as returned by get_instance() |
| 1566 |
|
| 1567 |
Returns: |
| 1568 |
changed (bool): True if instance was successfully rebooted, False otherwise. |
| 1569 |
""" |
| 1570 |
parameters = {"DBInstanceIdentifier": instance["DBInstanceIdentifier"]} |
| 1571 |
if instance["DBInstanceStatus"] in ["stopped", "stopping"]: |
| 1572 |
call_method(client, module, "start_db_instance", parameters) |
| 1573 |
if module.params.get("force_failover") is not None: |
| 1574 |
parameters["ForceFailover"] = module.params["force_failover"] |
| 1575 |
_results, changed = call_method(client, module, "reboot_db_instance", parameters) |
| 1576 |
return changed |
| 1577 |
|
| 1578 |
|
| 1579 |
def start_or_stop_instance(client, module: AnsibleAWSModule, instance: Dict[str, Any], state: str) -> bool: |
| 1580 |
""" |
| 1581 |
Starts or stops provided instance given desired state. |
| 1582 |
|
| 1583 |
Checks whether the instance is already in or pending the desired state, if so does not alter it. |
| 1584 |
|
| 1585 |
Parameters: |
| 1586 |
client: boto3 rds client |
| 1587 |
module: AnsibleAWSModule |
| 1588 |
instance (dict): Current instance attributes as returned by get_instance() |
| 1589 |
state (str): Desired instance state as provided to module options |
| 1590 |
|
| 1591 |
Returns: |
| 1592 |
changed (bool): True if instance was started or stopped, False if not |
| 1593 |
""" |
| 1594 |
changed = False |
| 1595 |
parameters = {"DBInstanceIdentifier": instance["DBInstanceIdentifier"]} |
| 1596 |
if state == "stopped" and instance["DBInstanceStatus"] not in ["stopping", "stopped"]: |
| 1597 |
if module.params["db_snapshot_identifier"]: |
| 1598 |
parameters["DBSnapshotIdentifier"] = module.params["db_snapshot_identifier"] |
| 1599 |
_result, changed = call_method(client, module, "stop_db_instance", parameters) |
| 1600 |
elif state == "started" and instance["DBInstanceStatus"] not in ["available", "starting", "restarting"]: |
| 1601 |
_result, changed = call_method(client, module, "start_db_instance", parameters) |
| 1602 |
return changed |
| 1603 |
|
| 1604 |
|
| 1605 |
def main(): |
| 1606 |
arg_spec = dict( |
| 1607 |
state=dict( |
| 1608 |
choices=["present", "absent", "terminated", "running", "started", "stopped", "rebooted", "restarted"], |
| 1609 |
default="present", |
| 1610 |
), |
| 1611 |
creation_source=dict(choices=["snapshot", "s3", "instance"]), |
| 1612 |
force_update_password=dict(type="bool", default=False, no_log=False), |
| 1613 |
purge_cloudwatch_logs_exports=dict(type="bool", default=True), |
| 1614 |
purge_iam_roles=dict(type="bool", default=False), |
| 1615 |
purge_tags=dict(type="bool", default=True), |
| 1616 |
read_replica=dict(type="bool"), |
| 1617 |
wait=dict(type="bool", default=True), |
| 1618 |
purge_security_groups=dict(type="bool", default=True), |
| 1619 |
) |
| 1620 |
|
| 1621 |
parameter_options = dict( |
| 1622 |
allocated_storage=dict(type="int"), |
| 1623 |
allow_major_version_upgrade=dict(type="bool"), |
| 1624 |
apply_immediately=dict(type="bool", default=False), |
| 1625 |
auto_minor_version_upgrade=dict(type="bool"), |
| 1626 |
availability_zone=dict(aliases=["az", "zone"]), |
| 1627 |
backup_retention_period=dict(type="int"), |
| 1628 |
ca_certificate_identifier=dict(type="str"), |
| 1629 |
character_set_name=dict(), |
| 1630 |
copy_tags_to_snapshot=dict(type="bool"), |
| 1631 |
db_cluster_identifier=dict(aliases=["cluster_id"]), |
| 1632 |
db_instance_class=dict(aliases=["class", "instance_type"]), |
| 1633 |
db_instance_identifier=dict(required=True, aliases=["instance_id", "id"]), |
| 1634 |
db_name=dict(), |
| 1635 |
db_parameter_group_name=dict(), |
| 1636 |
db_security_groups=dict(type="list", elements="str"), |
| 1637 |
db_snapshot_identifier=dict(type="str", aliases=["snapshot_identifier", "snapshot_id"]), |
| 1638 |
db_subnet_group_name=dict(aliases=["subnet_group"]), |
| 1639 |
deletion_protection=dict(type="bool"), |
| 1640 |
domain=dict(), |
| 1641 |
domain_iam_role_name=dict(), |
| 1642 |
enable_cloudwatch_logs_exports=dict(type="list", aliases=["cloudwatch_log_exports"], elements="str"), |
| 1643 |
enable_iam_database_authentication=dict(type="bool"), |
| 1644 |
enable_performance_insights=dict(type="bool"), |
| 1645 |
engine=dict(type="str", choices=valid_engines), |
| 1646 |
engine_version=dict(), |
| 1647 |
final_db_snapshot_identifier=dict(aliases=["final_snapshot_identifier"]), |
| 1648 |
force_failover=dict(type="bool"), |
| 1649 |
iam_roles=dict(type="list", elements="dict"), |
| 1650 |
iops=dict(type="int"), |
| 1651 |
kms_key_id=dict(), |
| 1652 |
license_model=dict(), |
| 1653 |
master_user_password=dict(aliases=["password"], no_log=True), |
| 1654 |
master_username=dict(aliases=["username"]), |
| 1655 |
max_allocated_storage=dict(type="int"), |
| 1656 |
monitoring_interval=dict(type="int"), |
| 1657 |
monitoring_role_arn=dict(), |
| 1658 |
multi_az=dict(type="bool"), |
| 1659 |
multi_tenant=dict(type="bool"), |
| 1660 |
new_db_instance_identifier=dict(aliases=["new_instance_id", "new_id"]), |
| 1661 |
option_group_name=dict(), |
| 1662 |
performance_insights_kms_key_id=dict(), |
| 1663 |
performance_insights_retention_period=dict(type="int"), |
| 1664 |
port=dict(type="int"), |
| 1665 |
preferred_backup_window=dict(aliases=["backup_window"]), |
| 1666 |
preferred_maintenance_window=dict(aliases=["maintenance_window"]), |
| 1667 |
processor_features=dict(type="dict"), |
| 1668 |
promotion_tier=dict(type="int"), |
| 1669 |
publicly_accessible=dict(type="bool"), |
| 1670 |
restore_time=dict(), |
| 1671 |
s3_bucket_name=dict(), |
| 1672 |
s3_ingestion_role_arn=dict(), |
| 1673 |
s3_prefix=dict(), |
| 1674 |
skip_final_snapshot=dict(type="bool", default=False), |
| 1675 |
source_db_instance_identifier=dict(), |
| 1676 |
source_engine=dict(choices=["mysql"]), |
| 1677 |
source_engine_version=dict(), |
| 1678 |
source_region=dict(), |
| 1679 |
storage_encrypted=dict(type="bool"), |
| 1680 |
storage_type=dict(choices=["standard", "gp2", "gp3", "io1", "io2"]), |
| 1681 |
storage_throughput=dict(type="int"), |
| 1682 |
tags=dict(type="dict", aliases=["resource_tags"]), |
| 1683 |
tde_credential_arn=dict(aliases=["transparent_data_encryption_arn"]), |
| 1684 |
tde_credential_password=dict(no_log=True, aliases=["transparent_data_encryption_password"]), |
| 1685 |
timezone=dict(), |
| 1686 |
use_latest_restorable_time=dict(type="bool", aliases=["restore_from_latest"]), |
| 1687 |
vpc_security_group_ids=dict(type="list", elements="str"), |
| 1688 |
) |
| 1689 |
arg_spec.update(parameter_options) |
| 1690 |
|
| 1691 |
required_if_s3_creation_source = [ |
| 1692 |
"s3_bucket_name", |
| 1693 |
"engine", |
| 1694 |
"master_username", |
| 1695 |
"master_user_password", |
| 1696 |
"source_engine", |
| 1697 |
"source_engine_version", |
| 1698 |
"s3_ingestion_role_arn", |
| 1699 |
] |
| 1700 |
|
| 1701 |
required_if = [ |
| 1702 |
["engine", "aurora", ["db_cluster_identifier"]], |
| 1703 |
["engine", "aurora-mysql", ["db_cluster_identifier"]], |
| 1704 |
["engine", "aurora-postresql", ["db_cluster_identifier"]], |
| 1705 |
["storage_type", "io1", ["iops", "allocated_storage"]], |
| 1706 |
["storage_type", "io2", ["iops", "allocated_storage"]], |
| 1707 |
["creation_source", "snapshot", ["db_snapshot_identifier", "engine"]], |
| 1708 |
["creation_source", "s3", required_if_s3_creation_source], |
| 1709 |
] |
| 1710 |
mutually_exclusive = [ |
| 1711 |
["s3_bucket_name", "source_db_instance_identifier", "db_snapshot_identifier"], |
| 1712 |
["use_latest_restorable_time", "restore_time"], |
| 1713 |
["availability_zone", "multi_az"], |
| 1714 |
] |
| 1715 |
|
| 1716 |
module = AnsibleAWSModule( |
| 1717 |
argument_spec=arg_spec, |
| 1718 |
required_if=required_if, |
| 1719 |
mutually_exclusive=mutually_exclusive, |
| 1720 |
supports_check_mode=True, |
| 1721 |
) |
| 1722 |
|
| 1723 |
# Sanitize instance identifiers |
| 1724 |
module.params["db_instance_identifier"] = module.params["db_instance_identifier"].lower() |
| 1725 |
if module.params["new_db_instance_identifier"]: |
| 1726 |
module.params["new_db_instance_identifier"] = module.params["new_db_instance_identifier"].lower() |
| 1727 |
|
| 1728 |
# Sanitize processor features |
| 1729 |
if module.params["processor_features"] is not None: |
| 1730 |
module.params["processor_features"] = dict( |
| 1731 |
(k, to_text(v)) for k, v in module.params["processor_features"].items() |
| 1732 |
) |
| 1733 |
|
| 1734 |
# Ensure dates are in lowercase |
| 1735 |
if module.params["preferred_maintenance_window"]: |
| 1736 |
module.params["preferred_maintenance_window"] = module.params["preferred_maintenance_window"].lower() |
| 1737 |
|
| 1738 |
# Throw warning regarding case when allow_major_version_upgrade is specified in check_mode |
| 1739 |
# describe_rds_instance never returns this value, so on check_mode, it will always return changed=True |
| 1740 |
# In non-check mode runs, changed will return the correct value, so no need to warn there. |
| 1741 |
# see: amazon.aws.module_util.rds.handle_errors. |
| 1742 |
if module.params.get("allow_major_version_upgrade") and module.check_mode: |
| 1743 |
module.warn( |
| 1744 |
"allow_major_version_upgrade is not returned when describing db instances, so changed will always be `True`" |
| 1745 |
" on check mode runs." |
| 1746 |
) |
| 1747 |
|
| 1748 |
client = module.client("rds") |
| 1749 |
changed = False |
| 1750 |
state = module.params["state"] |
| 1751 |
instance_id = module.params["db_instance_identifier"] |
| 1752 |
instance = get_instance(client, module, instance_id) |
| 1753 |
validate_options(client, module, instance) |
| 1754 |
method_name = get_rds_method_attribute_name( |
| 1755 |
instance, state, module.params["creation_source"], module.params["read_replica"] |
| 1756 |
) |
| 1757 |
|
| 1758 |
if method_name: |
| 1759 |
# Exit on create/delete if check_mode |
| 1760 |
if module.check_mode and method_name in ["create_db_instance", "delete_db_instance"]: |
| 1761 |
module.exit_json( |
| 1762 |
changed=True, **camel_dict_to_snake_dict(instance, ignore_list=["Tags", "ProcessorFeatures"]) |
| 1763 |
) |
| 1764 |
|
| 1765 |
raw_parameters = arg_spec_to_rds_params( |
| 1766 |
dict((k, module.params[k]) for k in module.params if k in parameter_options) |
| 1767 |
) |
| 1768 |
parameters_to_modify = get_parameters(client, module, raw_parameters, method_name) |
| 1769 |
|
| 1770 |
if parameters_to_modify: |
| 1771 |
# Exit on check_mode when parameters to modify |
| 1772 |
if module.check_mode: |
| 1773 |
module.exit_json( |
| 1774 |
changed=True, **camel_dict_to_snake_dict(instance, ignore_list=["Tags", "ProcessorFeatures"]) |
| 1775 |
) |
| 1776 |
_result, changed = call_method(client, module, method_name, parameters_to_modify) |
| 1777 |
|
| 1778 |
instance_id = get_final_identifier(method_name, module) |
| 1779 |
|
| 1780 |
if state != "absent": |
| 1781 |
# Check tagging/promoting/rebooting/starting/stopping instance |
| 1782 |
if not module.check_mode or instance: |
| 1783 |
changed |= update_instance(client, module, instance, instance_id) |
| 1784 |
|
| 1785 |
# Check IAM roles |
| 1786 |
if module.params.get("iam_roles") or module.params.get("purge_iam_roles"): |
| 1787 |
changed |= ensure_iam_roles(client, module, instance_id) |
| 1788 |
|
| 1789 |
if changed: |
| 1790 |
instance = get_instance(client, module, instance_id) |
| 1791 |
if state != "absent" and (instance or not module.check_mode): |
| 1792 |
for _wait_attempt in range(0, 10): |
| 1793 |
instance = get_instance(client, module, instance_id) |
| 1794 |
if instance: |
| 1795 |
break |
| 1796 |
sleep(5) |
| 1797 |
|
| 1798 |
if state == "absent" and changed and not module.params["skip_final_snapshot"]: |
| 1799 |
snapshot_id = module.params["final_db_snapshot_identifier"] |
| 1800 |
try: |
| 1801 |
instance.update(FinalSnapshot=get_snapshot(client, snapshot_id, "instance", False)) |
| 1802 |
except AnsibleRDSError as e: |
| 1803 |
module.fail_json_aws(e, msg=f"Failed to get snapshot: {snapshot_id}") |
| 1804 |
|
| 1805 |
pending_processor_features = None |
| 1806 |
if instance.get("PendingModifiedValues", {}).get("ProcessorFeatures"): |
| 1807 |
pending_processor_features = instance["PendingModifiedValues"].pop("ProcessorFeatures") |
| 1808 |
instance = camel_dict_to_snake_dict(instance, ignore_list=["Tags", "ProcessorFeatures"]) |
| 1809 |
if pending_processor_features is not None: |
| 1810 |
instance["pending_modified_values"]["processor_features"] = pending_processor_features |
| 1811 |
|
| 1812 |
module.exit_json(changed=changed, **instance) |
| 1813 |
|
| 1814 |
|
| 1815 |
if __name__ == "__main__": |
| 1816 |
main() |