Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/rds_cluster.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2022 Ansible Project
5 # Copyright (c) 2022 Alina Buzachis (@alinabuzachis)
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 DOCUMENTATION = r"""
9 ---
10 module: rds_cluster
11 version_added: 5.0.0
12 short_description: rds_cluster module
13 description:
14 - Create, modify, and delete RDS clusters.
15 - This module was originally added to C(community.aws) in release 3.2.0.
16 extends_documentation_fragment:
17 - amazon.aws.common.modules
18 - amazon.aws.region.modules
19 - amazon.aws.tags
20 - amazon.aws.boto3
21 author:
22 - Sloane Hertel (@s-hertel)
23 - Alina Buzachis (@alinabuzachis)
24 options:
25 # General module options
26 state:
27 description:
28 - Whether the snapshot should exist or not.
29 - V(started) and V(stopped) can only be used with aurora clusters.
30 - Support for V(started) and V(stopped) was added in release 6.3.0.
31 choices: ['present', 'absent', 'started', 'stopped']
32 default: 'present'
33 type: str
34 creation_source:
35 description: Which source to use if creating from a template (an existing cluster, S3 bucket, or snapshot).
36 choices: ['snapshot', 's3', 'cluster']
37 type: str
38 force_update_password:
39 description:
40 - Set to V(true) to update your cluster password with O(master_user_password).
41 - Since comparing passwords to determine if it needs to be updated is not possible this is set to V(false) by default to allow idempotence.
42 type: bool
43 default: false
44 promote:
45 description: Set to V(true) to promote a read replica cluster.
46 type: bool
47 default: false
48 purge_cloudwatch_logs_exports:
49 description:
50 - Whether or not to disable Cloudwatch logs enabled for the DB cluster that are not provided in O(enable_cloudwatch_logs_exports).
51 Set O(enable_cloudwatch_logs_exports) to an empty list to disable all.
52 type: bool
53 default: true
54 purge_security_groups:
55 description:
56 - Set to V(false) to retain any enabled security groups that aren't specified in the task and are associated with the cluster.
57 - Can be applied to O(vpc_security_group_ids)
58 type: bool
59 default: true
60 wait:
61 description: Whether to wait for the cluster to be available or deleted.
62 type: bool
63 default: true
64 # Options that have a corresponding boto3 parameter
65 apply_immediately:
66 description:
67 - A value that specifies whether modifying a cluster with O(new_db_cluster_identifier) and O(master_user_password)
68 should be applied as soon as possible, regardless of the O(preferred_maintenance_window) setting. If V(false), changes
69 are applied during the next maintenance window.
70 type: bool
71 default: false
72 availability_zones:
73 description:
74 - A list of EC2 Availability Zones that instances in the DB cluster can be created in.
75 May be used when creating a cluster or when restoring from S3 or a snapshot.
76 aliases:
77 - zones
78 - az
79 type: list
80 elements: str
81 backtrack_to:
82 description:
83 - The timestamp of the time to backtrack the DB cluster to in ISO 8601 format, such as "2017-07-08T18:00Z".
84 type: str
85 backtrack_window:
86 description:
87 - The target backtrack window, in seconds. To disable backtracking, set this value to V(0).
88 - If specified, this value must be set to a number from V(0) to V(259,200) (72 hours).
89 type: int
90 backup_retention_period:
91 description:
92 - The number of days for which automated backups are retained (must be within V(1) to V(35)).
93 May be used when creating a new cluster, when restoring from S3, or when modifying a cluster.
94 type: int
95 default: 1
96 character_set_name:
97 description:
98 - The character set to associate with the DB cluster.
99 type: str
100 database_name:
101 description:
102 - The name for your database. If a name is not provided Amazon RDS will not create a database.
103 aliases:
104 - db_name
105 type: str
106 db_cluster_identifier:
107 description:
108 - The DB cluster (lowercase) identifier. The identifier must contain from 1 to 63 letters, numbers, or
109 hyphens and the first character must be a letter and may not end in a hyphen or contain consecutive hyphens.
110 aliases:
111 - cluster_id
112 - id
113 - cluster_name
114 type: str
115 required: true
116 db_cluster_parameter_group_name:
117 description:
118 - The name of the DB cluster parameter group to associate with this DB cluster.
119 If this argument is omitted when creating a cluster, the default DB cluster parameter group for the specified DB engine and version is used.
120 type: str
121 db_subnet_group_name:
122 description:
123 - A DB subnet group to associate with this DB cluster if not using the default.
124 type: str
125 enable_cloudwatch_logs_exports:
126 description:
127 - A list of log types that need to be enabled for exporting to CloudWatch Logs.
128 - Engine aurora-mysql supports V(audit), V(error), V(general) and V(slowquery).
129 - Engine aurora-postgresql supports V(postgresql).
130 type: list
131 elements: str
132 deletion_protection:
133 description:
134 - A value that indicates whether the DB cluster has deletion protection enabled.
135 The database can't be deleted when deletion protection is enabled.
136 By default, deletion protection is disabled.
137 type: bool
138 global_cluster_identifier:
139 description:
140 - The global cluster ID of an Aurora cluster that becomes the primary cluster in the new global database cluster.
141 type: str
142 enable_http_endpoint:
143 description:
144 - A value that indicates whether to enable the HTTP endpoint for an Aurora Serverless DB cluster.
145 By default, the HTTP endpoint is disabled.
146 type: bool
147 copy_tags_to_snapshot:
148 description:
149 - Indicates whether to copy all tags from the DB cluster to snapshots of the DB cluster.
150 The default is not to copy them.
151 type: bool
152 domain:
153 description:
154 - The Active Directory directory ID to create the DB cluster in.
155 type: str
156 domain_iam_role_name:
157 description:
158 - Specify the name of the IAM role to be used when making API calls to the Directory Service.
159 type: str
160 enable_global_write_forwarding:
161 description:
162 - A value that indicates whether to enable this DB cluster to forward write operations to the primary cluster of an Aurora global database.
163 By default, write operations are not allowed on Aurora DB clusters that are secondary clusters in an Aurora global database.
164 - This value can be only set on Aurora DB clusters that are members of an Aurora global database.
165 type: bool
166 db_cluster_instance_class:
167 description:
168 - The compute and memory capacity of each DB instance in the Multi-AZ DB cluster, for example V(db.m6gd.xlarge).
169 - Not all DB instance classes are available in all Amazon Web Services Regions, or for all database engines.
170 - For the full list of DB instance classes and availability for your engine visit
171 U(https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.DBInstanceClass.html).
172 - This setting is required to create a Multi-AZ DB cluster.
173 type: str
174 version_added: 5.5.0
175 enable_iam_database_authentication:
176 description:
177 - Enable mapping of AWS Identity and Access Management (IAM) accounts to database accounts.
178 If this option is omitted when creating the cluster, Amazon RDS sets this to C(false).
179 type: bool
180 allocated_storage:
181 description:
182 - The amount of storage in gibibytes (GiB) to allocate to each DB instance in the Multi-AZ DB cluster.
183 - This setting is required to create a Multi-AZ DB cluster.
184 type: int
185 version_added: 5.5.0
186 storage_type:
187 description:
188 - Specifies the storage type to be associated with the DB cluster.
189 - This setting is required to create a Multi-AZ DB cluster.
190 - For multi-AZ DB clusters, O(storage_type) defaults to V(io1) and a value for the O(iops) parameter is required.
191 - For Aurora DB clusters, O(storage_type) defaults to V(aurora) standard.
192 - For mysql and postgres DB clusters, O(storage_type) defaults to V(io1).
193 - Support for V(aurora) and V(aurora-iopt1) was added in release 8.2.0.
194 type: str
195 choices:
196 - io1
197 - aurora
198 - aurora-iopt1
199 version_added: 5.5.0
200 iops:
201 description:
202 - The amount of Provisioned IOPS (input/output operations per second) to be initially allocated for each DB instance in the Multi-AZ DB cluster.
203 - This setting is required to create a Multi-AZ DB cluster
204 - Must be a multiple between .5 and 50 of the storage amount for the DB cluster.
205 type: int
206 version_added: 5.5.0
207 engine:
208 description:
209 - The name of the database engine to be used for this DB cluster. This is required to create a cluster.
210 - The combinaison of I(engine) and I(engine_mode) may not be supported.
211 - "See AWS documentation for details:
212 L(Amazon RDS Documentation,https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CreateDBCluster.html)."
213 - When O(engine=mysql), O(allocated_storage), O(iops) and O(db_cluster_instance_class) must also be specified.
214 - When I(engine=postgres), O(allocated_storage), O(iops) and O(db_cluster_instance_class) must also be specified.
215 - Support for V(postgres) and V(mysql) was added in amazon.aws 5.5.0.
216 choices:
217 - aurora
218 - aurora-mysql
219 - aurora-postgresql
220 - mysql
221 - postgres
222 type: str
223 engine_mode:
224 description:
225 - The DB engine mode of the DB cluster. The combination of O(engine) and O(engine_mode) may not be supported.
226 - "See AWS documentation for details:
227 L(Amazon RDS Documentation,https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CreateDBCluster.html)."
228 choices:
229 - provisioned
230 - serverless
231 - parallelquery
232 - global
233 - multimaster
234 type: str
235 version_added: 5.5.0
236 engine_version:
237 description:
238 - The version number of the database engine to use.
239 - For Aurora MySQL that could be V(5.6.10a), V(5.7.12).
240 - Aurora PostgreSQL example, V(9.6.3).
241 type: str
242 final_snapshot_identifier:
243 description:
244 - The DB cluster snapshot identifier of the new DB cluster snapshot created when O(skip_final_snapshot=false).
245 type: str
246 force_backtrack:
247 description:
248 - A boolean to indicate if the DB cluster should be forced to backtrack when binary logging is enabled.
249 Otherwise, an error occurs when binary logging is enabled.
250 type: bool
251 kms_key_id:
252 description:
253 - The AWS KMS key identifier (the ARN, unless you are creating a cluster in the same account that owns the
254 KMS key, in which case the KMS key alias may be used).
255 - If O(replication_source_identifier) specifies an encrypted source Amazon RDS will use the key used toe encrypt the source.
256 - If O(storage_encrypted=true) and and O(replication_source_identifier) is not provided, the default encryption key is used.
257 type: str
258 master_user_password:
259 description:
260 - An 8-41 character password for the master database user.
261 - The password can contain any printable ASCII character except V(/), V("), or V(@).
262 - To modify the password use O(force_update_password). Use O(apply_immediately) to change
263 the password immediately, otherwise it is updated during the next maintenance window.
264 aliases:
265 - password
266 type: str
267 master_username:
268 description:
269 - The name of the master user for the DB cluster. Must be 1-16 letters or numbers and begin with a letter.
270 aliases:
271 - username
272 type: str
273 new_db_cluster_identifier:
274 description:
275 - The new DB cluster (lowercase) identifier for the DB cluster when renaming a DB cluster.
276 - The identifier must contain from 1 to 63 letters, numbers, or hyphens and the first character must be a
277 letter and may not end in a hyphen or contain consecutive hyphens.
278 - Use O(apply_immediately) to rename immediately, otherwise it is updated during the next maintenance window.
279 aliases:
280 - new_cluster_id
281 - new_id
282 - new_cluster_name
283 type: str
284 option_group_name:
285 description:
286 - The option group to associate with the DB cluster.
287 type: str
288 port:
289 description:
290 - The port number on which the instances in the DB cluster accept connections. If not specified, Amazon RDS
291 defaults this to V(3306) if the O(engine) is V(aurora) and V(5432) if the O(engine) is V(aurora-postgresql).
292 type: int
293 preferred_backup_window:
294 description:
295 - The daily time range (in UTC) of at least 30 minutes, during which automated backups are created if automated backups are
296 enabled using O(backup_retention_period). The option must be in the format of "hh24:mi-hh24:mi" and not conflict with
297 O(preferred_maintenance_window).
298 aliases:
299 - backup_window
300 type: str
301 preferred_maintenance_window:
302 description:
303 - The weekly time range (in UTC) of at least 30 minutes, during which system maintenance can occur. The option must
304 be in the format "ddd:hh24:mi-ddd:hh24:mi" where ddd is one of Mon, Tue, Wed, Thu, Fri, Sat, Sun.
305 aliases:
306 - maintenance_window
307 type: str
308 remove_from_global_db:
309 description:
310 - If set to V(true), the cluster will be removed from global DB.
311 - Parameters O(global_cluster_identifier), O(db_cluster_identifier) must be specified when O(remove_from_global_db=true).
312 type: bool
313 required: false
314 version_added: 6.5.0
315 replication_source_identifier:
316 description:
317 - The Amazon Resource Name (ARN) of the source DB instance or DB cluster if this DB cluster is created as a Read Replica.
318 aliases:
319 - replication_src_id
320 type: str
321 restore_to_time:
322 description:
323 - The UTC date and time to restore the DB cluster to. Must be in the format "2015-03-07T23:45:00Z".
324 - If this is not provided while restoring a cluster, O(use_latest_restorable_time) must be.
325 May not be specified if O(restore_type) is copy-on-write.
326 type: str
327 restore_type:
328 description:
329 - The type of restore to be performed. If not provided, Amazon RDS uses full-copy.
330 choices:
331 - full-copy
332 - copy-on-write
333 type: str
334 role_arn:
335 description:
336 - The Amazon Resource Name (ARN) of the IAM role to associate with the Aurora DB cluster, for example
337 "arn:aws:iam::123456789012:role/AuroraAccessRole"
338 type: str
339 s3_bucket_name:
340 description:
341 - The name of the Amazon S3 bucket that contains the data used to create the Amazon Aurora DB cluster.
342 type: str
343 s3_ingestion_role_arn:
344 description:
345 - The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that authorizes Amazon RDS to access
346 the Amazon S3 bucket on your behalf.
347 type: str
348 s3_prefix:
349 description:
350 - The prefix for all of the file names that contain the data used to create the Amazon Aurora DB cluster.
351 - If you do not specify a SourceS3Prefix value, then the Amazon Aurora DB cluster is created by using all of the files in the Amazon S3 bucket.
352 type: str
353 serverless_v2_scaling_configuration:
354 description:
355 - Contains the scaling configuration of an Aurora Serverless v2 DB cluster.
356 type: dict
357 suboptions:
358 min_capacity:
359 description:
360 - The minimum number of Aurora capacity units (ACUs) for a DB instance in an Aurora Serverless v2 cluster.
361 - ACU values can be specified in in half-step increments, such as V(8), V(8.5), V(9), and so on.
362 - The smallest possible value is V(0.5).
363 type: float
364 max_capacity:
365 description:
366 - The maximum number of Aurora capacity units (ACUs) for a DB instance in an Aurora Serverless v2 cluster.
367 - ACU values can be specified in in half-step increments, such as V(40), V(40.5), V(41), and so on.
368 - The largest possible value is V(128).
369 type: float
370 version_added: 7.3.0
371 skip_final_snapshot:
372 description:
373 - Whether a final DB cluster snapshot is created before the DB cluster is deleted.
374 - If this is V(false), O(final_snapshot_identifier) must be provided.
375 type: bool
376 default: false
377 snapshot_identifier:
378 description:
379 - The identifier for the DB snapshot or DB cluster snapshot to restore from.
380 - You can use either the name or the ARN to specify a DB cluster snapshot. However, you can use only the ARN to specify a DB snapshot.
381 type: str
382 source_db_cluster_identifier:
383 description:
384 - The identifier of the source DB cluster from which to restore.
385 type: str
386 source_engine:
387 description:
388 - The identifier for the database engine that was backed up to create the files stored in the Amazon S3 bucket.
389 choices:
390 - mysql
391 type: str
392 source_engine_version:
393 description:
394 - The version of the database that the backup files were created from.
395 type: str
396 source_region:
397 description:
398 - The ID of the region that contains the source for the DB cluster.
399 type: str
400 storage_encrypted:
401 description:
402 - Whether the DB cluster is encrypted.
403 type: bool
404 use_earliest_time_on_point_in_time_unavailable:
405 description:
406 - If O(backtrack_to) is set to a timestamp earlier than the earliest backtrack time, this value backtracks the DB cluster to
407 the earliest possible backtrack time. Otherwise, an error occurs.
408 type: bool
409 use_latest_restorable_time:
410 description:
411 - Whether to restore the DB cluster to the latest restorable backup time. Only one of O(use_latest_restorable_time)
412 and O(restore_to_time) may be provided.
413 type: bool
414 vpc_security_group_ids:
415 description:
416 - A list of EC2 VPC security groups to associate with the DB cluster.
417 type: list
418 elements: str
419 """
420
421 EXAMPLES = r"""
422 # Note: These examples do not set authentication details, see the AWS Guide for details.
423 - name: Create minimal Aurora cluster in default VPC and default subnet group
424 amazon.aws.rds_cluster:
425 cluster_id: "{{ cluster_id }}"
426 engine: "aurora"
427 password: "{{ password }}"
428 username: "{{ username }}"
429
430 - name: Add a new security group without purge
431 amazon.aws.rds_cluster:
432 id: "{{ cluster_id }}"
433 state: present
434 vpc_security_group_ids:
435 - sg-0be17ba10c9286b0b
436 purge_security_groups: false
437
438 - name: Modify password
439 amazon.aws.rds_cluster:
440 id: "{{ cluster_id }}"
441 state: present
442 password: "{{ new_password }}"
443 force_update_password: true
444 apply_immediately: true
445
446 - name: Rename the cluster
447 amazon.aws.rds_cluster:
448 engine: aurora
449 password: "{{ password }}"
450 username: "{{ username }}"
451 cluster_id: "cluster-{{ resource_prefix }}"
452 new_cluster_id: "cluster-{{ resource_prefix }}-renamed"
453 apply_immediately: true
454
455 - name: Delete Aurora cluster without creating a final snapshot
456 amazon.aws.rds_cluster:
457 engine: aurora
458 password: "{{ password }}"
459 username: "{{ username }}"
460 cluster_id: "{{ cluster_id }}"
461 skip_final_snapshot: true
462 tags:
463 Name: "cluster-{{ resource_prefix }}"
464 Created_By: "Ansible_rds_cluster_integration_test"
465 state: absent
466
467 - name: Restore cluster from source snapshot
468 amazon.aws.rds_cluster:
469 engine: aurora
470 password: "{{ password }}"
471 username: "{{ username }}"
472 cluster_id: "cluster-{{ resource_prefix }}-restored"
473 snapshot_identifier: "cluster-{{ resource_prefix }}-snapshot"
474
475 - name: Create an Aurora PostgreSQL cluster and attach an intance
476 amazon.aws.rds_cluster:
477 state: present
478 engine: aurora-postgresql
479 engine_mode: provisioned
480 cluster_id: '{{ cluster_id }}'
481 username: '{{ username }}'
482 password: '{{ password }}'
483
484 - name: Attach a new instance to the cluster
485 amazon.aws.rds_instance:
486 id: '{{ instance_id }}'
487 cluster_id: '{{ cluster_id }}'
488 engine: aurora-postgresql
489 state: present
490 db_instance_class: 'db.t3.medium'
491
492 - name: Remove a cluster from global DB (do not delete)
493 amazon.aws.rds_cluster:
494 db_cluster_identifier: '{{ cluster_id }}'
495 global_cluster_identifier: '{{ global_cluster_id }}'
496 remove_from_global_db: true
497
498 - name: Remove a cluster from global DB and Delete without creating a final snapshot
499 amazon.aws.rds_cluster:
500 engine: aurora
501 password: "{{ password }}"
502 username: "{{ username }}"
503 cluster_id: "{{ cluster_id }}"
504 skip_final_snapshot: true
505 remove_from_global_db: true
506 wait: true
507 state: absent
508
509 - name: Update cluster port and WAIT for remove secondary DB cluster from global DB to complete
510 amazon.aws.rds_cluster:
511 db_cluster_identifier: "{{ secondary_cluster_name }}"
512 global_cluster_identifier: "{{ global_cluster_name }}"
513 remove_from_global_db: true
514 state: present
515 port: 3389
516 region: "{{ secondary_cluster_region }}"
517
518 - name: Update cluster port and DO NOT WAIT for remove secondary DB cluster from global DB to complete
519 amazon.aws.rds_cluster:
520 db_cluster_identifier: "{{ secondary_cluster_name }}"
521 global_cluster_identifier: "{{ global_cluster_name }}"
522 remove_from_global_db: true
523 state: present
524 port: 3389
525 region: "{{ secondary_cluster_region }}"
526 wait: false
527 """
528
529 RETURN = r"""
530 activity_stream_status:
531 description: The status of the database activity stream.
532 returned: always
533 type: str
534 sample: "stopped"
535 allocated_storage:
536 description:
537 - The allocated storage size in gigabytes. Since aurora storage size is not fixed this is
538 always 1 for aurora database engines.
539 returned: always
540 type: int
541 sample: 1
542 associated_roles:
543 description:
544 - A list of dictionaries of the AWS Identity and Access Management (IAM) roles that are associated
545 with the DB cluster. Each dictionary contains the role_arn and the status of the role.
546 returned: always
547 type: list
548 sample: []
549 auto_minor_version_upgrade:
550 description: Specifies whether minor engine upgrades are applied automatically to the DB cluster during the maintenance window.
551 returned: always
552 type: bool
553 sample: true
554 availability_zones:
555 description: The list of availability zones that instances in the DB cluster can be created in.
556 returned: always
557 type: list
558 sample:
559 - us-east-1c
560 - us-east-1a
561 - us-east-1e
562 backup_retention_period:
563 description: The number of days for which automatic DB snapshots are retained.
564 returned: always
565 type: int
566 sample: 1
567 changed:
568 description: If the RDS cluster has changed.
569 returned: always
570 type: bool
571 sample: true
572 cluster_create_time:
573 description: The time in UTC when the DB cluster was created.
574 returned: always
575 type: str
576 sample: "2018-06-29T14:08:58.491000+00:00"
577 copy_tags_to_snapshot:
578 description:
579 - Specifies whether tags are copied from the DB cluster to snapshots of the DB cluster.
580 returned: always
581 type: bool
582 sample: false
583 cross_account_clone:
584 description:
585 - Specifies whether the DB cluster is a clone of a DB cluster owned by a different Amazon Web Services account.
586 returned: always
587 type: bool
588 sample: false
589 db_cluster_arn:
590 description: The Amazon Resource Name (ARN) for the DB cluster.
591 returned: always
592 type: str
593 sample: arn:aws:rds:us-east-1:123456789012:cluster:rds-cluster-demo
594 db_cluster_identifier:
595 description: The lowercase user-supplied DB cluster identifier.
596 returned: always
597 type: str
598 sample: "rds-cluster-demo"
599 db_cluster_members:
600 description:
601 - A list of dictionaries containing information about the instances in the cluster.
602 Each dictionary contains the db_instance_identifier, is_cluster_writer (bool),
603 db_cluster_parameter_group_status, and promotion_tier (int).
604 returned: always
605 type: list
606 sample: []
607 db_cluster_parameter_group:
608 description: The parameter group associated with the DB cluster.
609 returned: always
610 type: str
611 sample: "default.aurora5.6"
612 db_cluster_resource_id:
613 description: The AWS Region-unique, immutable identifier for the DB cluster.
614 returned: always
615 type: str
616 sample: "cluster-D2MEQDN3BQNXDF74K6DQJTHASU"
617 db_subnet_group:
618 description: The name of the subnet group associated with the DB Cluster.
619 returned: always
620 type: str
621 sample: "default"
622 deletion_protection:
623 description:
624 - Indicates if the DB cluster has deletion protection enabled.
625 The database can't be deleted when deletion protection is enabled.
626 returned: always
627 type: bool
628 sample: false
629 domain_memberships:
630 description:
631 - The Active Directory Domain membership records associated with the DB cluster.
632 returned: always
633 type: list
634 sample: []
635 earliest_restorable_time:
636 description: The earliest time to which a database can be restored with point-in-time restore.
637 returned: always
638 type: str
639 sample: "2018-06-29T14:09:34.797000+00:00"
640 endpoint:
641 description: The connection endpoint for the primary instance of the DB cluster.
642 returned: always
643 type: str
644 sample: "rds-cluster-demo.cluster-cvlrtwiennww.us-east-1.rds.amazonaws.com"
645 engine:
646 description: The database engine of the DB cluster.
647 returned: always
648 type: str
649 sample: "aurora"
650 engine_mode:
651 description: The DB engine mode of the DB cluster.
652 returned: always
653 type: str
654 sample: "provisioned"
655 engine_version:
656 description: The database engine version.
657 returned: always
658 type: str
659 sample: "5.6.10a"
660 hosted_zone_id:
661 description: The ID that Amazon Route 53 assigns when you create a hosted zone.
662 returned: always
663 type: str
664 sample: "Z2R2ITUGPM61AM"
665 http_endpoint_enabled:
666 description:
667 - A value that indicates whether the HTTP endpoint for an Aurora Serverless DB cluster is enabled.
668 returned: always
669 type: bool
670 sample: false
671 iam_database_authentication_enabled:
672 description: Whether IAM accounts may be mapped to database accounts.
673 returned: always
674 type: bool
675 sample: false
676 latest_restorable_time:
677 description: The latest time to which a database can be restored with point-in-time restore.
678 returned: always
679 type: str
680 sample: "2018-06-29T14:09:34.797000+00:00"
681 master_username:
682 description: The master username for the DB cluster.
683 returned: always
684 type: str
685 sample: "username"
686 multi_az:
687 description: Whether the DB cluster has instances in multiple availability zones.
688 returned: always
689 type: bool
690 sample: false
691 port:
692 description: The port that the database engine is listening on.
693 returned: always
694 type: int
695 sample: 3306
696 preferred_backup_window:
697 description: The UTC weekly time range during which system maintenance can occur.
698 returned: always
699 type: str
700 sample: "10:18-10:48"
701 preferred_maintenance_window:
702 description: The UTC weekly time range during which system maintenance can occur.
703 returned: always
704 type: str
705 sample: "tue:03:23-tue:03:53"
706 read_replica_identifiers:
707 description: A list of read replica ID strings associated with the DB cluster.
708 returned: always
709 type: list
710 sample: []
711 reader_endpoint:
712 description: The reader endpoint for the DB cluster.
713 returned: always
714 type: str
715 sample: "rds-cluster-demo.cluster-ro-cvlrtwiennww.us-east-1.rds.amazonaws.com"
716 serverless_v2_scaling_configuration:
717 description: The scaling configuration for an Aurora Serverless v2 DB cluster.
718 returned: when configured
719 type: dict
720 sample: {
721 "max_capacity": 4.5,
722 "min_capacity": 2.5
723 }
724 version_added: 7.3.0
725 status:
726 description: The status of the DB cluster.
727 returned: always
728 type: str
729 sample: "available"
730 storage_encrypted:
731 description: Whether the DB cluster is storage encrypted.
732 returned: always
733 type: bool
734 sample: false
735 tag_list:
736 description: A list of tags consisting of key-value pairs.
737 returned: always
738 type: list
739 elements: dict
740 sample: [
741 {
742 "key": "Created_By",
743 "value": "Ansible_rds_cluster_integration_test"
744 }
745 ]
746 tags:
747 description: A dictionary of key value pairs.
748 returned: always
749 type: dict
750 sample: {
751 "Name": "rds-cluster-demo"
752 }
753 vpc_security_groups:
754 description: A list of the DB cluster's security groups and their status.
755 returned: always
756 type: complex
757 contains:
758 status:
759 description: Status of the security group.
760 returned: always
761 type: str
762 sample: "active"
763 vpc_security_group_id:
764 description: Security group of the cluster.
765 returned: always
766 type: str
767 sample: "sg-12345678"
768 """
769
770 try:
771 import botocore
772 except ImportError:
773 pass # caught by AnsibleAWSModule
774
775 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
776
777 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
778 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
779 from ansible_collections.amazon.aws.plugins.module_utils.rds import arg_spec_to_rds_params
780 from ansible_collections.amazon.aws.plugins.module_utils.rds import call_method
781 from ansible_collections.amazon.aws.plugins.module_utils.rds import ensure_tags
782 from ansible_collections.amazon.aws.plugins.module_utils.rds import get_tags
783 from ansible_collections.amazon.aws.plugins.module_utils.rds import wait_for_cluster_status
784 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
785 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
786
787
788 @AWSRetry.jittered_backoff(retries=10)
789 def _describe_db_clusters(**params):
790 try:
791 paginator = client.get_paginator("describe_db_clusters")
792 return paginator.paginate(**params).build_full_result()["DBClusters"][0]
793 except is_boto3_error_code("DBClusterNotFoundFault"):
794 return {}
795
796
797 def get_add_role_options(params_dict, cluster):
798 current_role_arns = [role["RoleArn"] for role in cluster.get("AssociatedRoles", [])]
799 role = params_dict["RoleArn"]
800 if role is not None and role not in current_role_arns:
801 return {"RoleArn": role, "DBClusterIdentifier": params_dict["DBClusterIdentifier"]}
802 return {}
803
804
805 def get_backtrack_options(params_dict):
806 options = ["BacktrackTo", "DBClusterIdentifier", "UseEarliestTimeOnPointInTimeUnavailable"]
807 if params_dict["BacktrackTo"] is not None:
808 options = dict((k, params_dict[k]) for k in options if params_dict[k] is not None)
809 if "ForceBacktrack" in params_dict:
810 options["Force"] = params_dict["ForceBacktrack"]
811 return options
812 return {}
813
814
815 def get_create_options(params_dict):
816 options = [
817 "AvailabilityZones",
818 "BacktrackWindow",
819 "BackupRetentionPeriod",
820 "PreferredBackupWindow",
821 "CharacterSetName",
822 "DBClusterIdentifier",
823 "DBClusterParameterGroupName",
824 "DBSubnetGroupName",
825 "DatabaseName",
826 "EnableCloudwatchLogsExports",
827 "EnableIAMDatabaseAuthentication",
828 "KmsKeyId",
829 "Engine",
830 "EngineMode",
831 "EngineVersion",
832 "PreferredMaintenanceWindow",
833 "MasterUserPassword",
834 "MasterUsername",
835 "OptionGroupName",
836 "Port",
837 "ReplicationSourceIdentifier",
838 "SourceRegion",
839 "StorageEncrypted",
840 "Tags",
841 "VpcSecurityGroupIds",
842 "EngineMode",
843 "ScalingConfiguration",
844 "DeletionProtection",
845 "EnableHttpEndpoint",
846 "CopyTagsToSnapshot",
847 "Domain",
848 "DomainIAMRoleName",
849 "EnableGlobalWriteForwarding",
850 "GlobalClusterIdentifier",
851 "AllocatedStorage",
852 "DBClusterInstanceClass",
853 "StorageType",
854 "Iops",
855 "EngineMode",
856 "ServerlessV2ScalingConfiguration",
857 ]
858
859 return dict((k, v) for k, v in params_dict.items() if k in options and v is not None)
860
861
862 def get_modify_options(params_dict, force_update_password):
863 options = [
864 "ApplyImmediately",
865 "BacktrackWindow",
866 "BackupRetentionPeriod",
867 "PreferredBackupWindow",
868 "DBClusterIdentifier",
869 "DBClusterParameterGroupName",
870 "EnableIAMDatabaseAuthentication",
871 "EngineVersion",
872 "PreferredMaintenanceWindow",
873 "MasterUserPassword",
874 "NewDBClusterIdentifier",
875 "OptionGroupName",
876 "Port",
877 "VpcSecurityGroupIds",
878 "EnableIAMDatabaseAuthentication",
879 "CloudwatchLogsExportConfiguration",
880 "DeletionProtection",
881 "EnableHttpEndpoint",
882 "CopyTagsToSnapshot",
883 "EnableGlobalWriteForwarding",
884 "Domain",
885 "DomainIAMRoleName",
886 "AllocatedStorage",
887 "DBClusterInstanceClass",
888 "StorageType",
889 "Iops",
890 "EngineMode",
891 "ServerlessV2ScalingConfiguration",
892 ]
893 modify_options = dict((k, v) for k, v in params_dict.items() if k in options and v is not None)
894 if not force_update_password:
895 modify_options.pop("MasterUserPassword", None)
896 return modify_options
897
898
899 def get_delete_options(params_dict):
900 options = ["DBClusterIdentifier", "FinalSnapshotIdentifier", "SkipFinalSnapshot"]
901 return dict((k, params_dict[k]) for k in options if params_dict[k] is not None)
902
903
904 def get_restore_s3_options(params_dict):
905 options = [
906 "AvailabilityZones",
907 "BacktrackWindow",
908 "BackupRetentionPeriod",
909 "CharacterSetName",
910 "DBClusterIdentifier",
911 "DBClusterParameterGroupName",
912 "DBSubnetGroupName",
913 "DatabaseName",
914 "EnableCloudwatchLogsExports",
915 "EnableIAMDatabaseAuthentication",
916 "Engine",
917 "EngineVersion",
918 "KmsKeyId",
919 "MasterUserPassword",
920 "MasterUsername",
921 "OptionGroupName",
922 "Port",
923 "PreferredBackupWindow",
924 "PreferredMaintenanceWindow",
925 "S3BucketName",
926 "S3IngestionRoleArn",
927 "S3Prefix",
928 "SourceEngine",
929 "SourceEngineVersion",
930 "StorageEncrypted",
931 "Tags",
932 "VpcSecurityGroupIds",
933 "DeletionProtection",
934 "EnableHttpEndpoint",
935 "CopyTagsToSnapshot",
936 "Domain",
937 "DomainIAMRoleName",
938 ]
939
940 return dict((k, v) for k, v in params_dict.items() if k in options and v is not None)
941
942
943 def get_restore_snapshot_options(params_dict):
944 options = [
945 "AvailabilityZones",
946 "BacktrackWindow",
947 "DBClusterIdentifier",
948 "DBSubnetGroupName",
949 "DatabaseName",
950 "EnableCloudwatchLogsExports",
951 "EnableIAMDatabaseAuthentication",
952 "Engine",
953 "EngineVersion",
954 "KmsKeyId",
955 "OptionGroupName",
956 "Port",
957 "SnapshotIdentifier",
958 "Tags",
959 "VpcSecurityGroupIds",
960 "DBClusterParameterGroupName",
961 "DeletionProtection",
962 "CopyTagsToSnapshot",
963 "Domain",
964 "DomainIAMRoleName",
965 ]
966 return dict((k, v) for k, v in params_dict.items() if k in options and v is not None)
967
968
969 def get_restore_cluster_options(params_dict):
970 options = [
971 "BacktrackWindow",
972 "DBClusterIdentifier",
973 "DBSubnetGroupName",
974 "EnableCloudwatchLogsExports",
975 "EnableIAMDatabaseAuthentication",
976 "KmsKeyId",
977 "OptionGroupName",
978 "Port",
979 "RestoreToTime",
980 "RestoreType",
981 "SourceDBClusterIdentifier",
982 "Tags",
983 "UseLatestRestorableTime",
984 "VpcSecurityGroupIds",
985 "DeletionProtection",
986 "CopyTagsToSnapshot",
987 "Domain",
988 "DomainIAMRoleName",
989 ]
990 return dict((k, v) for k, v in params_dict.items() if k in options and v is not None)
991
992
993 def get_rds_method_attribute_name(cluster):
994 state = module.params["state"]
995 creation_source = module.params["creation_source"]
996 method_name = None
997 method_options_name = None
998
999 if state == "absent":
1000 if cluster and cluster["Status"] not in ["deleting", "deleted"]:
1001 method_name = "delete_db_cluster"
1002 method_options_name = "get_delete_options"
1003 elif state == "started":
1004 if cluster and cluster["Status"] not in ["starting", "started", "available"]:
1005 method_name = "start_db_cluster"
1006 method_options_name = "get_modify_options"
1007 elif state == "stopped":
1008 if cluster and cluster["Status"] not in ["stopping", "stopped"]:
1009 method_name = "stop_db_cluster"
1010 method_options_name = "get_modify_options"
1011 else:
1012 if cluster:
1013 method_name = "modify_db_cluster"
1014 method_options_name = "get_modify_options"
1015 elif creation_source == "snapshot":
1016 method_name = "restore_db_cluster_from_snapshot"
1017 method_options_name = "get_restore_snapshot_options"
1018 elif creation_source == "s3":
1019 method_name = "restore_db_cluster_from_s3"
1020 method_options_name = "get_restore_s3_options"
1021 elif creation_source == "cluster":
1022 method_name = "restore_db_cluster_to_point_in_time"
1023 method_options_name = "get_restore_cluster_options"
1024 else:
1025 method_name = "create_db_cluster"
1026 method_options_name = "get_create_options"
1027
1028 return method_name, method_options_name
1029
1030
1031 def add_role(params):
1032 if not module.check_mode:
1033 try:
1034 client.add_role_to_db_cluster(**params)
1035 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
1036 module.fail_json_aws(
1037 e, msg=f"Unable to add role {params['RoleArn']} to cluster {params['DBClusterIdentifier']}"
1038 )
1039 wait_for_cluster_status(client, module, params["DBClusterIdentifier"], "cluster_available")
1040
1041
1042 def backtrack_cluster(params):
1043 if not module.check_mode:
1044 try:
1045 client.backtrack_db_cluster(**params)
1046 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
1047 module.fail_json_aws(e, msg=f"Unable to backtrack cluster {params['DBClusterIdentifier']}")
1048 wait_for_cluster_status(client, module, params["DBClusterIdentifier"], "cluster_available")
1049
1050
1051 def get_cluster(db_cluster_id):
1052 try:
1053 return _describe_db_clusters(DBClusterIdentifier=db_cluster_id)
1054 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
1055 module.fail_json_aws(e, msg="Failed to describe DB clusters")
1056
1057
1058 def changing_cluster_options(modify_params, current_cluster):
1059 changing_params = {}
1060 apply_immediately = modify_params.pop("ApplyImmediately")
1061 db_cluster_id = modify_params.pop("DBClusterIdentifier")
1062
1063 enable_cloudwatch_logs_export = modify_params.pop("EnableCloudwatchLogsExports", None)
1064 if enable_cloudwatch_logs_export is not None:
1065 desired_cloudwatch_logs_configuration = {"EnableLogTypes": [], "DisableLogTypes": []}
1066 provided_cloudwatch_logs = set(enable_cloudwatch_logs_export)
1067 current_cloudwatch_logs_export = set(current_cluster["EnabledCloudwatchLogsExports"])
1068
1069 desired_cloudwatch_logs_configuration["EnableLogTypes"] = sorted(
1070 list(provided_cloudwatch_logs.difference(current_cloudwatch_logs_export))
1071 )
1072 if module.params["purge_cloudwatch_logs_exports"]:
1073 desired_cloudwatch_logs_configuration["DisableLogTypes"] = sorted(
1074 list(current_cloudwatch_logs_export.difference(provided_cloudwatch_logs))
1075 )
1076 if (
1077 desired_cloudwatch_logs_configuration["EnableLogTypes"]
1078 or desired_cloudwatch_logs_configuration["DisableLogTypes"]
1079 ):
1080 changing_params["CloudwatchLogsExportConfiguration"] = desired_cloudwatch_logs_configuration
1081
1082 password = modify_params.pop("MasterUserPassword", None)
1083 if password:
1084 changing_params["MasterUserPassword"] = password
1085
1086 new_cluster_id = modify_params.pop("NewDBClusterIdentifier", None)
1087 if new_cluster_id and new_cluster_id != current_cluster["DBClusterIdentifier"]:
1088 changing_params["NewDBClusterIdentifier"] = new_cluster_id
1089
1090 option_group = modify_params.pop("OptionGroupName", None)
1091 if option_group and option_group not in [
1092 g["DBClusterOptionGroupName"] for g in current_cluster["DBClusterOptionGroupMemberships"]
1093 ]:
1094 changing_params["OptionGroupName"] = option_group
1095
1096 vpc_sgs = modify_params.pop("VpcSecurityGroupIds", None)
1097 if vpc_sgs:
1098 desired_vpc_sgs = []
1099 provided_vpc_sgs = set(vpc_sgs)
1100 current_vpc_sgs = set([sg["VpcSecurityGroupId"] for sg in current_cluster["VpcSecurityGroups"]])
1101 if module.params["purge_security_groups"]:
1102 desired_vpc_sgs = sorted(list(provided_vpc_sgs))
1103 else:
1104 if provided_vpc_sgs - current_vpc_sgs:
1105 desired_vpc_sgs = sorted(list(provided_vpc_sgs | current_vpc_sgs))
1106
1107 if desired_vpc_sgs:
1108 changing_params["VpcSecurityGroupIds"] = desired_vpc_sgs
1109
1110 desired_db_cluster_parameter_group = modify_params.pop("DBClusterParameterGroupName", None)
1111 if desired_db_cluster_parameter_group:
1112 if desired_db_cluster_parameter_group != current_cluster["DBClusterParameterGroup"]:
1113 changing_params["DBClusterParameterGroupName"] = desired_db_cluster_parameter_group
1114
1115 for param in modify_params:
1116 # describe_db_clusters does not return StorageType for clusters with storage config as "aurora standard"
1117 if param == "StorageType":
1118 changing_params[param] = modify_params[param]
1119 continue
1120 # describe_db_clusters returns the Domain member ship information as follow
1121 # 'DomainMemberships': [
1122 # {
1123 # 'Domain': 'string',
1124 # 'Status': 'string',
1125 # 'FQDN': 'string',
1126 # 'IAMRoleName': 'string'
1127 # },
1128 # ]
1129 if param in ("Domain", "DomainIAMRoleName"):
1130 n_domain = modify_params.get("Domain")
1131 n_domain_iam_role_name = modify_params.get("DomainIAMRoleName")
1132 if not any(
1133 n_domain == d.get("Domain") and n_domain_iam_role_name == d.get("IAMRoleName")
1134 for d in current_cluster.get("DomainMemberships", [])
1135 ):
1136 changing_params[param] = modify_params[param]
1137 continue
1138 if modify_params[param] != current_cluster[param]:
1139 changing_params[param] = modify_params[param]
1140
1141 if changing_params:
1142 changing_params["DBClusterIdentifier"] = db_cluster_id
1143 if apply_immediately is not None:
1144 changing_params["ApplyImmediately"] = apply_immediately
1145
1146 if module.params["state"] == "started":
1147 if current_cluster["Engine"] in ["mysql", "postgres"]:
1148 module.fail_json("Only aurora clusters can use the state started")
1149 # start_db_cluster supports only DBClusterIdentifier
1150 changing_params = {}
1151 changing_params["DBClusterIdentifier"] = db_cluster_id
1152
1153 if module.params["state"] == "stopped":
1154 if current_cluster["Engine"] in ["mysql", "postgres"]:
1155 module.fail_json("Only aurora clusters can use the state stopped")
1156 # stop_db_cluster supports only DBClusterIdentifier
1157 changing_params = {}
1158 changing_params["DBClusterIdentifier"] = db_cluster_id
1159
1160 return changing_params
1161
1162
1163 def ensure_present(cluster, parameters, method_name, method_options_name):
1164 changed = False
1165
1166 if not cluster:
1167 if parameters.get("Tags") is not None:
1168 parameters["Tags"] = ansible_dict_to_boto3_tag_list(parameters["Tags"])
1169
1170 call_method(client, module, method_name, eval(method_options_name)(parameters))
1171 changed = True
1172 else:
1173 if get_backtrack_options(parameters):
1174 backtrack_cluster(client, module, get_backtrack_options(parameters))
1175 changed = True
1176 else:
1177 modifiable_options = eval(method_options_name)(
1178 parameters, force_update_password=module.params["force_update_password"]
1179 )
1180 modify_options = changing_cluster_options(modifiable_options, cluster)
1181 if modify_options:
1182 call_method(client, module, method_name, modify_options)
1183 changed = True
1184 if module.params["tags"] is not None:
1185 existing_tags = get_tags(client, module, cluster["DBClusterArn"])
1186 changed |= ensure_tags(
1187 client,
1188 module,
1189 cluster["DBClusterArn"],
1190 existing_tags,
1191 module.params["tags"],
1192 module.params["purge_tags"],
1193 )
1194
1195 add_role_params = get_add_role_options(parameters, cluster)
1196 if add_role_params:
1197 add_role(client, module, add_role_params)
1198 changed = True
1199
1200 if module.params["promote"] and cluster.get("ReplicationSourceIdentifier"):
1201 call_method(
1202 client,
1203 module,
1204 "promote_read_replica_db_cluster",
1205 parameters={"DBClusterIdentifier": module.params["db_cluster_identifier"]},
1206 )
1207 changed = True
1208
1209 return changed
1210
1211
1212 def handle_remove_from_global_db(cluster):
1213 global_cluster_id = module.params.get("global_cluster_identifier")
1214 db_cluster_id = module.params.get("db_cluster_identifier")
1215 db_cluster_arn = cluster["DBClusterArn"]
1216
1217 if module.check_mode:
1218 return True
1219
1220 try:
1221 client.remove_from_global_cluster(DbClusterIdentifier=db_cluster_arn, GlobalClusterIdentifier=global_cluster_id)
1222 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
1223 module.fail_json_aws(
1224 e, msg=f"Failed to remove cluster {db_cluster_id} from global DB cluster {global_cluster_id}."
1225 )
1226
1227 # for replica cluster - wait for cluster to change status from 'available' to 'promoting'
1228 # only replica/secondary clusters have "GlobalWriteForwardingStatus" field
1229 if "GlobalWriteForwardingStatus" in cluster:
1230 wait_for_cluster_status(client, module, db_cluster_id, "db_cluster_promoting")
1231
1232 # if wait=true, wait for db cluster remove from global db operation to complete
1233 if module.params.get("wait"):
1234 wait_for_cluster_status(client, module, db_cluster_id, "cluster_available")
1235
1236 return True
1237
1238
1239 def main():
1240 global module
1241 global client
1242
1243 arg_spec = dict(
1244 state=dict(choices=["present", "absent", "started", "stopped"], default="present"),
1245 creation_source=dict(type="str", choices=["snapshot", "s3", "cluster"]),
1246 force_update_password=dict(type="bool", default=False),
1247 promote=dict(type="bool", default=False),
1248 purge_cloudwatch_logs_exports=dict(type="bool", default=True),
1249 purge_tags=dict(type="bool", default=True),
1250 wait=dict(type="bool", default=True),
1251 purge_security_groups=dict(type="bool", default=True),
1252 )
1253
1254 parameter_options = dict(
1255 apply_immediately=dict(type="bool", default=False),
1256 availability_zones=dict(type="list", elements="str", aliases=["zones", "az"]),
1257 backtrack_to=dict(),
1258 backtrack_window=dict(type="int"),
1259 backup_retention_period=dict(type="int", default=1),
1260 character_set_name=dict(),
1261 database_name=dict(aliases=["db_name"]),
1262 db_cluster_identifier=dict(required=True, aliases=["cluster_id", "id", "cluster_name"]),
1263 db_cluster_parameter_group_name=dict(),
1264 db_subnet_group_name=dict(),
1265 enable_cloudwatch_logs_exports=dict(type="list", elements="str"),
1266 deletion_protection=dict(type="bool"),
1267 global_cluster_identifier=dict(),
1268 enable_http_endpoint=dict(type="bool"),
1269 copy_tags_to_snapshot=dict(type="bool"),
1270 domain=dict(),
1271 domain_iam_role_name=dict(),
1272 enable_global_write_forwarding=dict(type="bool"),
1273 db_cluster_instance_class=dict(type="str"),
1274 enable_iam_database_authentication=dict(type="bool"),
1275 engine=dict(choices=["aurora", "aurora-mysql", "aurora-postgresql", "mysql", "postgres"]),
1276 engine_mode=dict(choices=["provisioned", "serverless", "parallelquery", "global", "multimaster"]),
1277 engine_version=dict(),
1278 allocated_storage=dict(type="int"),
1279 storage_type=dict(type="str", choices=["io1", "aurora", "aurora-iopt1"]),
1280 iops=dict(type="int"),
1281 final_snapshot_identifier=dict(),
1282 force_backtrack=dict(type="bool"),
1283 kms_key_id=dict(),
1284 master_user_password=dict(aliases=["password"], no_log=True),
1285 master_username=dict(aliases=["username"]),
1286 new_db_cluster_identifier=dict(aliases=["new_cluster_id", "new_id", "new_cluster_name"]),
1287 option_group_name=dict(),
1288 port=dict(type="int"),
1289 preferred_backup_window=dict(aliases=["backup_window"]),
1290 preferred_maintenance_window=dict(aliases=["maintenance_window"]),
1291 remove_from_global_db=dict(type="bool"),
1292 replication_source_identifier=dict(aliases=["replication_src_id"]),
1293 restore_to_time=dict(),
1294 restore_type=dict(choices=["full-copy", "copy-on-write"]),
1295 role_arn=dict(),
1296 s3_bucket_name=dict(),
1297 s3_ingestion_role_arn=dict(),
1298 s3_prefix=dict(),
1299 serverless_v2_scaling_configuration=dict(
1300 type="dict",
1301 options=dict(
1302 min_capacity=dict(type="float"),
1303 max_capacity=dict(type="float"),
1304 ),
1305 ),
1306 skip_final_snapshot=dict(type="bool", default=False),
1307 snapshot_identifier=dict(),
1308 source_db_cluster_identifier=dict(),
1309 source_engine=dict(choices=["mysql"]),
1310 source_engine_version=dict(),
1311 source_region=dict(),
1312 storage_encrypted=dict(type="bool"),
1313 tags=dict(type="dict", aliases=["resource_tags"]),
1314 use_earliest_time_on_point_in_time_unavailable=dict(type="bool"),
1315 use_latest_restorable_time=dict(type="bool"),
1316 vpc_security_group_ids=dict(type="list", elements="str"),
1317 )
1318 arg_spec.update(parameter_options)
1319
1320 required_by_s3_creation_source = [
1321 "s3_bucket_name",
1322 "engine",
1323 "master_username",
1324 "master_user_password",
1325 "source_engine",
1326 "source_engine_version",
1327 "s3_ingestion_role_arn",
1328 ]
1329
1330 module = AnsibleAWSModule(
1331 argument_spec=arg_spec,
1332 required_if=[
1333 ["creation_source", "snapshot", ["snapshot_identifier", "engine"]],
1334 ["creation_source", "s3", required_by_s3_creation_source],
1335 ["remove_from_global_db", True, ["global_cluster_identifier", "db_cluster_identifier"]],
1336 ],
1337 mutually_exclusive=[
1338 ["s3_bucket_name", "source_db_cluster_identifier", "snapshot_identifier"],
1339 ["use_latest_restorable_time", "restore_to_time"],
1340 ],
1341 supports_check_mode=True,
1342 )
1343
1344 retry_decorator = AWSRetry.jittered_backoff(retries=10)
1345
1346 try:
1347 client = module.client("rds", retry_decorator=retry_decorator)
1348 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
1349 module.fail_json_aws(e, msg="Failed to connect to AWS.")
1350
1351 if module.params.get("engine") and module.params["engine"] in ("mysql", "postgres"):
1352 if module.params["state"] == "present":
1353 if not (
1354 module.params.get("allocated_storage")
1355 and module.params.get("iops")
1356 and module.params.get("db_cluster_instance_class")
1357 ):
1358 module.fail_json(
1359 f"When engine={module.params['engine']} allocated_storage, iops and db_cluster_instance_class must be specified"
1360 )
1361 else:
1362 # Fall to default value
1363 if not module.params.get("storage_type"):
1364 module.params["storage_type"] = "io1"
1365
1366 if module.params.get("engine") and module.params["engine"] in ("aurora", "aurora-mysql", "aurora-postgresql"):
1367 if not module.check_mode and module.params.get("storage_type"):
1368 module.params["storage_type"] = "aurora"
1369
1370 if module.params.get("storage_type") and module.params["storage_type"] in ("aurora", "aurora-iopt1"):
1371 if module.params.get("engine") not in ("aurora", "aurora-mysql", "aurora-postgresql"):
1372 module.fail_json(
1373 f"storage_type={module.params['storage_type']} is only supported for aurora engines 'aurora', 'aurora-mysql', 'aurora-postgresql'"
1374 )
1375
1376 module.params["db_cluster_identifier"] = module.params["db_cluster_identifier"].lower()
1377 cluster = get_cluster(module.params["db_cluster_identifier"])
1378
1379 if module.params["new_db_cluster_identifier"]:
1380 module.params["new_db_cluster_identifier"] = module.params["new_db_cluster_identifier"].lower()
1381
1382 if get_cluster(module.params["new_db_cluster_identifier"]):
1383 module.fail_json(
1384 f"A new cluster ID {module.params['new_db_cluster_identifier']} was provided but it already exists"
1385 )
1386 if not cluster:
1387 module.fail_json(
1388 f"A new cluster ID {module.params['new_db_cluster_identifier']} was provided but the cluster to be renamed does not exist"
1389 )
1390
1391 if (
1392 module.params["state"] == "absent"
1393 and module.params["skip_final_snapshot"] is False
1394 and module.params["final_snapshot_identifier"] is None
1395 ):
1396 module.fail_json(
1397 msg="skip_final_snapshot is False but all of the following are missing: final_snapshot_identifier"
1398 )
1399
1400 changed = False
1401
1402 parameters = arg_spec_to_rds_params(dict((k, module.params[k]) for k in module.params if k in parameter_options))
1403 method_name, method_options_name = get_rds_method_attribute_name(cluster)
1404
1405 if method_name:
1406 if method_name == "delete_db_cluster":
1407 if cluster and module.params.get("remove_from_global_db"):
1408 if cluster["Engine"] in ["aurora", "aurora-mysql", "aurora-postgresql"]:
1409 changed = handle_remove_from_global_db(cluster)
1410
1411 call_method(client, module, method_name, eval(method_options_name)(parameters))
1412 changed = True
1413 else:
1414 changed |= ensure_present(cluster, parameters, method_name, method_options_name)
1415
1416 if not module.check_mode and module.params["new_db_cluster_identifier"] and module.params["apply_immediately"]:
1417 cluster_id = module.params["new_db_cluster_identifier"]
1418 else:
1419 cluster_id = module.params["db_cluster_identifier"]
1420
1421 if cluster_id and get_cluster(cluster_id) and module.params.get("remove_from_global_db"):
1422 if cluster["Engine"] in ["aurora", "aurora-mysql", "aurora-postgresql"]:
1423 if changed:
1424 wait_for_cluster_status(client, module, cluster_id, "cluster_available")
1425 changed |= handle_remove_from_global_db(cluster)
1426
1427 result = camel_dict_to_snake_dict(get_cluster(cluster_id))
1428
1429 if result:
1430 result["tags"] = get_tags(client, module, result["db_cluster_arn"])
1431
1432 module.exit_json(changed=changed, **result)
1433
1434
1435 if __name__ == "__main__":
1436 main()