
    Vh0                    J   d Z dZdZddlmZ ddlmZ ddlmZ ddlmZ ddlm	Z	 dd	l
mZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlm!Z! g dZ"g dZ#dede$de$de	e%   d e	e$   f
d!Z&d"ed#e$d ee$ef   fd$Z'd"ed%ee$ef   d&e$d ee$ef   fd'Z(d"ed%ee$ef   d ee$ef   fd(Z)dee$ef   d ee$ef   fd)Z*d*ee$ef   dee$ef   d+e%d,e%d ee$ef   f
d-Z+d*ee$ef   dee$ef   d ee$ef   fd.Z,d"edee$ef   d d/fd0Z-d"edee$ef   d1e$d e%fd2Z.d"edee$ef   de%d e%fd3Z/d"ed1e$d e%fd4Z0d"edee$ef   de$d e%fd5Z1d"edee$ef   d e%fd6Z2d"edee$ef   de$d e%fd7Z3d8 Z4e5d9k(  r e4        y/y/):aR  
---
module: rds_instance
version_added: 5.0.0
short_description: Manage RDS instances
description:
 - Create, modify, and delete RDS instances.
 - This module was originally added to C(community.aws) in release 1.0.0.
extends_documentation_fragment:
 - amazon.aws.common.modules
 - amazon.aws.region.modules
 - amazon.aws.tags
 - amazon.aws.boto3
author:
 - Sloane Hertel (@s-hertel)

options:
  # General module options
    state:
        description:
          - Desired state of the RDS Instance.
          - O(state=rebooted) is not idempotent and will leave the DB instance in a running state
            and start it prior to rebooting if it was stopped. V(present) will leave the DB instance in the current running/stopped state,
            (running if creating the DB instance).
          - O(state=running) and I(state=started) are synonyms, as are O(state=rebooted) and O(state=restarted).
        choices: ['present', 'absent', 'terminated', 'running', 'started', 'stopped', 'rebooted', 'restarted']
        default: 'present'
        type: str
    creation_source:
        description: Which source to use if restoring from a template (an existing instance, S3 bucket, or snapshot).
        choices: ['snapshot', 's3', 'instance']
        type: str
    force_update_password:
        description:
          - Set to V(true) to update your instance password with O(master_user_password). 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.
        type: bool
        default: false
    purge_cloudwatch_logs_exports:
        description:
          - Set to V(false) to retain any enabled cloudwatch logs that aren't specified in the task and are associated with the instance.
          - Set O(enable_cloudwatch_logs_exports) to an empty list to disable all.
        type: bool
        default: true
    read_replica:
        description:
          - 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
            be set to 'instance' or not provided. O(source_db_instance_identifier) must be provided with this option.
        type: bool
    wait:
        description:
          - Whether to wait for the instance to be available, stopped, or deleted. At a later time a I(wait_timeout) option may be added.
            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
            the expected state (available/stopped/deleted). The total task time may also be influenced by AWSRetry which helps stabilize if the
            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).
            If setting this to V(false) task retries and delays may make your playbook execution better handle timeouts for major modifications.
        type: bool
        default: true

    # Options that have a corresponding boto3 parameter
    allocated_storage:
        description:
          - The amount of storage (in gibibytes) to allocate for the DB instance.
        type: int
    allow_major_version_upgrade:
        description:
          - Whether to allow major version upgrades.
        type: bool
    apply_immediately:
        description:
          - A value that specifies whether modifying an instance with O(new_db_instance_identifier) and I(master_user_password)
            should be applied as soon as possible, regardless of the O(preferred_maintenance_window) setting. If V(false), changes
            are applied during the next maintenance window.
        type: bool
        default: false
    auto_minor_version_upgrade:
        description:
          - Whether minor version upgrades are applied automatically to the DB instance during the maintenance window.
        type: bool
    availability_zone:
        description:
          - A list of EC2 Availability Zones that the DB instance can be created in.
            May be used when creating an instance or when restoring from S3 or a snapshot. Mutually exclusive with O(multi_az).
        aliases:
          - az
          - zone
        type: str
    backup_retention_period:
        description:
          - The number of days for which automated backups are retained.
          - When set to V(0), automated backups will be disabled. (Not applicable if the DB instance is a source to read replicas)
          - May be used when creating a new instance, when restoring from S3, or when modifying an instance.
        type: int
    ca_certificate_identifier:
        description:
          - The identifier of the CA certificate for the DB instance.
        type: str
    character_set_name:
        description:
          - The character set to associate with the DB instance.
        type: str
    copy_tags_to_snapshot:
        description:
          - Whether or not to copy all tags from the DB instance to snapshots of the instance. When initially creating
            a DB instance the RDS API defaults this to V(false) if unspecified.
        type: bool
    db_cluster_identifier:
        description:
          - The DB cluster (lowercase) identifier to add the aurora DB instance to. The identifier must contain from 1 to
            63 letters, numbers, or hyphens and the first character must be a letter and may not end in a hyphen or
            contain consecutive hyphens.
        aliases:
          - cluster_id
        type: str
    db_instance_class:
        description:
          - The compute and memory capacity of the DB instance, for example V(db.t3.micro).
        aliases:
          - class
          - instance_type
        type: str
    db_instance_identifier:
        description:
          - The DB instance (lowercase) identifier. The identifier must contain from 1 to 63 letters, numbers, or
            hyphens and the first character must be a letter and may not end in a hyphen or contain consecutive hyphens.
        aliases:
          - instance_id
          - id
        required: true
        type: str
    db_name:
        description:
          - The name for your database. If a name is not provided Amazon RDS will not create a database.
        type: str
    db_parameter_group_name:
        description:
          - The name of the DB parameter group to associate with this DB instance. When creating the DB instance if this
            argument is omitted the default DBParameterGroup for the specified engine is used.
        type: str
    db_security_groups:
        description:
          - (EC2-Classic platform) A list of DB security groups to associate with this DB instance.
        type: list
        elements: str
    db_snapshot_identifier:
        description:
          - The identifier or ARN of the DB snapshot to restore from when using O(creation_source=snapshot).
        type: str
        aliases:
          - snapshot_identifier
          - snapshot_id
    db_subnet_group_name:
        description:
          - The DB subnet group name to use for the DB instance.
        aliases:
          - subnet_group
        type: str
    deletion_protection:
        description:
          -  A value that indicates whether the DB instance has deletion protection enabled.
             The database can't be deleted when deletion protection is enabled.
             By default, deletion protection is disabled.
        type: bool
        version_added: 3.3.0
        version_added_collection: community.aws
    domain:
        description:
          - The Active Directory Domain to restore the instance in.
        type: str
    domain_iam_role_name:
        description:
          - The name of the IAM role to be used when making API calls to the Directory Service.
        type: str
    enable_cloudwatch_logs_exports:
        description:
          - A list of log types that need to be enabled for exporting to CloudWatch Logs.
        aliases:
          - cloudwatch_log_exports
        type: list
        elements: str
    enable_iam_database_authentication:
        description:
          - Enable mapping of AWS Identity and Access Management (IAM) accounts to database accounts.
            If this option is omitted when creating the instance, Amazon RDS sets this to V(false).
        type: bool
    enable_performance_insights:
        description:
          - Whether to enable Performance Insights for the DB instance.
        type: bool
    engine:
        description:
          - The name of the database engine to be used for this DB instance. This is required to create an instance.
        choices: ['aurora', 'aurora-mysql', 'aurora-postgresql', 'mariadb', 'mysql', 'oracle-ee', 'oracle-ee-cdb',
                  'oracle-se2', 'oracle-se2-cdb', 'postgres', 'sqlserver-ee', 'sqlserver-se', 'sqlserver-ex', 'sqlserver-web']
        type: str
    engine_version:
        description:
          - The version number of the database engine to use. For Aurora MySQL that could be V(5.6.10a) , V(5.7.12).
            Aurora PostgreSQL example, V(9.6.3)
        type: str
    final_db_snapshot_identifier:
        description:
          - The DB instance snapshot identifier of the new DB instance snapshot created when O(skip_final_snapshot) is V(false).
        aliases:
          - final_snapshot_identifier
        type: str
    force_failover:
        description:
          - Set to V(true) to conduct the reboot through a MultiAZ failover.
        type: bool
    iam_roles:
        description:
          - List of Amazon Web Services Identity and Access Management (IAM) roles to associate with DB instance.
        type: list
        elements: dict
        suboptions:
          feature_name:
            description:
              - The name of the feature associated with the IAM role.
            type: str
            required: true
          role_arn:
            description:
              - The ARN of the IAM role to associate with the DB instance.
            type: str
            required: true
        version_added: 3.3.0
        version_added_collection: community.aws
    iops:
        description:
          - The Provisioned IOPS (I/O operations per second) value. Is only set when using O(storage_type) is set to io1.
        type: int
    kms_key_id:
        description:
          - The ARN of the AWS KMS key identifier for an encrypted DB instance. If you are creating a DB instance with the
            same AWS account that owns the KMS encryption key used to encrypt the new DB instance, then you can use the KMS key
            alias instead of the ARN for the KM encryption key.
          - If O(storage_encrypted) is V(true) and and this option is not provided, the default encryption key is used.
        type: str
    license_model:
        description:
          - The license model for the DB instance.
          - Several options are license-included, bring-your-own-license, and general-public-license.
          - This option can also be omitted to default to an accepted value.
        type: str
    master_user_password:
        description:
          - An 8-41 character password for the master database user. The password can contain any printable ASCII character
            except V(/), V("), or V(@). To modify the password use I(force_update_password). Use O(apply_immediately) to change
            the password immediately, otherwise it is updated during the next maintenance window.
        aliases:
          - password
        type: str
    master_username:
        description:
          - The name of the master user for the DB instance. Must be 1-16 letters or numbers and begin with a letter.
        aliases:
          - username
        type: str
    max_allocated_storage:
        description:
          - The upper limit to which Amazon RDS can automatically scale the storage of the DB instance.
        type: int
    monitoring_interval:
        description:
          - The interval, in seconds, when Enhanced Monitoring metrics are collected for the DB instance. To disable collecting
            metrics, specify V(0). Amazon RDS defaults this to 0 if omitted when initially creating a DB instance.
        type: int
    monitoring_role_arn:
        description:
          - The ARN for the IAM role that permits RDS to send enhanced monitoring metrics to Amazon CloudWatch Logs.
        type: str
    multi_az:
        description:
          - Specifies if the DB instance is a Multi-AZ deployment. Mutually exclusive with O(availability_zone).
        type: bool
    multi_tenant:
        description:
          - Specifies whether to use the multi-tenant configuration or the single-tenant configuration (default).
          - This parameter only applies to RDS for Oracle container database (CDB) engines.
          - The DB engine that you specify in the request must support the multi-tenant configuration.
          - If the multi-tenant configuration is enabled during creation of the DB instance, it cannot be modified later.
        type: bool
        version_added: 9.0.0
    new_db_instance_identifier:
        description:
          - The new DB instance (lowercase) identifier for the DB instance when renaming a DB instance. The identifier must contain
            from 1 to 63 letters, numbers, or hyphens and the first character must be a letter and may not end in a hyphen or
            contain consecutive hyphens. Use O(apply_immediately) to rename immediately, otherwise it is updated during the
            next maintenance window.
        aliases:
          - new_instance_id
          - new_id
        type: str
    option_group_name:
        description:
          - The option group to associate with the DB instance.
        type: str
    performance_insights_kms_key_id:
        description:
          - The AWS KMS key identifier (ARN, name, or alias) for encryption of Performance Insights data.
        type: str
    performance_insights_retention_period:
        description:
          - The amount of time, in days, to retain Performance Insights data. Valid values are 7 or 731.
        type: int
    port:
        description:
          - The port number on which the instances accept connections.
        type: int
    preferred_backup_window:
        description:
          - The daily time range (in UTC) of at least 30 minutes, during which automated backups are created if automated backups are
            enabled using O(backup_retention_period). The option must be in the format of "hh24:mi-hh24:mi" and not conflict with
            O(preferred_maintenance_window).
        aliases:
          - backup_window
        type: str
    preferred_maintenance_window:
        description:
          - The weekly time range (in UTC) of at least 30 minutes, during which system maintenance can occur. The option must
            be in the format "ddd:hh24:mi-ddd:hh24:mi" where ddd is one of Mon, Tue, Wed, Thu, Fri, Sat, Sun.
        aliases:
          - maintenance_window
        type: str
    processor_features:
        description:
          - A dictionary of Name, Value pairs to indicate the number of CPU cores and the number of threads per core for the
            DB instance class of the DB instance. Names are threadsPerCore and coreCount.
            Set this option to an empty dictionary to use the default processor features.
        suboptions:
          threadsPerCore:
            description: The number of threads per core
          coreCount:
            description: The number of CPU cores
        type: dict
    promotion_tier:
        description:
          - An integer that specifies the order in which an Aurora Replica is promoted to the primary instance after a failure of
            the existing primary instance.
        type: int
    publicly_accessible:
        description:
          - Specifies the accessibility options for the DB instance. A value of Vtrue) specifies an Internet-facing instance with
            a publicly resolvable DNS name, which resolves to a public IP address. A value of C(false) specifies an internal
            instance with a DNS name that resolves to a private IP address.
        type: bool
    purge_iam_roles:
        description:
          - Set to V(true) to remove any IAM roles that aren't specified in the task and are associated with the instance.
        type: bool
        default: false
        version_added: 3.3.0
        version_added_collection: community.aws
    restore_time:
        description:
          - If using I(creation_source=instance) this indicates the UTC date and time to restore from the source instance.
            For example, "2009-09-07T23:45:00Z".
          - May alternatively set O(use_latest_restorable_time=true).
          - Only one of O(use_latest_restorable_time) and O(restore_time) may be provided.
        type: str
    s3_bucket_name:
        description:
          - The name of the Amazon S3 bucket that contains the data used to create the Amazon DB instance.
        type: str
    s3_ingestion_role_arn:
        description:
          - The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that authorizes Amazon RDS to access
            the Amazon S3 bucket on your behalf.
        type: str
    s3_prefix:
        description:
          - The prefix for all of the file names that contain the data used to create the Amazon DB instance. If you do not
            specify a SourceS3Prefix value, then the Amazon DB instance is created by using all of the files in the Amazon S3 bucket.
        type: str
    skip_final_snapshot:
        description:
          - Whether a final DB instance snapshot is created before the DB instance is deleted. If this is V(false) O(final_db_snapshot_identifier)
            must be provided.
        type: bool
        default: false
    source_db_instance_identifier:
        description:
          - 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
            DB instance using O(creation_source=instance). If the source DB is not in the same region this should be an ARN.
        type: str
    source_engine:
        description:
          - The identifier for the database engine that was backed up to create the files stored in the Amazon S3 bucket.
        choices:
          - mysql
        type: str
    source_engine_version:
        description:
          - The version of the database that the backup files were created from.
        type: str
    source_region:
        description:
          - The region of the DB instance from which the replica is created.
        type: str
    storage_encrypted:
        description:
          - Whether the DB instance is encrypted.
        type: bool
    storage_type:
        description:
          - The storage type to be associated with the DB instance. O(storage_type) does not apply to Aurora DB instances.
        choices:
          - standard
          - gp2
          - gp3
          - io1
        type: str
    storage_throughput:
      description:
        - The storage throughput when the O(storage_type) is V(gp3).
        - When the allocated storage is below 400 GB, the storage throughput will always be 125 mb/s.
        - When the allocated storage is large than or equal 400 GB, the througput starts at 500 mb/s.
      type: int
      version_added: 5.2.0
    tde_credential_arn:
        description:
          - The ARN from the key store with which to associate the instance for Transparent Data Encryption. This is
            supported by Oracle or SQL Server DB instances and may be used in conjunction with O(storage_encrypted)
            though it might slightly affect the performance of your database.
        aliases:
          - transparent_data_encryption_arn
        type: str
    tde_credential_password:
        description:
          - The password for the given ARN from the key store in order to access the device.
        aliases:
          - transparent_data_encryption_password
        type: str
    timezone:
        description:
          - The time zone of the DB instance.
        type: str
    use_latest_restorable_time:
        description:
          - Whether to restore the DB instance to the latest restorable backup time.
          - Only one of O(use_latest_restorable_time) and O(restore_time) may be provided.
        type: bool
        aliases:
          - restore_from_latest
    vpc_security_group_ids:
        description:
          - A list of EC2 VPC security groups to associate with the DB instance.
        type: list
        elements: str
    purge_security_groups:
        description:
          - Set to V(false) to retain any enabled security groups that aren't specified in the task and are associated with the instance.
          - Can be applied to O(vpc_security_group_ids) and O(db_security_groups)
        type: bool
        default: true
        version_added: 1.5.0
        version_added_collection: community.aws
a  
# Note: These examples do not set authentication details, see the AWS Guide for details.
- name: Create minimal aurora instance in default VPC and default subnet group
  amazon.aws.rds_instance:
    engine: aurora
    db_instance_identifier: ansible-test-aurora-db-instance
    instance_type: db.t3.small
    password: "{{ password }}"
    username: "{{ username }}"
    cluster_id: ansible-test-cluster  # This cluster must exist - see rds_cluster to manage it

- name: Create a DB instance using the default AWS KMS encryption key
  amazon.aws.rds_instance:
    id: test-encrypted-db
    state: present
    engine: mariadb
    storage_encrypted: true
    db_instance_class: db.t3.medium
    username: "{{ username }}"
    password: "{{ password }}"
    allocated_storage: "{{ allocated_storage }}"

- name: Remove the DB instance without a final snapshot
  amazon.aws.rds_instance:
    id: "{{ instance_id }}"
    state: absent
    skip_final_snapshot: true

- name: Remove the DB instance with a final snapshot
  amazon.aws.rds_instance:
    id: "{{ instance_id }}"
    state: absent
    final_snapshot_identifier: "{{ snapshot_id }}"

- name: Add a new security group without purge
  amazon.aws.rds_instance:
    id: "{{ instance_id }}"
    state: present
    vpc_security_group_ids:
      - sg-0be17ba10c9286b0b
    purge_security_groups: false
  register: result

# Add IAM role to db instance
- name: Create IAM policy
  amazon.aws.iam_managed_policy:
    policy_name: "my-policy"
    policy: "{{ lookup('file','files/policy.json') }}"
    state: present
  register: iam_policy

- name: Create IAM role
  community.aws.iam_role:
    assume_role_policy_document: "{{ lookup('file','files/assume_policy.json') }}"
    name: "my-role"
    state: present
    managed_policy: "{{ iam_policy.policy.arn }}"
  register: iam_role

- name: Create DB instance with added IAM role
  amazon.aws.rds_instance:
    id: "my-instance-id"
    state: present
    engine: postgres
    engine_version: 14.2
    username: "{{ username }}"
    password: "{{ password }}"
    db_instance_class: db.m6g.large
    allocated_storage: "{{ allocated_storage }}"
    iam_roles:
      - role_arn: "{{ iam_role.arn }}"
        feature_name: 's3Export'

- name: Remove IAM role from DB instance
  amazon.aws.rds_instance:
    id: "my-instance-id"
    state: present
    purge_iam_roles: true

# Modify the DB instance type without waiting for a maintenance window
- name: Modify an RDS Instance
  amazon.aws.rds_instance:
    db_instance_identifier: mydbinstance123
    instance_class: db.t2.small
    apply_immediately: true
  register: rds_instance

# Restore DB instance from snapshot
- name: Create a snapshot and wait until completion
  amazon.aws.rds_instance_snapshot:
    instance_id: 'my-instance-id'
    snapshot_id: 'my-new-snapshot'
    state: present
    wait: true
  register: snapshot

- name: Restore DB from snapshot
  amazon.aws.rds_instance:
    id: 'my-restored-db'
    creation_source: snapshot
    snapshot_identifier: 'my-new-snapshot'
    engine: mariadb
    state: present
  register: restored_db
a%  
allocated_storage:
  description: The allocated storage size in gigabytes. This is always 1 for aurora database engines.
  returned: always
  type: int
  sample: 20
associated_roles:
  description: The list of currently associated roles.
  returned: always
  type: list
  sample: []
auto_minor_version_upgrade:
  description: Whether minor engine upgrades are applied automatically to the DB instance during the maintenance window.
  returned: always
  type: bool
  sample: true
availability_zone:
  description: The availability zone for the DB instance.
  returned: always
  type: str
  sample: us-east-1f
backup_retention_period:
  description: The number of days for which automated backups are retained.
  returned: always
  type: int
  sample: 1
ca_certificate_identifier:
  description:
    - The identifier of the CA certificate for the DB instance.
  returned: always
  type: str
  sample: rds-ca-2015
copy_tags_to_snapshot:
  description: Whether tags are copied from the DB instance to snapshots of the DB instance.
  returned: always
  type: bool
  sample: false
db_instance_arn:
  description: The Amazon Resource Name (ARN) for the DB instance.
  returned: always
  type: str
  sample: arn:aws:rds:us-east-1:123456789012:db:ansible-test
db_instance_class:
  description: The name of the compute and memory capacity class of the DB instance.
  returned: always
  type: str
  sample: db.m5.large
db_instance_identifier:
  description: The identifier of the DB instance.
  returned: always
  type: str
  sample: ansible-test
db_instance_port:
  description: The port that the DB instance listens on.
  returned: always
  type: int
  sample: 0
db_instance_status:
  description: The current state of this database.
  returned: always
  type: str
  sample: stopped
db_parameter_groups:
  description: The list of DB parameter groups applied to this DB instance.
  returned: always
  type: complex
  contains:
    db_parameter_group_name:
      description: The name of the DP parameter group.
      returned: always
      type: str
      sample: default.mariadb10.0
    parameter_apply_status:
      description: The status of parameter updates.
      returned: always
      type: str
      sample: in-sync
db_security_groups:
  description: A list of DB security groups associated with this DB instance.
  returned: always
  type: list
  sample: []
db_subnet_group:
  description: The subnet group associated with the DB instance.
  returned: always
  type: complex
  contains:
    db_subnet_group_description:
      description: The description of the DB subnet group.
      returned: always
      type: str
      sample: default
    db_subnet_group_name:
      description: The name of the DB subnet group.
      returned: always
      type: str
      sample: default
    subnet_group_status:
      description: The status of the DB subnet group.
      returned: always
      type: str
      sample: Complete
    subnets:
      description: A list of Subnet elements.
      returned: always
      type: complex
      contains:
        subnet_availability_zone:
          description: The availability zone of the subnet.
          returned: always
          type: complex
          contains:
            name:
              description: The name of the Availability Zone.
              returned: always
              type: str
              sample: us-east-1c
        subnet_identifier:
          description: The ID of the subnet.
          returned: always
          type: str
          sample: subnet-12345678
        subnet_status:
          description: The status of the subnet.
          returned: always
          type: str
          sample: Active
    vpc_id:
      description: The VpcId of the DB subnet group.
      returned: always
      type: str
      sample: vpc-12345678
dbi_resource_id:
  description: The AWS Region-unique, immutable identifier for the DB instance.
  returned: always
  type: str
  sample: db-UHV3QRNWX4KB6GALCIGRML6QFA
deletion_protection:
  description: C(true) if the DB instance has deletion protection enabled, C(False) if not.
  returned: always
  type: bool
  sample: False
  version_added: 3.3.0
  version_added_collection: community.aws
domain_memberships:
  description: The Active Directory Domain membership records associated with the DB instance.
  returned: always
  type: list
  sample: []
endpoint:
  description: The connection endpoint.
  returned: always
  type: complex
  contains:
    address:
      description: The DNS address of the DB instance.
      returned: always
      type: str
      sample: ansible-test.cvlrtwiennww.us-east-1.rds.amazonaws.com
    hosted_zone_id:
      description: The ID that Amazon Route 53 assigns when you create a hosted zone.
      returned: always
      type: str
      sample: ZTR2ITUGPA61AM
    port:
      description: The port that the database engine is listening on.
      returned: always
      type: int
      sample: 3306
engine:
  description: The database engine version.
  returned: always
  type: str
  sample: mariadb
engine_version:
  description: The database engine version.
  returned: always
  type: str
  sample: 10.0.35
iam_database_authentication_enabled:
  description: Whether mapping of AWS Identity and Access Management (IAM) accounts to database accounts is enabled.
  returned: always
  type: bool
  sample: false
instance_create_time:
  description: The date and time the DB instance was created.
  returned: always
  type: str
  sample: '2018-07-04T16:48:35.332000+00:00'
kms_key_id:
  description: The AWS KMS key identifier for the encrypted DB instance when storage_encrypted is true.
  returned: When storage_encrypted is true
  type: str
  sample: arn:aws:kms:us-east-1:123456789012:key/70c45553-ad2e-4a85-9f14-cfeb47555c33
latest_restorable_time:
  description: The latest time to which a database can be restored with point-in-time restore.
  returned: always
  type: str
  sample: '2018-07-04T16:50:50.642000+00:00'
license_model:
  description: The License model information for this DB instance.
  returned: always
  type: str
  sample: general-public-license
master_username:
  description: The master username for the DB instance.
  returned: always
  type: str
  sample: test
max_allocated_storage:
  description: The upper limit to which Amazon RDS can automatically scale the storage of the DB instance.
  returned: When max allocated storage is present.
  type: int
  sample: 100
monitoring_interval:
  description:
    - The interval, in seconds, between points when Enhanced Monitoring metrics are collected for the DB instance.
      0 means collecting Enhanced Monitoring metrics is disabled.
  returned: always
  type: int
  sample: 0
multi_az:
  description: Whether the DB instance is a Multi-AZ deployment.
  returned: always
  type: bool
  sample: false
multi_tenant:
  description: Specifies whether to use the multi-tenant configuration or the single-tenant configuration (default).
  returned: for Oracle container database (CDB) engines and boto3_version == "1.28.80"
  type: bool
  version_added: 9.0.0
  sample: false
option_group_memberships:
  description: The list of option group memberships for this DB instance.
  returned: always
  type: complex
  contains:
    option_group_name:
      description: The name of the option group that the instance belongs to.
      returned: always
      type: str
      sample: default:mariadb-10-0
    status:
      description: The status of the DB instance's option group membership.
      returned: always
      type: str
      sample: in-sync
pending_modified_values:
  description: The changes to the DB instance that are pending.
  returned: always
  type: complex
  contains: {}
performance_insights_enabled:
  description: true if Performance Insights is enabled for the DB instance, and otherwise false.
  returned: always
  type: bool
  sample: false
preferred_backup_window:
  description: The daily time range during which automated backups are created if automated backups are enabled.
  returned: always
  type: str
  sample: 07:01-07:31
preferred_maintenance_window:
  description: The weekly time range (in UTC) during which system maintenance can occur.
  returned: always
  type: str
  sample: sun:09:31-sun:10:01
publicly_accessible:
  description:
    - C(True) for an Internet-facing instance with a publicly resolvable DNS name, C(False) to indicate an
      internal instance with a DNS name that resolves to a private IP address.
  returned: always
  type: bool
  sample: true
read_replica_db_instance_identifiers:
  description: Identifiers of the Read Replicas associated with this DB instance.
  returned: always
  type: list
  sample: []
storage_encrypted:
  description: Whether the DB instance is encrypted.
  returned: always
  type: bool
  sample: false
storage_type:
  description: The storage type to be associated with the DB instance.
  returned: always
  type: str
  sample: standard
tags:
  description: A dictionary of tags associated with the DB instance.
  returned: always
  type: complex
  contains: {}
vpc_security_groups:
  description: A list of VPC security group elements that the DB instance belongs to.
  returned: always
  type: complex
  contains:
    status:
      description: The status of the VPC security group.
      returned: always
      type: str
      sample: active
    vpc_security_group_id:
      description: The name of the VPC security group.
      returned: always
      type: str
      sample: sg-12345678
    )sleep)Any)Dict)List)Optionalto_text)camel_dict_to_snake_dict)string_types)is_boto3_error_message)AnsibleAWSModule)AnsibleRDSError)arg_spec_to_rds_params)call_method)compare_iam_roles)describe_db_instances)ensure_tags)#format_rds_client_method_parameters)get_final_identifier)get_snapshot)update_iam_roles)ansible_dict_to_boto3_tag_list)boto3_tag_list_to_ansible_dict)auroraaurora-mysqlaurora-postgresqlmariadbmysql	oracle-eeoracle-ee-cdb
oracle-se2oracle-se2-cdbpostgressqlserver-eesqlserver-sesqlserver-exsqlserver-web)
r   r   r    r!   r"   r#   r$   r%   r&   r'   instancestatecreation_sourceread_replicareturnc                     d}|dk(  s|dk(  r| r	| d   dvrd}|S | rd}|S |du rd	}|S |d
k(  rd}|S |dk(  rd}|S |dk(  rd}|S d}|S )a0  
    Returns the target boto3 rds client method name given the provided module options and current instance state.

        Parameters:
            instance (dict): Current instance attributes as returned by get_instance()
            state (str): Desired instance state as provided to module options
            creation_source (str): Creation source to use for restoring an instance as provided to module options
            read_replica (bool): Whether to create (True) or promote (False) a read replica as provided to module options

        Returns:
            method_name (str): Name of boto3 rds client method needed to achieve desired state. Returns None if desired state is "absent" or "terminated" and
                current instance is None or the current instance status is "deleting" or "deleted"
    Nabsent
terminatedDBInstanceStatus)deletingdeleteddelete_db_instancemodify_db_instanceTcreate_db_instance_read_replicasnapshot$restore_db_instance_from_db_snapshots3restore_db_instance_from_s3r(   $restore_db_instance_to_point_in_timecreate_db_instance )r(   r)   r*   r+   method_names        k/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/modules/rds_instance.pyget_rds_method_attribute_namer?     s      KE\1!34<SS.K  .K  T!;K  
*@K  $7K
 	 
*@K  /K    moduledb_instance_idc                    d}	 t        | |      }|r|d   }ni S t        |j	                  d            |d<   |j                  d      rt        d	 |d   D              |d<   |j                  d
i       j                  d      rt        d |d
   d   D              |d
   d<   |S # t        $ r }|j                  |d|        Y d}~d}~ww xY w)a  
    Returns attributes for the provided db instance.

        Parameters:
            client: boto3 rds client
            module: AnsibleAWSModule
            db_instance_id (str): DB instance identifier

        Returns:
            instance (dict): DB instance attributes with the following boto3 attribute lists converted to dicts of key/value pairs:
                    - PendingModifiedValues["ProcessorFeatures"]
                    - ProcessorFeatures
                    - Tags (from boto3 TagList attribute)
                If no matching instance is found, returns an empty dict.

        Raises:
            Fails the module if an exception is raised while retrieving the db instance attributes.
    N)DBInstanceIdentifierzFailed to get DB instance msgr   TagListTagsProcessorFeaturesc              3   0   K   | ]  }|d    |d   f  ywNameValueNr<   .0features     r>   	<genexpr>zget_instance.<locals>.<genexpr>  s#      -
4;WV_gg./-
   PendingModifiedValuesc              3   0   K   | ]  }|d    |d   f  ywrK   r<   rN   s     r>   rQ   zget_instance.<locals>.<genexpr>  s%      F
4;WV_gg./F
rR   )r   r   fail_json_awsr   popgetdict)clientrA   rB   	instanceser(   s         r>   get_instancer\     s    & IS)&~V	 Q<	5hll96MNHV||'((, -
?GH[?\-
 )
$% ||+R0445HIAE F
?GH_?`at?uF
 B
()*=> O%  SQ&@@P$QRRSs   B" "	C+CC
parametersr=   c                    |dk(  r|j                   d   |d<   t        | |||d      }|j                  d      5|d   j                         D cg c]  \  }}|t	        |      d c}}|d<   |j                  d      g k(  r|dk(  s|j                  d       |d	v r"|j                  d
      rt        |d
         |d
<   |dk(  rt        | ||      }|S c c}}w )a  
    Returns a dict of parameters validated and formatted for the provided boto3 client method.

    Performs the following parameters checks and updates:
        - Formats provided parameters as expected by provided method
        - Converts the following dict parameters to lists of dicts as expected by the boto3 rds client: ProcessorFeatures, Tags
        - If method is "modify_db_instance", compares supplied parameters to current instance attributes, determines which parameters need to be modified, and
            removes any parameters that do not need to be modified

        Parameters:
            client: boto3 rds client
            module: AnsibleAWSModule
            parameters (dict): Parameter options from module argument_spec
            method_name: boto3 client method for which to validate parameters

        Returns:
            Dict of client parameters formatted for the provided method

        Raises:
            Fails the module if any parameters required by the provided method are not provided in module options
    r:   db_instance_identifierTargetDBInstanceIdentifierF)format_tagsrI   )rL   rM   r4   )r;   r5   r7   rH   )paramsr   rW   itemsr	   rV   r    get_options_with_changing_values)rY   rA   r]   r=   kvs         r>   get_parametersrg     s    , <<39==AY3Z
/04VVZQ\jopJ~~)*69CDW9X9^9^9`+
15AQ,+

&'
 ~~)*b0H\9\*+ww>>&!!?
6@R!SJv **5ffjQ
!+
s   Cc                    |j                   d   }|j                   d   }|j                   d   }|j                   d   }|j                  dd      }|j                   d   }|j                   d   }	|j                   d	   }
|j                   j                  d
      }|
r|
|d<   |r||d<   |s|j                  dd       |||d<   |j                   d   s|j                  dd       t        | ||      }t	        ||||	      }|j                  t        ||             |}|du r#|j                  d      r|j                  d       |j                  d      dk(  r|j                  di       j                  d|d         }|j                  di       j                  d|d         }|j                   j                  d      }|j                   j                  d      }||k7  s||k7  r
||d<   ||d<   |j                  d      dk(  r$d}|j                  di       j                  d|d         }|j                   j                  d      xs |}||k7  r||d<   |j                  di       j                  d|d         }|j                   j                  d      xs |}|j                   j                  d      }|j                  di       j                  d|d         }|rN||k7  r||d<   |dk\  r?|d k  r|j                  d!       |d"k  r|r|j                  d#       ||k7  r
||d<   ||d<   |j                  d$      }||j                   j                  d%      k(  s0|j                  d&      d'   |j                   j                  d%      k(  r|j                  d$d       |j                  d(      rB|j                  di       j                  d)      r!|d(   |d   d)   k(  r|s|j                  d(       |r||d)<   |||d<   |S )*a  
    Compares current instance attributes to the provided parameters and module options and returns parameters with values to be modified.

        Parameters:
            client: boto3 rds client
            module: AnsibleAWSModule
            parameters (dict): Parameters for boto3 client modify_db_instance method

        Returns:
            parameters (dict): Updated parameters including only parameters that need to be modified, renamed and formatted as expected by boto3 client
                modify_db_instance method

        Raises:
            Fails the module if invalid changes are provided for iops or storage_throughput values
    r_   purge_cloudwatch_logs_exportsforce_update_passwordportApplyImmediatelyNenable_cloudwatch_logs_exportspurge_security_groupsca_certificate_identifiermulti_tenantCACertificateIdentifierDBPortNumberMasterUserPassword!CloudwatchLogsExportConfigurationstorage_typeIopsFMultiTenantzdA DB which is configured to be a multi tenant cannot be modified to use single tenant configuration.rE   StorageTypeio1rS   AllocatedStorageiopsallocated_storagegp3TStorageThroughputstorage_throughputi  i.  zYIOPS must be at least 12000 when the allocated storage is larger than or equal to 400 GB.i  zeStorage Throughput must be at least 500 when the allocated storage is larger than or equal to 400 GB.PerformanceInsightsKMSKeyIdperformance_insights_kms_key_id/NewDBInstanceIdentifierrD   )	rb   rV   rW   r\   +get_changing_options_with_inconsistent_keysupdate)get_changing_options_with_consistent_keys	fail_jsonsplit)rY   rA   r]   instance_idpurge_cloudwatch_logsrj   rk   apply_immediatelycloudwatch_logs_enabledrn   ro   rp   r(   updated_parameterscurrent_iopscurrent_allocated_storagenew_iopsnew_allocated_storageGP3_THROUGHPUTcurrent_storage_throughputnew_storage_throughput(instance_performance_insights_kms_key_ids                         r>   rd   rd   )  s`     -- 89K"MM*IJ"MM*AB== D"'94@$mm,LM"MM*AB &.I J==$$^4L 0I
,-%)
>" +T2*:Q
67==(vt$FFK8HDH35J G
T\]^#J u<<&z  
 ||M"e+||$;R@DDVXV\M]^$,LL1H"$M$Q$Q); <%
! ==$$V, & 1 12E F8#'@DY'Y-BJ)*!)Jv||M"e+%-\\2I2%N%R%R*=!>&
" "(!2!23G!H!fLf!%??.DJ*+||$;R@DDVXV\M]^==$$V,< & 1 12E F$,LL1H"$M$Q$Q); <%
! !(,AA1F
-.$+e#$$w %  *C/N$$* %   8+)1Jv&5JJ12/7||<Y/Z,/6==3D3D)4 	1	7	7	<R	@FMMDUDU)E 
 	4d;~~/0X\\BY[]5^5b5b6 01X>U5VWm5nn%NN45-8
)*(->J)*r@   c                    i }| j                  di       j                  di       j                  dg       r| d   d   d   }| d   d   d   }||d|d<   n| j                  dg       g d|d<   | j                  di       j                  d      r| d   d   |d	<   n| d
   d   |d	<   | j                  di       j                  d      r| d   d   |d<   n| d   d   |d<   | j                  di       j                  d      r| d   d   |d<   n| j                  di       |d<   | d   D cg c]  }|d   	 c}|d<   | d   D cg c]  }|d   dv s|d    c}|d<   | d   D cg c]  }|d   dv s|d    c}|d<   | d   D cg c]  }|d   	 c}|d<   | d   |d<   | j                  dd      |d<   | d   |d<   d |d!<   d |d"<   |S c c}w c c}w c c}w c c}w )#a  
    Returns current instance attributes whose formats differ from those expected by boto3 client modify_db_instance method, updated to match method options.

    Option formats for the boto3 client modify_db_instance method do not always match their corresponding attributes returned by describe_db_instances.
    To ensure that we are accurately comparing the two dicts for changes, this function:
        - Checks for pending modified values in these instance attributes and updates the corresponding current attributes to match the pending values
        - Converts these instance attribute names and value formats to those expected by the modify_db_instance method

        Parameters:
            instance (dict): Current instance attributes as returned by get_instance()

        Returns:
            options (dict): Current instance attributes updated to match the boto3 client modify_db_instance method option formatting. Only returns attributes
                whose format varies between the returned attributes and the method options (i.e., excludes any attributes whose formats already match what the
                boto3 client method expects)
    rS   PendingCloudwatchLogsExportsLogTypesToEnableLogTypesToDisable)r   r   rt   EnabledCloudwatchLogsExportsPortrr   EndpointDBSubnetGroupNameDBSubnetGrouprI   OptionGroupMembershipsOptionGroupNameDBSecurityGroupsStatus)addingactiveDBSecurityGroupNameVpcSecurityGroupsVpcSecurityGroupIdVpcSecurityGroupIdsDBParameterGroupsDBParameterGroupName IAMDatabaseAuthenticationEnabledEnableIAMDatabaseAuthenticationPerformanceInsightsEnabledFEnablePerformanceInsightsrD   r   NAllowMajorVersionUpgraders   rW   )r(   optionscurrent_enabledcurrent_disabledgsgparameter_groups          r>   -get_current_attributes_with_inconsistent_keysr     s   " !G ||+R0445SUWX\\]oqst"#:;<Z[\no#$;<=[\]pq /!18
34 !)-KR P!#8
34 ||+R044V<"*+B"CF"K"*:"6v">||+R0445HI'/0G'HI\']#$'/'@AT'U#$||+R0445HI'/0G'HI\']#$'/||4G'L#$ AIIa@b!c1!$5"6!cG,45G,H#&(BxL\pLp !#G ,44G+H&%'BxL\pLp &G!" HPPcGd'4C./'G"# 2::\1]G-. ,4<<8TV[+\G'()12H)IG%& +/G&'$(G !N) "d#&'s$   %G>GGG,G Gmodify_paramsr   rn   c                 ,   i }t        |      }|j                         D ]r  \  }}| j                  |d      }|t        |t              r`t        |t              r;t        |      t        |      k  r|dv r|r|||<   n-t        |      t        |      k  rwt        |t              r||v r|dk7  r||k(  r|dk(  r|t        |dd      k(  r|dk(  r|g k(  rd|d<   |dk(  rzt        |j                  d	g             }t        |      }g g d
}	t	        |j                  |            |	d<   |rt	        |j                  |            |	d<   |	d   s|	d   s5|	||<   <|dv r.|r|||<   It	        t        |      t        |      z        ||<   n|||<   u |S )a  
    Compares current instance attributes with provided parameters whose formats are inconsistent between describe_db_instances and modify_db_instance methods.

        Parameters:
            modify_params (dict): Parameters to be supplied to boto3 client modify_db_instance method; should already be validated and formatted
            instance (dict): Current instance attributes as returned by get_instance()
            purge_cloudwatch_logs (bool): True if currently enabled cloudwatch logs exports should be removed from configuration when not in provided
                parameters, False if they should be retained
            purge_security_groups (bool): True if currently associated security groups should be removed from instance if not in provided parameters, False if
                they should be retained

        Returns:
                changing_params (dict): Parameters to be modified
    N)r   r   rI   rL   rM   TUseDefaultProcessorFeaturesrt   r   )EnableLogTypesDisableLogTypesr   r   )
r   rc   rV   
isinstancelistsetr   r   rW   
difference)
r   r(   r   rn   changing_paramscurrent_optionsoptioncurrent_optiondesired_optionformat_options
             r>   r   r     s   " ')OCHMO"1"7"7"9 :5&**648! nd+.$/'#n*=="MM- /=OF+(C,??NL9!^3 ((^~-M((^?]FG@
 .
  ((^r-A=AO9::: !3!34F!KLN 0N@BWY-ZM.2>3L3L^3\.]M*+$378Q8QR`8a3b/0-.-@Q2R*7'BB$*8'*.s>/BSEX/X*Y'&4OF#u:5v r@   c                     i }| D ]I  }|j                  di       j                  |d      }||j                  |d      }| |   |k7  sB| |   ||<   K |S )a  
    Compares current instance attributes with provided parameters whose attribute and parameter formats match.

        Parameters:
            modify_params (dict): Parameters to be supplied to boto3 client modify_db_instance method; should already be validated and formatted
            instance (dict): Current instance attributes as returned by get_instance()

        Returns:
            changing_params (dict): Parameters to be modified
    rS   Nr   )r   r(   r   paramr   s        r>   r   r   H  sp     ')O :!&=rBFFudS!%\\%6N>1%25%9OE": r@   Nc                 P   |j                   d   }|j                   d   }|j                   d   }|j                   d   }|j                   d   }t        |j                   d   xs |j                   d         }|j                   d   }	|j                   d	   }
|j                   d
   }|j                   d   }|rt        | ||      }ni }|r|r|r|j                  d| d       |r|s|r|j                  d| d       |dv r|r|s||j                  d       |6|j	                  d      s%|j	                  d      s|r|j                  d       |	du r|s|
dvr|j                  d|
 d       |	du r|s|s|j                  d       ||dvr|j                  d| d       yyy)a  
    Validates complex module option logic and fails the module with an error message if options are invalid.

        Parameters:
            client: boto3 rds client
            module: AnsibleAWSModule
            instance (dict): Current instance attributes as returned by get_instance()

        Raises:
            Fails the module if provided module options are incompatible with each other or with current instance attributes
    r)   skip_final_snapshotfinal_db_snapshot_identifiernew_db_instance_identifierenginetde_credential_passwordtde_credential_arnr+   r*   source_db_instance_identifierrp   zA new instance ID z# was provided but it already existsrE   z; was provided but the instance to be renamed does not exist)r.   r/   Nz_skip_final_snapshot is false but all of the following are missing: final_db_snapshot_identifierr   oraclez2TDE is available for MySQL and Oracle DB instancesT)Nr(   z"Cannot create a read replica from z#. You must use a source DB instancez|read_replica is true and the instance does not exist yet but all of the following are missing: source_db_instance_identifier)r"   r    zbMulti Tenant parameter only applies to RDS for Oracle container database (CDB) engines and not to .)rb   boolr\   r   
startswith)rY   rA   r(   r)   r   snapshot_idmodified_idr   tde_optionsr+   r*   source_instancerp   modified_instances                 r>   validate_optionsr   `  s    MM'"E --(=>-- >?K-- <=K]]8$Fv}}%>?f6==QeCfgK==0Lmm$56Omm$CDO==0L(Ex$51+>abc8(9$[M1lm 	 	
 ((X>QVaViq 	 	
 6#4#4W#=ARARS[A\bmQRtHHZ1ZA/ARRuvwtH_1 	 	
 F2U$Utu{t||}~ 	 	
 %Vr@   r   c           
         d}|st        | ||      }|t        | ||d   |d   |j                  d   |j                  d         z  }|t        | |||j                  d         z  }|t	        | |||j                  d         z  }|S )a  
    Ensures that an existing instance's tags, read replica status, and state match what is supplied in module options.

        Parameters:
            client: boto3 rds client
            module: AnsibleAWSModule
            instance (dict): Current instance attributes as returned by get_instance()
            instance_id (str): Existing instance identifier, used to retrieve instance attributes if provided instance dict is empty

        Returns:
            changed (bool): True if instance was successfully updated, False if not
    FDBInstanceArnrH   tags
purge_tagsr+   r)   )r\   r   rb   promote_replication_instanceupdate_instance_state)rY   rA   r(   r   changeds        r>   update_instancer     s     G < {18F3CV]]SYEZ\b\i\ijv\w G +FFHfmmTbFcddG$VVXv}}W?UVVGNr@   c                     d}|du r4t        |j                  d            r	 t        | |dd|d   i      \  }}|S |S # t        d      $ r Y |S w xY w)a  
    Promotes the provided DB instance from a read replica to a standalone instance.

    Only promotes the instance if read_replica is False, which is confusing but is how the module is documented.
    Returns changed=False without any warning or error message if the provided instance is not a read replica.

        Parameters:
            client: boto3 rds client
            module: AnsibleAWSModule
            instance (dict): Current instance attributes as returned by get_instance()
            read_replica (bool): False if instance should be promoted

        Returns:
            changed (bool): True if provided instance was successfully promoted, False if not
    FStatusInfospromote_read_replicarD   )r=   r]   z!DB Instance is not a read replica)r   rW   r   r   )rY   rA   r(   r+   r   _results         r>   r   r     sy    $ Gu ]+,#. 6 6AW8XY	$  N7N **MN Ns   = AAc                    t        t        | ||      ddg      }|j                  d      }|t        vr|j	                  d| dt                d}|j
                  j                  d	      }|j
                  j                  d
      r|j
                  j                  d
      ng }|j                  dg       }t        |||      \  }	}
t        |	xs |
      r3d}|j                  r |j                  dd|i| |S t        | |||	|
       |S )aa  
    Ensure specified IAM roles are associated with DB instance.

        Parameters:
            client: boto3 rds client
            module: AnsibleAWSModule
            instance_id (str): Existing DB instance identifier

        Returns:
            changed (bool): True if changes were successfully made to DB instance's IAM roles; False if not
    rH   rI   ignore_listr   z
DB engine z6 is not valid for adding IAM roles. Valid engines are rE   Fpurge_iam_roles	iam_rolesassociated_rolesTr   r<   )r
   r\   rW   valid_engines_iam_rolesr   rb   r   r   
check_mode	exit_jsonr   )rY   rA   r   r(   r   r   r   target_rolesexisting_rolesroles_to_addroles_to_removes              r>   ensure_iam_rolesr     s    (VV[1H[?\H
 \\(#F,,VH$Z[rZst 	 	
 Gmm''(9:O5;]]5F5F{5S6==$$[1Y[L\\"4b9N$5nlTc$d!L/L+O,F9W99 N VV[,XNr@   c                 \    d}|dv r|t        | ||      z  }|dv r|t        | |||      z  }|S )a  
    Starts, stops, or reboots an instance given the desired state and current instance attributes.

        Parameters:
            client: boto3 rds client
            module: AnsibleAWSModule
            instance (dict): Current instance attributes as returned by get_instance()
            state (str): Desired instance state as provided to module options

        Returns:
            changed (bool): True if DB instance state was updated, False if not
    F)rebooted	restarted)startedrunningstopped)reboot_running_db_instancestart_or_stop_instance)rY   rA   r(   r)   r   s        r>   r   r     sJ     G))-ffhGG11)&&(EJJNr@   c                     d|d   i}|d   dv rt        | |d|       |j                  j                  d      |j                  d   |d<   t        | |d|      \  }}|S )a  
    Reboots provided instance.

    If the instance is currently stopped or stopping, restarts it first.

        Parameters:
            client: boto3 rds client
            module: AnsibleAWSModule
            instance (dict): Current instance attributes as returned by get_instance()

        Returns:
            changed (bool): True if instance was successfully rebooted, False otherwise.
    rD   r0   )r   stoppingstart_db_instanceforce_failoverForceFailoverreboot_db_instance)r   rb   rW   )rY   rA   r(   r]   _resultsr   s         r>   r   r     sw     )(3I*JKJ"#'>>FF$7D}})*6&,mm4D&E
?##FF4H*UHgNr@   c                     d}d|d   i}|dk(  r;|d   dvr4|j                   d   r|j                   d   |d<   t        | |d|      \  }}|S |d	k(  r|d   d
vrt        | |d|      \  }}|S )a  
    Starts or stops provided instance given desired state.

    Checks whether the instance is already in or pending the desired state, if so does not alter it.

        Parameters:
            client: boto3 rds client
            module: AnsibleAWSModule
            instance (dict): Current instance attributes as returned by get_instance()
            state (str): Desired instance state as provided to module options

        Returns:
            changed (bool): True if instance was started or stopped, False if not
    FrD   r   r0   )r   r   db_snapshot_identifierDBSnapshotIdentifierstop_db_instancer   )	availablestarting
restartingr   )rb   r   )rY   rA   r(   r)   r   r]   r   s          r>   r   r   +  s     G((3I*JKJ	h'9:BYY==1217?W1XJ-.&vv7I:V N 
)	); <Dk k&vv7JJWNr@   c                     t        t        g dd      t        g d      t        ddd      t        dd	
      t        dd
      t        dd	
      t        d      t        dd	
      t        dd	
      	      } t        di dt        d      dt        d      dt        dd
      dt        d      dt        ddg      dt        d      dt        d      dt               dt        d      dt        dg      dt        ddg      d t        d	d!d"g#      d$t               d%t               d&t        d'd(      d)t        dd*d+g,      d-t        d.g      d/t        d      d0t               d1t               d2t        d'd3gd4      d5t        d      d6t        d      d7t        dt        8      d9t               d:t        d;g      d<t        d      d=t        d'd>(      d?t        d      d@t               dAt               dBt        dCgd	D      dEt        dFg      dGt        d      dHt        d      dIt               dJt        d      dKt        d      dLt        dMdNg      dOt               dPt               dQt        d      dRt        d      dSt        dTg      dUt        dVg      dWt        d>      dXt        d      dYt        d      dZt               d[t               d\t               d]t               d^t        dd
      d_t               d`t        dag      dbt               dct               ddt        d      det        g df      dgt        d      dht        d>dig,      djt        dkg      dlt        d	dmgn      dot               dpt        ddqg,      drt        d'd(      | j                         g ds}d7dtdggd7dudggd7dvdggdedwd?dggdxdyd)d7ggdxdz|gg}g d{dpdZgddJgg}t        | ||d	|      j                  d    j                         j                  d <   j                  dL   r*j                  dL   j                         j                  dL<   j                  dW   :t        d} j                  dW   j                         D              j                  dW<   j                  dU   r*j                  dU   j                         j                  dU<   j                  j                  d      rj                  rj                  d~       j                  d      }d}j                  d   }j                  d    }t        ||      }t        ||       t        ||j                  dx   j                  d         }	|	rj                  r%|	dv r! j                  ddd	it        |ddg       t!        t        fdj                  D                    }
t#        ||
|	      }|r>j                  r! j                  ddd	it        |ddg       t%        ||	|      \  }}t'        |	      }|dk7  rej                  r|r|t)        |||      z  }j                  j                  d=      sj                  j                  d      r|t+        ||      z  }|rMt        ||      }|dk7  r;|sj                  s-t-        dd      D ]  }t        ||      }|r nt/        d         |dk(  r?|r=j                  d^   s.j                  d:   }	 |j                  t1        ||dd             d }|j                  di       j                  d      r|d   j7                  d      }t        |ddg      }|||d   dW<    j                  dd|i| y # t2        $ r }j5                  |d|        Y d }~d }~ww xY w)N)presentr.   r/   r   r   r   r   r   r  )choicesdefault)r6   r8   r(   )r  r   F)typer  no_logT)r  r  )r  )	r)   r*   rj   ri   r   r   r+   waitrn   r|   intallow_major_version_upgrader   auto_minor_version_upgradeavailability_zoneazzone)aliasesbackup_retention_periodro   strcharacter_set_namecopy_tags_to_snapshotdb_cluster_identifier
cluster_iddb_instance_classclassinstance_typer_   r   id)requiredr  db_namedb_parameter_group_namedb_security_groupsr   )r  elementsr  snapshot_identifierr   )r  r  db_subnet_group_namesubnet_groupdeletion_protectiondomaindomain_iam_role_namerm   cloudwatch_log_exports)r  r  r(  "enable_iam_database_authenticationenable_performance_insightsr   )r  r  engine_versionr   final_snapshot_identifierr  r   rX   r{   
kms_key_idlicense_modelmaster_user_passwordpassword)r  r  master_usernameusernamemax_allocated_storagemonitoring_intervalmonitoring_role_arnmulti_azrp   r   new_instance_idnew_idoption_group_namer   %performance_insights_retention_periodrk   preferred_backup_windowbackup_windowpreferred_maintenance_windowmaintenance_windowprocessor_featurespromotion_tierpublicly_accessiblerestore_times3_bucket_names3_ingestion_role_arn	s3_prefixr   r   source_enginer   source_engine_versionsource_regionstorage_encryptedru   )standardgp2r}   ry   r   r   resource_tagsr   transparent_data_encryption_arnr   $transparent_data_encryption_password)r  r  timezoneuse_latest_restorable_timerestore_from_latestvpc_security_group_ids)rJ  r   r8  r6  rM  rN  rK  r   r   zaurora-postresqlry   r*   r6   r8   )rJ  r   r  )argument_specrequired_ifmutually_exclusivesupports_check_modec              3   <   K   | ]  \  }}|t        |      f  y wNr   )rO   re   rf   s      r>   rQ   zmain.<locals>.<genexpr>  s!      3
 $1Q
O3
s   z~allow_major_version_upgrade is not returned when describing db instances, so changed will always be `True` on check mode runs.rdsr)   r+   )r;   r3   r   rH   rI   r   c              3   J   K   | ]  }|v s|j                   |   f  y wr_  )rb   )rO   re   rA   parameter_optionss     r>   rQ   zmain.<locals>.<genexpr>  s'     X1FWAW!V]]1%&Xs   	##r.   r   r   
      r(   )FinalSnapshotzFailed to get snapshot: rE   rS   pending_modified_valuesr<   )rX   valid_enginesr   r   rb   lowerrc   rW   r   warnrY   r\   r   r?   r   r
   r   rg   r   r   r   r   ranger   r   r   rU   rV   )arg_specrequired_if_s3_creation_sourcer[  r\  rY   r   r)   r   r(   r=   raw_parametersparameters_to_modifyr   _wait_attemptr   r[   pending_processor_featuresrA   rb  s                    @@r>   mainrq  E  s	   q
 %CD"eL&*&E&%8VT2v&vt,"=H  CE*C$(f$5C FE:C $(V#4	C
 f~6C !%% 0C #'E"2C  6C #/C #L>:C 'ABC  $TM4;PQC C !%C  Ve<C   $9NP]8^_!C" ">*:;#C$ !f-%C& v'C( "V)C* (,BZA[fk'l+C, ,0V+<-C. %)f$5/C0 61C2 v3C4 &*3N2O%P5C6 (7C8 FV49C: u;C< 6=C> f?C@ ":,tDACB j\2CCD #.ECF !e,GCH !FICJ 6"KCL v&MCN $(1BH0M#NOCP &QCR )-SCT /3.>UCV uWCX !%o-> ?YCZ &*3G2H%I[C\  V,]C^ '_C` !f-aCb VcCd veCf #fgCh &iCj !fe<kCl '+fmCn G9-oCp #fqCr fsCt F+uCv "CDwCx  U+yCz v'89{C|  )J(KL}C~ !%D;a:b cC@ ACB $(V>S=T#UCCD  $%@ECH OO%&&" 
8567	>$;#<=	%(?'@A	)< =>	J)A8(LM	D"@AK 	V	%~6	j) - 	F /5mm<T.U.[.[.]FMM*+}}126<mmD`6a6g6g6i23 }})*6.2 3
(.6J(K(Q(Q(S3
 /
*+
 }}348>Fd8e8k8k8m45 }}67F<M<M#	

 ]]5!FGMM'"E-- 89KFFK8HVVX./%'896==;XK 0\!\F  8PVXkOl m 0XXX
  .ffnkZ       $<XTZ\oSp$q  +66;H\]GW*;?H$$?668[QQ }}  -1B1BCT1U+FFKHH#FFK@H hf6G6G%*1b\ M+FFKHH!H	 H?T1U --(FGKVl6;PZ\a.bc "&||+R0445HI%-.E%F%J%JK^%_"'vGZ>[\H!-D^*+,@AF1W11 # V$$Q.F{m,T$UUVs   _ 	`&``__main__)6DOCUMENTATIONEXAMPLESRETURNtimer   typingr   r   r   r   ansible.module_utils._textr	   0ansible.module_utils.common.dict_transformationsr
   ansible.module_utils.sixr   <ansible_collections.amazon.aws.plugins.module_utils.botocorer   ;ansible_collections.amazon.aws.plugins.module_utils.modulesr   7ansible_collections.amazon.aws.plugins.module_utils.rdsr   r   r   r   r   r   r   r   r   r   ;ansible_collections.amazon.aws.plugins.module_utils.taggingr   r   rg  r   r  r   r?   r\   rg   rd   r   r   r   r   r   r   r   r   r   r   rq  __name__r<   r@   r>   <module>r     s%  JXhTu
n	      . U 1 _ X S Z O U Y O g X P T f f" !!!14!DLTN!c]!H(!1 (3 (4PSUXPX> (V+#3 +c3h +^a +fjknpsksft +\B5E BSWX[]`X`Sa Bfjknpsksft BJFDcN FtTWY\T\~ FRNS>N-1#s(^NTXNquN	#s(^NbS>-1#s(^	#s(^06
%5 6
c3h 6
TX 6
r$4 S#X ]` ei : $ 04S#X NR 	 F#%5 #C #D #L*: d3PS8n ]` ei */? 4PSUXPX> ^b .+; tCQTH~ ^a fj 4N2b zF r@   