aws-cdk.aws-rds


Nameaws-cdk.aws-rds JSON
Version 1.204.0 PyPI version JSON
download
home_pagehttps://github.com/aws/aws-cdk
SummaryThe CDK Construct Library for AWS::RDS
upload_time2023-06-19 21:06:47
maintainer
docs_urlNone
authorAmazon Web Services
requires_python~=3.7
licenseApache-2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Amazon Relational Database Service Construct Library

<!--BEGIN STABILITY BANNER-->---


![End-of-Support](https://img.shields.io/badge/End--of--Support-critical.svg?style=for-the-badge)

> AWS CDK v1 has reached End-of-Support on 2023-06-01.
> This package is no longer being updated, and users should migrate to AWS CDK v2.
>
> For more information on how to migrate, see the [*Migrating to AWS CDK v2* guide](https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html).

---
<!--END STABILITY BANNER-->

```python
import aws_cdk.aws_rds as rds
```

## Starting a clustered database

To set up a clustered database (like Aurora), define a `DatabaseCluster`. You must
always launch a database in a VPC. Use the `vpcSubnets` attribute to control whether
your instances will be launched privately or publicly:

```python
# vpc: ec2.Vpc

cluster = rds.DatabaseCluster(self, "Database",
    engine=rds.DatabaseClusterEngine.aurora_mysql(version=rds.AuroraMysqlEngineVersion.VER_2_08_1),
    credentials=rds.Credentials.from_generated_secret("clusteradmin"),  # Optional - will default to 'admin' username and generated password
    instance_props=rds.InstanceProps(
        # optional , defaults to t3.medium
        instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.SMALL),
        vpc_subnets=ec2.SubnetSelection(
            subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT
        ),
        vpc=vpc
    )
)
```

If there isn't a constant for the exact version you want to use,
all of the `Version` classes have a static `of` method that can be used to create an arbitrary version.

```python
custom_engine_version = rds.AuroraMysqlEngineVersion.of("5.7.mysql_aurora.2.08.1")
```

By default, the master password will be generated and stored in AWS Secrets Manager with auto-generated description.

Your cluster will be empty by default. To add a default database upon construction, specify the
`defaultDatabaseName` attribute.

Use `DatabaseClusterFromSnapshot` to create a cluster from a snapshot:

```python
# vpc: ec2.Vpc

rds.DatabaseClusterFromSnapshot(self, "Database",
    engine=rds.DatabaseClusterEngine.aurora(version=rds.AuroraEngineVersion.VER_1_22_2),
    instance_props=rds.InstanceProps(
        vpc=vpc
    ),
    snapshot_identifier="mySnapshot"
)
```

## Starting an instance database

To set up a instance database, define a `DatabaseInstance`. You must
always launch a database in a VPC. Use the `vpcSubnets` attribute to control whether
your instances will be launched privately or publicly:

```python
# vpc: ec2.Vpc

instance = rds.DatabaseInstance(self, "Instance",
    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),
    # optional, defaults to m5.large
    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.SMALL),
    credentials=rds.Credentials.from_generated_secret("syscdk"),  # Optional - will default to 'admin' username and generated password
    vpc=vpc,
    vpc_subnets=ec2.SubnetSelection(
        subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT
    )
)
```

If there isn't a constant for the exact engine version you want to use,
all of the `Version` classes have a static `of` method that can be used to create an arbitrary version.

```python
custom_engine_version = rds.OracleEngineVersion.of("19.0.0.0.ru-2020-04.rur-2020-04.r1", "19")
```

By default, the master password will be generated and stored in AWS Secrets Manager.

To use the storage auto scaling option of RDS you can specify the maximum allocated storage.
This is the upper limit to which RDS can automatically scale the storage. More info can be found
[here](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PIOPS.StorageTypes.html#USER_PIOPS.Autoscaling)
Example for max storage configuration:

```python
# vpc: ec2.Vpc

instance = rds.DatabaseInstance(self, "Instance",
    engine=rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3),
    # optional, defaults to m5.large
    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.SMALL),
    vpc=vpc,
    max_allocated_storage=200
)
```

Use `DatabaseInstanceFromSnapshot` and `DatabaseInstanceReadReplica` to create an instance from snapshot or
a source database respectively:

```python
# vpc: ec2.Vpc

# source_instance: rds.DatabaseInstance

rds.DatabaseInstanceFromSnapshot(self, "Instance",
    snapshot_identifier="my-snapshot",
    engine=rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3),
    # optional, defaults to m5.large
    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.LARGE),
    vpc=vpc
)
rds.DatabaseInstanceReadReplica(self, "ReadReplica",
    source_database_instance=source_instance,
    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.LARGE),
    vpc=vpc
)
```

Automatic backups of read replica instances are only supported for MySQL and MariaDB. By default,
automatic backups are disabled for read replicas and can only be enabled (using `backupRetention`)
if also enabled on the source instance.

Creating a "production" Oracle database instance with option and parameter groups:

```python
# Set open cursors with parameter group
parameter_group = rds.ParameterGroup(self, "ParameterGroup",
    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),
    parameters={
        "open_cursors": "2500"
    }
)

option_group = rds.OptionGroup(self, "OptionGroup",
    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),
    configurations=[rds.OptionConfiguration(
        name="LOCATOR"
    ), rds.OptionConfiguration(
        name="OEM",
        port=1158,
        vpc=vpc
    )
    ]
)

# Allow connections to OEM
option_group.option_connections.OEM.connections.allow_default_port_from_any_ipv4()

# Database instance with production values
instance = rds.DatabaseInstance(self, "Instance",
    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),
    license_model=rds.LicenseModel.BRING_YOUR_OWN_LICENSE,
    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MEDIUM),
    multi_az=True,
    storage_type=rds.StorageType.IO1,
    credentials=rds.Credentials.from_username("syscdk"),
    vpc=vpc,
    database_name="ORCL",
    storage_encrypted=True,
    backup_retention=cdk.Duration.days(7),
    monitoring_interval=cdk.Duration.seconds(60),
    enable_performance_insights=True,
    cloudwatch_logs_exports=["trace", "audit", "alert", "listener"
    ],
    cloudwatch_logs_retention=logs.RetentionDays.ONE_MONTH,
    auto_minor_version_upgrade=True,  # required to be true if LOCATOR is used in the option group
    option_group=option_group,
    parameter_group=parameter_group,
    removal_policy=RemovalPolicy.DESTROY
)

# Allow connections on default port from any IPV4
instance.connections.allow_default_port_from_any_ipv4()

# Rotate the master user password every 30 days
instance.add_rotation_single_user()

# Add alarm for high CPU
cloudwatch.Alarm(self, "HighCPU",
    metric=instance.metric_cPUUtilization(),
    threshold=90,
    evaluation_periods=1
)

# Trigger Lambda function on instance availability events
fn = lambda_.Function(self, "Function",
    code=lambda_.Code.from_inline("exports.handler = (event) => console.log(event);"),
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_14_X
)

availability_rule = instance.on_event("Availability", target=targets.LambdaFunction(fn))
availability_rule.add_event_pattern(
    detail={
        "EventCategories": ["availability"
        ]
    }
)
```

Add XMLDB and OEM with option group

```python
# Set open cursors with parameter group
parameter_group = rds.ParameterGroup(self, "ParameterGroup",
    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),
    parameters={
        "open_cursors": "2500"
    }
)

option_group = rds.OptionGroup(self, "OptionGroup",
    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),
    configurations=[rds.OptionConfiguration(
        name="LOCATOR"
    ), rds.OptionConfiguration(
        name="OEM",
        port=1158,
        vpc=vpc
    )
    ]
)

# Allow connections to OEM
option_group.option_connections.OEM.connections.allow_default_port_from_any_ipv4()

# Database instance with production values
instance = rds.DatabaseInstance(self, "Instance",
    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),
    license_model=rds.LicenseModel.BRING_YOUR_OWN_LICENSE,
    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MEDIUM),
    multi_az=True,
    storage_type=rds.StorageType.IO1,
    credentials=rds.Credentials.from_username("syscdk"),
    vpc=vpc,
    database_name="ORCL",
    storage_encrypted=True,
    backup_retention=cdk.Duration.days(7),
    monitoring_interval=cdk.Duration.seconds(60),
    enable_performance_insights=True,
    cloudwatch_logs_exports=["trace", "audit", "alert", "listener"
    ],
    cloudwatch_logs_retention=logs.RetentionDays.ONE_MONTH,
    auto_minor_version_upgrade=True,  # required to be true if LOCATOR is used in the option group
    option_group=option_group,
    parameter_group=parameter_group,
    removal_policy=RemovalPolicy.DESTROY
)

# Allow connections on default port from any IPV4
instance.connections.allow_default_port_from_any_ipv4()

# Rotate the master user password every 30 days
instance.add_rotation_single_user()

# Add alarm for high CPU
cloudwatch.Alarm(self, "HighCPU",
    metric=instance.metric_cPUUtilization(),
    threshold=90,
    evaluation_periods=1
)

# Trigger Lambda function on instance availability events
fn = lambda_.Function(self, "Function",
    code=lambda_.Code.from_inline("exports.handler = (event) => console.log(event);"),
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_14_X
)

availability_rule = instance.on_event("Availability", target=targets.LambdaFunction(fn))
availability_rule.add_event_pattern(
    detail={
        "EventCategories": ["availability"
        ]
    }
)
```

## Setting Public Accessibility

You can set public accessibility for the database instance or cluster using the `publiclyAccessible` property.
If you specify `true`, it creates an instance with a publicly resolvable DNS name, which resolves to a public IP address.
If you specify `false`, it creates an internal instance with a DNS name that resolves to a private IP address.
The default value depends on `vpcSubnets`.
It will be `true` if `vpcSubnets` is `subnetType: SubnetType.PUBLIC`, `false` otherwise.

```python
# vpc: ec2.Vpc

# Setting public accessibility for DB instance
rds.DatabaseInstance(self, "Instance",
    engine=rds.DatabaseInstanceEngine.mysql(
        version=rds.MysqlEngineVersion.VER_8_0_19
    ),
    vpc=vpc,
    vpc_subnets=ec2.SubnetSelection(
        subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT
    ),
    publicly_accessible=True
)

# Setting public accessibility for DB cluster
rds.DatabaseCluster(self, "DatabaseCluster",
    engine=rds.DatabaseClusterEngine.AURORA,
    instance_props=rds.InstanceProps(
        vpc=vpc,
        vpc_subnets=ec2.SubnetSelection(
            subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT
        ),
        publicly_accessible=True
    )
)
```

## Instance events

To define Amazon CloudWatch event rules for database instances, use the `onEvent`
method:

```python
# instance: rds.DatabaseInstance
# fn: lambda.Function

rule = instance.on_event("InstanceEvent", target=targets.LambdaFunction(fn))
```

## Login credentials

By default, database instances and clusters (with the exception of `DatabaseInstanceFromSnapshot` and `ServerlessClusterFromSnapshot`) will have `admin` user with an auto-generated password.
An alternative username (and password) may be specified for the admin user instead of the default.

The following examples use a `DatabaseInstance`, but the same usage is applicable to `DatabaseCluster`.

```python
# vpc: ec2.Vpc

engine = rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3)
rds.DatabaseInstance(self, "InstanceWithUsername",
    engine=engine,
    vpc=vpc,
    credentials=rds.Credentials.from_generated_secret("postgres")
)

rds.DatabaseInstance(self, "InstanceWithUsernameAndPassword",
    engine=engine,
    vpc=vpc,
    credentials=rds.Credentials.from_password("postgres", SecretValue.ssm_secure("/dbPassword", "1"))
)

my_secret = secretsmanager.Secret.from_secret_name(self, "DBSecret", "myDBLoginInfo")
rds.DatabaseInstance(self, "InstanceWithSecretLogin",
    engine=engine,
    vpc=vpc,
    credentials=rds.Credentials.from_secret(my_secret)
)
```

Secrets generated by `fromGeneratedSecret()` can be customized:

```python
# vpc: ec2.Vpc

engine = rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3)
my_key = kms.Key(self, "MyKey")

rds.DatabaseInstance(self, "InstanceWithCustomizedSecret",
    engine=engine,
    vpc=vpc,
    credentials=rds.Credentials.from_generated_secret("postgres",
        secret_name="my-cool-name",
        encryption_key=my_key,
        exclude_characters="!&*^#@()",
        replica_regions=[secretsmanager.ReplicaRegion(region="eu-west-1"), secretsmanager.ReplicaRegion(region="eu-west-2")]
    )
)
```

### Snapshot credentials

As noted above, Databases created with `DatabaseInstanceFromSnapshot` or `ServerlessClusterFromSnapshot` will not create user and auto-generated password by default because it's not possible to change the master username for a snapshot. Instead, they will use the existing username and password from the snapshot. You can still generate a new password - to generate a secret similarly to the other constructs, pass in credentials with `fromGeneratedSecret()` or `fromGeneratedPassword()`.

```python
# vpc: ec2.Vpc

engine = rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3)
my_key = kms.Key(self, "MyKey")

rds.DatabaseInstanceFromSnapshot(self, "InstanceFromSnapshotWithCustomizedSecret",
    engine=engine,
    vpc=vpc,
    snapshot_identifier="mySnapshot",
    credentials=rds.SnapshotCredentials.from_generated_secret("username",
        encryption_key=my_key,
        exclude_characters="!&*^#@()",
        replica_regions=[secretsmanager.ReplicaRegion(region="eu-west-1"), secretsmanager.ReplicaRegion(region="eu-west-2")]
    )
)
```

## Connecting

To control who can access the cluster or instance, use the `.connections` attribute. RDS databases have
a default port, so you don't need to specify the port:

```python
# cluster: rds.DatabaseCluster

cluster.connections.allow_from_any_ipv4(ec2.Port.all_traffic(), "Open to the world")
```

The endpoints to access your database cluster will be available as the `.clusterEndpoint` and `.readerEndpoint`
attributes:

```python
# cluster: rds.DatabaseCluster

write_address = cluster.cluster_endpoint.socket_address
```

For an instance database:

```python
# instance: rds.DatabaseInstance

address = instance.instance_endpoint.socket_address
```

## Rotating credentials

When the master password is generated and stored in AWS Secrets Manager, it can be rotated automatically:

```python
import aws_cdk.core as cdk

# instance: rds.DatabaseInstance

instance.add_rotation_single_user(
    automatically_after=cdk.Duration.days(7),  # defaults to 30 days
    exclude_characters="!@#$%^&*"
)
```

```python
cluster = rds.DatabaseCluster(stack, "Database",
    engine=rds.DatabaseClusterEngine.AURORA,
    instance_props=rds.InstanceProps(
        instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.SMALL),
        vpc=vpc
    )
)

cluster.add_rotation_single_user()
```

The multi user rotation scheme is also available:

```python
# instance: rds.DatabaseInstance
# my_imported_secret: rds.DatabaseSecret

instance.add_rotation_multi_user("MyUser",
    secret=my_imported_secret
)
```

It's also possible to create user credentials together with the instance/cluster and add rotation:

```python
# instance: rds.DatabaseInstance

my_user_secret = rds.DatabaseSecret(self, "MyUserSecret",
    username="myuser",
    secret_name="my-user-secret",  # optional, defaults to a CloudFormation-generated name
    master_secret=instance.secret,
    exclude_characters="{}[]()'\"/\\"
)
my_user_secret_attached = my_user_secret.attach(instance) # Adds DB connections information in the secret

instance.add_rotation_multi_user("MyUser",  # Add rotation using the multi user scheme
    secret=my_user_secret_attached)
```

**Note**: This user must be created manually in the database using the master credentials.
The rotation will start as soon as this user exists.

Access to the Secrets Manager API is required for the secret rotation. This can be achieved either with
internet connectivity (through NAT) or with a VPC interface endpoint. By default, the rotation Lambda function
is deployed in the same subnets as the instance/cluster. If access to the Secrets Manager API is not possible from
those subnets or using the default API endpoint, use the `vpcSubnets` and/or `endpoint` options:

```python
# instance: rds.DatabaseInstance
# my_endpoint: ec2.InterfaceVpcEndpoint


instance.add_rotation_single_user(
    vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT),  # Place rotation Lambda in private subnets
    endpoint=my_endpoint
)
```

See also [@aws-cdk/aws-secretsmanager](https://github.com/aws/aws-cdk/blob/master/packages/%40aws-cdk/aws-secretsmanager/README.md) for credentials rotation of existing clusters/instances.

## IAM Authentication

You can also authenticate to a database instance using AWS Identity and Access Management (IAM) database authentication;
See [https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html) for more information
and a list of supported versions and limitations.

**Note**: `grantConnect()` does not currently work - see [this GitHub issue](https://github.com/aws/aws-cdk/issues/11851).

The following example shows enabling IAM authentication for a database instance and granting connection access to an IAM role.

```python
# vpc: ec2.Vpc

instance = rds.DatabaseInstance(self, "Instance",
    engine=rds.DatabaseInstanceEngine.mysql(version=rds.MysqlEngineVersion.VER_8_0_19),
    vpc=vpc,
    iam_authentication=True
)
role = iam.Role(self, "DBRole", assumed_by=iam.AccountPrincipal(self.account))
instance.grant_connect(role)
```

The following example shows granting connection access for RDS Proxy to an IAM role.

```python
# vpc: ec2.Vpc

cluster = rds.DatabaseCluster(self, "Database",
    engine=rds.DatabaseClusterEngine.AURORA,
    instance_props=rds.InstanceProps(vpc=vpc)
)

proxy = rds.DatabaseProxy(self, "Proxy",
    proxy_target=rds.ProxyTarget.from_cluster(cluster),
    secrets=[cluster.secret],
    vpc=vpc
)

role = iam.Role(self, "DBProxyRole", assumed_by=iam.AccountPrincipal(self.account))
proxy.grant_connect(role, "admin")
```

**Note**: In addition to the setup above, a database user will need to be created to support IAM auth.
See [https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.DBAccounts.html](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.DBAccounts.html) for setup instructions.

## Kerberos Authentication

You can also authenticate using Kerberos to a database instance using AWS Managed Microsoft AD for authentication;
See [https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html) for more information
and a list of supported versions and limitations.

The following example shows enabling domain support for a database instance and creating an IAM role to access
Directory Services.

```python
# vpc: ec2.Vpc

role = iam.Role(self, "RDSDirectoryServicesRole",
    assumed_by=iam.ServicePrincipal("rds.amazonaws.com"),
    managed_policies=[
        iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AmazonRDSDirectoryServiceAccess")
    ]
)
instance = rds.DatabaseInstance(self, "Instance",
    engine=rds.DatabaseInstanceEngine.mysql(version=rds.MysqlEngineVersion.VER_8_0_19),
    vpc=vpc,
    domain="d-????????",  # The ID of the domain for the instance to join.
    domain_role=role
)
```

**Note**: In addition to the setup above, you need to make sure that the database instance has network connectivity
to the domain controllers. This includes enabling cross-VPC traffic if in a different VPC and setting up the
appropriate security groups/network ACL to allow traffic between the database instance and domain controllers.
Once configured, see [https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html) for details
on configuring users for each available database engine.

## Metrics

Database instances and clusters both expose metrics (`cloudwatch.Metric`):

```python
# The number of database connections in use (average over 5 minutes)
# instance: rds.DatabaseInstance

# Average CPU utilization over 5 minutes
# cluster: rds.DatabaseCluster

db_connections = instance.metric_database_connections()
cpu_utilization = cluster.metric_cPUUtilization()

# The average amount of time taken per disk I/O operation (average over 1 minute)
read_latency = instance.metric("ReadLatency", statistic="Average", period=Duration.seconds(60))
```

## Enabling S3 integration

Data in S3 buckets can be imported to and exported from certain database engines using SQL queries. To enable this
functionality, set the `s3ImportBuckets` and `s3ExportBuckets` properties for import and export respectively. When
configured, the CDK automatically creates and configures IAM roles as required.
Additionally, the `s3ImportRole` and `s3ExportRole` properties can be used to set this role directly.

You can read more about loading data to (or from) S3 here:

* Aurora MySQL - [import](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.LoadFromS3.html)
  and [export](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.SaveIntoS3.html).
* Aurora PostgreSQL - [import](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraPostgreSQL.Migrating.html#USER_PostgreSQL.S3Import)
  and [export](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/postgresql-s3-export.html).
* Microsoft SQL Server - [import and export](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/SQLServer.Procedural.Importing.html)
* PostgreSQL - [import](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/PostgreSQL.Procedural.Importing.html)
  and [export](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/postgresql-s3-export.html)
* Oracle - [import and export](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-s3-integration.html)

The following snippet sets up a database cluster with different S3 buckets where the data is imported and exported -

```python
import aws_cdk.aws_s3 as s3

# vpc: ec2.Vpc

import_bucket = s3.Bucket(self, "importbucket")
export_bucket = s3.Bucket(self, "exportbucket")
rds.DatabaseCluster(self, "dbcluster",
    engine=rds.DatabaseClusterEngine.AURORA,
    instance_props=rds.InstanceProps(
        vpc=vpc
    ),
    s3_import_buckets=[import_bucket],
    s3_export_buckets=[export_bucket]
)
```

## Creating a Database Proxy

Amazon RDS Proxy sits between your application and your relational database to efficiently manage
connections to the database and improve scalability of the application. Learn more about at [Amazon RDS Proxy](https://aws.amazon.com/rds/proxy/)

The following code configures an RDS Proxy for a `DatabaseInstance`.

```python
# vpc: ec2.Vpc
# security_group: ec2.SecurityGroup
# secrets: List[secretsmanager.Secret[]]
# db_instance: rds.DatabaseInstance


proxy = db_instance.add_proxy("proxy",
    borrow_timeout=Duration.seconds(30),
    max_connections_percent=50,
    secrets=secrets,
    vpc=vpc
)
```

## Exporting Logs

You can publish database logs to Amazon CloudWatch Logs. With CloudWatch Logs, you can perform real-time analysis of the log data,
store the data in highly durable storage, and manage the data with the CloudWatch Logs Agent. This is available for both database
instances and clusters; the types of logs available depend on the database type and engine being used.

```python
import aws_cdk.aws_logs as logs
# my_logs_publishing_role: iam.Role
# vpc: ec2.Vpc


# Exporting logs from a cluster
cluster = rds.DatabaseCluster(self, "Database",
    engine=rds.DatabaseClusterEngine.aurora(
        version=rds.AuroraEngineVersion.VER_1_17_9
    ),
    instance_props=rds.InstanceProps(
        vpc=vpc
    ),
    cloudwatch_logs_exports=["error", "general", "slowquery", "audit"],  # Export all available MySQL-based logs
    cloudwatch_logs_retention=logs.RetentionDays.THREE_MONTHS,  # Optional - default is to never expire logs
    cloudwatch_logs_retention_role=my_logs_publishing_role
)

# Exporting logs from an instance
instance = rds.DatabaseInstance(self, "Instance",
    engine=rds.DatabaseInstanceEngine.postgres(
        version=rds.PostgresEngineVersion.VER_12_3
    ),
    vpc=vpc,
    cloudwatch_logs_exports=["postgresql"]
)
```

## Option Groups

Some DB engines offer additional features that make it easier to manage data and databases, and to provide additional security for your database.
Amazon RDS uses option groups to enable and configure these features. An option group can specify features, called options,
that are available for a particular Amazon RDS DB instance.

```python
# vpc: ec2.Vpc
# security_group: ec2.SecurityGroup


rds.OptionGroup(self, "Options",
    engine=rds.DatabaseInstanceEngine.oracle_se2(
        version=rds.OracleEngineVersion.VER_19
    ),
    configurations=[rds.OptionConfiguration(
        name="OEM",
        port=5500,
        vpc=vpc,
        security_groups=[security_group]
    )
    ]
)
```

## Parameter Groups

Database parameters specify how the database is configured.
For example, database parameters can specify the amount of resources, such as memory, to allocate to a database.
You manage your database configuration by associating your DB instances with parameter groups.
Amazon RDS defines parameter groups with default settings.

You can create your own parameter group for your cluster or instance and associate it with your database:

```python
# vpc: ec2.Vpc


parameter_group = rds.ParameterGroup(self, "ParameterGroup",
    engine=rds.DatabaseInstanceEngine.sql_server_ee(
        version=rds.SqlServerEngineVersion.VER_11
    ),
    parameters={
        "locks": "100"
    }
)

rds.DatabaseInstance(self, "Database",
    engine=rds.DatabaseInstanceEngine.SQL_SERVER_EE,
    vpc=vpc,
    parameter_group=parameter_group
)
```

Another way to specify parameters is to use the inline field `parameters` that creates an RDS parameter group for you.
You can use this if you do not want to reuse the parameter group instance for different instances:

```python
# vpc: ec2.Vpc


rds.DatabaseInstance(self, "Database",
    engine=rds.DatabaseInstanceEngine.sql_server_ee(version=rds.SqlServerEngineVersion.VER_11),
    vpc=vpc,
    parameters={
        "locks": "100"
    }
)
```

You cannot specify a parameter map and a parameter group at the same time.

## Serverless

[Amazon Aurora Serverless](https://aws.amazon.com/rds/aurora/serverless/) is an on-demand, auto-scaling configuration for Amazon
Aurora. The database will automatically start up, shut down, and scale capacity
up or down based on your application's needs. It enables you to run your database
in the cloud without managing any database instances.

The following example initializes an Aurora Serverless PostgreSql cluster.
Aurora Serverless clusters can specify scaling properties which will be used to
automatically scale the database cluster seamlessly based on the workload.

```python
# vpc: ec2.Vpc


cluster = rds.ServerlessCluster(self, "AnotherCluster",
    engine=rds.DatabaseClusterEngine.AURORA_POSTGRESQL,
    parameter_group=rds.ParameterGroup.from_parameter_group_name(self, "ParameterGroup", "default.aurora-postgresql10"),
    vpc=vpc,
    scaling=rds.ServerlessScalingOptions(
        auto_pause=Duration.minutes(10),  # default is to pause after 5 minutes of idle time
        min_capacity=rds.AuroraCapacityUnit.ACU_8,  # default is 2 Aurora capacity units (ACUs)
        max_capacity=rds.AuroraCapacityUnit.ACU_32
    )
)
```

Aurora Serverless Clusters do not support the following features:

* Loading data from an Amazon S3 bucket
* Saving data to an Amazon S3 bucket
* Invoking an AWS Lambda function with an Aurora MySQL native function
* Aurora replicas
* Backtracking
* Multi-master clusters
* Database cloning
* IAM database cloning
* IAM database authentication
* Restoring a snapshot from MySQL DB instance
* Performance Insights
* RDS Proxy

Read more about the [limitations of Aurora Serverless](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless.html#aurora-serverless.limitations)

Learn more about using Amazon Aurora Serverless by reading the [documentation](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless.html)

Use `ServerlessClusterFromSnapshot` to create a serverless cluster from a snapshot:

```python
# vpc: ec2.Vpc

rds.ServerlessClusterFromSnapshot(self, "Cluster",
    engine=rds.DatabaseClusterEngine.AURORA_MYSQL,
    vpc=vpc,
    snapshot_identifier="mySnapshot"
)
```

### Data API

You can access your Aurora Serverless DB cluster using the built-in Data API. The Data API doesn't require a persistent connection to the DB cluster. Instead, it provides a secure HTTP endpoint and integration with AWS SDKs.

The following example shows granting Data API access to a Lamba function.

```python
# vpc: ec2.Vpc

# code: lambda.Code


cluster = rds.ServerlessCluster(self, "AnotherCluster",
    engine=rds.DatabaseClusterEngine.AURORA_MYSQL,
    vpc=vpc,  # this parameter is optional for serverless Clusters
    enable_data_api=True
)
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_14_X,
    handler="index.handler",
    code=code,
    environment={
        "CLUSTER_ARN": cluster.cluster_arn,
        "SECRET_ARN": cluster.secret.secret_arn
    }
)
cluster.grant_data_api_access(fn)
```

**Note**: To invoke the Data API, the resource will need to read the secret associated with the cluster.

To learn more about using the Data API, see the [documentation](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html).

### Default VPC

The `vpc` parameter is optional.

If not provided, the cluster will be created in the default VPC of the account and region.
As this VPC is not deployed with AWS CDK, you can't configure the `vpcSubnets`, `subnetGroup` or `securityGroups` of the Aurora Serverless Cluster.
If you want to provide one of `vpcSubnets`, `subnetGroup` or `securityGroups` parameter, please provide a `vpc`.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/aws/aws-cdk",
    "name": "aws-cdk.aws-rds",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "~=3.7",
    "maintainer_email": "",
    "keywords": "",
    "author": "Amazon Web Services",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/b3/47/ff7131880b0797321fb992906a8edb1848c2202fac3080e157e7de428245/aws-cdk.aws-rds-1.204.0.tar.gz",
    "platform": null,
    "description": "# Amazon Relational Database Service Construct Library\n\n<!--BEGIN STABILITY BANNER-->---\n\n\n![End-of-Support](https://img.shields.io/badge/End--of--Support-critical.svg?style=for-the-badge)\n\n> AWS CDK v1 has reached End-of-Support on 2023-06-01.\n> This package is no longer being updated, and users should migrate to AWS CDK v2.\n>\n> For more information on how to migrate, see the [*Migrating to AWS CDK v2* guide](https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html).\n\n---\n<!--END STABILITY BANNER-->\n\n```python\nimport aws_cdk.aws_rds as rds\n```\n\n## Starting a clustered database\n\nTo set up a clustered database (like Aurora), define a `DatabaseCluster`. You must\nalways launch a database in a VPC. Use the `vpcSubnets` attribute to control whether\nyour instances will be launched privately or publicly:\n\n```python\n# vpc: ec2.Vpc\n\ncluster = rds.DatabaseCluster(self, \"Database\",\n    engine=rds.DatabaseClusterEngine.aurora_mysql(version=rds.AuroraMysqlEngineVersion.VER_2_08_1),\n    credentials=rds.Credentials.from_generated_secret(\"clusteradmin\"),  # Optional - will default to 'admin' username and generated password\n    instance_props=rds.InstanceProps(\n        # optional , defaults to t3.medium\n        instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.SMALL),\n        vpc_subnets=ec2.SubnetSelection(\n            subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT\n        ),\n        vpc=vpc\n    )\n)\n```\n\nIf there isn't a constant for the exact version you want to use,\nall of the `Version` classes have a static `of` method that can be used to create an arbitrary version.\n\n```python\ncustom_engine_version = rds.AuroraMysqlEngineVersion.of(\"5.7.mysql_aurora.2.08.1\")\n```\n\nBy default, the master password will be generated and stored in AWS Secrets Manager with auto-generated description.\n\nYour cluster will be empty by default. To add a default database upon construction, specify the\n`defaultDatabaseName` attribute.\n\nUse `DatabaseClusterFromSnapshot` to create a cluster from a snapshot:\n\n```python\n# vpc: ec2.Vpc\n\nrds.DatabaseClusterFromSnapshot(self, \"Database\",\n    engine=rds.DatabaseClusterEngine.aurora(version=rds.AuroraEngineVersion.VER_1_22_2),\n    instance_props=rds.InstanceProps(\n        vpc=vpc\n    ),\n    snapshot_identifier=\"mySnapshot\"\n)\n```\n\n## Starting an instance database\n\nTo set up a instance database, define a `DatabaseInstance`. You must\nalways launch a database in a VPC. Use the `vpcSubnets` attribute to control whether\nyour instances will be launched privately or publicly:\n\n```python\n# vpc: ec2.Vpc\n\ninstance = rds.DatabaseInstance(self, \"Instance\",\n    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),\n    # optional, defaults to m5.large\n    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.SMALL),\n    credentials=rds.Credentials.from_generated_secret(\"syscdk\"),  # Optional - will default to 'admin' username and generated password\n    vpc=vpc,\n    vpc_subnets=ec2.SubnetSelection(\n        subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT\n    )\n)\n```\n\nIf there isn't a constant for the exact engine version you want to use,\nall of the `Version` classes have a static `of` method that can be used to create an arbitrary version.\n\n```python\ncustom_engine_version = rds.OracleEngineVersion.of(\"19.0.0.0.ru-2020-04.rur-2020-04.r1\", \"19\")\n```\n\nBy default, the master password will be generated and stored in AWS Secrets Manager.\n\nTo use the storage auto scaling option of RDS you can specify the maximum allocated storage.\nThis is the upper limit to which RDS can automatically scale the storage. More info can be found\n[here](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PIOPS.StorageTypes.html#USER_PIOPS.Autoscaling)\nExample for max storage configuration:\n\n```python\n# vpc: ec2.Vpc\n\ninstance = rds.DatabaseInstance(self, \"Instance\",\n    engine=rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3),\n    # optional, defaults to m5.large\n    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.SMALL),\n    vpc=vpc,\n    max_allocated_storage=200\n)\n```\n\nUse `DatabaseInstanceFromSnapshot` and `DatabaseInstanceReadReplica` to create an instance from snapshot or\na source database respectively:\n\n```python\n# vpc: ec2.Vpc\n\n# source_instance: rds.DatabaseInstance\n\nrds.DatabaseInstanceFromSnapshot(self, \"Instance\",\n    snapshot_identifier=\"my-snapshot\",\n    engine=rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3),\n    # optional, defaults to m5.large\n    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.LARGE),\n    vpc=vpc\n)\nrds.DatabaseInstanceReadReplica(self, \"ReadReplica\",\n    source_database_instance=source_instance,\n    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.LARGE),\n    vpc=vpc\n)\n```\n\nAutomatic backups of read replica instances are only supported for MySQL and MariaDB. By default,\nautomatic backups are disabled for read replicas and can only be enabled (using `backupRetention`)\nif also enabled on the source instance.\n\nCreating a \"production\" Oracle database instance with option and parameter groups:\n\n```python\n# Set open cursors with parameter group\nparameter_group = rds.ParameterGroup(self, \"ParameterGroup\",\n    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),\n    parameters={\n        \"open_cursors\": \"2500\"\n    }\n)\n\noption_group = rds.OptionGroup(self, \"OptionGroup\",\n    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),\n    configurations=[rds.OptionConfiguration(\n        name=\"LOCATOR\"\n    ), rds.OptionConfiguration(\n        name=\"OEM\",\n        port=1158,\n        vpc=vpc\n    )\n    ]\n)\n\n# Allow connections to OEM\noption_group.option_connections.OEM.connections.allow_default_port_from_any_ipv4()\n\n# Database instance with production values\ninstance = rds.DatabaseInstance(self, \"Instance\",\n    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),\n    license_model=rds.LicenseModel.BRING_YOUR_OWN_LICENSE,\n    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MEDIUM),\n    multi_az=True,\n    storage_type=rds.StorageType.IO1,\n    credentials=rds.Credentials.from_username(\"syscdk\"),\n    vpc=vpc,\n    database_name=\"ORCL\",\n    storage_encrypted=True,\n    backup_retention=cdk.Duration.days(7),\n    monitoring_interval=cdk.Duration.seconds(60),\n    enable_performance_insights=True,\n    cloudwatch_logs_exports=[\"trace\", \"audit\", \"alert\", \"listener\"\n    ],\n    cloudwatch_logs_retention=logs.RetentionDays.ONE_MONTH,\n    auto_minor_version_upgrade=True,  # required to be true if LOCATOR is used in the option group\n    option_group=option_group,\n    parameter_group=parameter_group,\n    removal_policy=RemovalPolicy.DESTROY\n)\n\n# Allow connections on default port from any IPV4\ninstance.connections.allow_default_port_from_any_ipv4()\n\n# Rotate the master user password every 30 days\ninstance.add_rotation_single_user()\n\n# Add alarm for high CPU\ncloudwatch.Alarm(self, \"HighCPU\",\n    metric=instance.metric_cPUUtilization(),\n    threshold=90,\n    evaluation_periods=1\n)\n\n# Trigger Lambda function on instance availability events\nfn = lambda_.Function(self, \"Function\",\n    code=lambda_.Code.from_inline(\"exports.handler = (event) => console.log(event);\"),\n    handler=\"index.handler\",\n    runtime=lambda_.Runtime.NODEJS_14_X\n)\n\navailability_rule = instance.on_event(\"Availability\", target=targets.LambdaFunction(fn))\navailability_rule.add_event_pattern(\n    detail={\n        \"EventCategories\": [\"availability\"\n        ]\n    }\n)\n```\n\nAdd XMLDB and OEM with option group\n\n```python\n# Set open cursors with parameter group\nparameter_group = rds.ParameterGroup(self, \"ParameterGroup\",\n    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),\n    parameters={\n        \"open_cursors\": \"2500\"\n    }\n)\n\noption_group = rds.OptionGroup(self, \"OptionGroup\",\n    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),\n    configurations=[rds.OptionConfiguration(\n        name=\"LOCATOR\"\n    ), rds.OptionConfiguration(\n        name=\"OEM\",\n        port=1158,\n        vpc=vpc\n    )\n    ]\n)\n\n# Allow connections to OEM\noption_group.option_connections.OEM.connections.allow_default_port_from_any_ipv4()\n\n# Database instance with production values\ninstance = rds.DatabaseInstance(self, \"Instance\",\n    engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),\n    license_model=rds.LicenseModel.BRING_YOUR_OWN_LICENSE,\n    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MEDIUM),\n    multi_az=True,\n    storage_type=rds.StorageType.IO1,\n    credentials=rds.Credentials.from_username(\"syscdk\"),\n    vpc=vpc,\n    database_name=\"ORCL\",\n    storage_encrypted=True,\n    backup_retention=cdk.Duration.days(7),\n    monitoring_interval=cdk.Duration.seconds(60),\n    enable_performance_insights=True,\n    cloudwatch_logs_exports=[\"trace\", \"audit\", \"alert\", \"listener\"\n    ],\n    cloudwatch_logs_retention=logs.RetentionDays.ONE_MONTH,\n    auto_minor_version_upgrade=True,  # required to be true if LOCATOR is used in the option group\n    option_group=option_group,\n    parameter_group=parameter_group,\n    removal_policy=RemovalPolicy.DESTROY\n)\n\n# Allow connections on default port from any IPV4\ninstance.connections.allow_default_port_from_any_ipv4()\n\n# Rotate the master user password every 30 days\ninstance.add_rotation_single_user()\n\n# Add alarm for high CPU\ncloudwatch.Alarm(self, \"HighCPU\",\n    metric=instance.metric_cPUUtilization(),\n    threshold=90,\n    evaluation_periods=1\n)\n\n# Trigger Lambda function on instance availability events\nfn = lambda_.Function(self, \"Function\",\n    code=lambda_.Code.from_inline(\"exports.handler = (event) => console.log(event);\"),\n    handler=\"index.handler\",\n    runtime=lambda_.Runtime.NODEJS_14_X\n)\n\navailability_rule = instance.on_event(\"Availability\", target=targets.LambdaFunction(fn))\navailability_rule.add_event_pattern(\n    detail={\n        \"EventCategories\": [\"availability\"\n        ]\n    }\n)\n```\n\n## Setting Public Accessibility\n\nYou can set public accessibility for the database instance or cluster using the `publiclyAccessible` property.\nIf you specify `true`, it creates an instance with a publicly resolvable DNS name, which resolves to a public IP address.\nIf you specify `false`, it creates an internal instance with a DNS name that resolves to a private IP address.\nThe default value depends on `vpcSubnets`.\nIt will be `true` if `vpcSubnets` is `subnetType: SubnetType.PUBLIC`, `false` otherwise.\n\n```python\n# vpc: ec2.Vpc\n\n# Setting public accessibility for DB instance\nrds.DatabaseInstance(self, \"Instance\",\n    engine=rds.DatabaseInstanceEngine.mysql(\n        version=rds.MysqlEngineVersion.VER_8_0_19\n    ),\n    vpc=vpc,\n    vpc_subnets=ec2.SubnetSelection(\n        subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT\n    ),\n    publicly_accessible=True\n)\n\n# Setting public accessibility for DB cluster\nrds.DatabaseCluster(self, \"DatabaseCluster\",\n    engine=rds.DatabaseClusterEngine.AURORA,\n    instance_props=rds.InstanceProps(\n        vpc=vpc,\n        vpc_subnets=ec2.SubnetSelection(\n            subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT\n        ),\n        publicly_accessible=True\n    )\n)\n```\n\n## Instance events\n\nTo define Amazon CloudWatch event rules for database instances, use the `onEvent`\nmethod:\n\n```python\n# instance: rds.DatabaseInstance\n# fn: lambda.Function\n\nrule = instance.on_event(\"InstanceEvent\", target=targets.LambdaFunction(fn))\n```\n\n## Login credentials\n\nBy default, database instances and clusters (with the exception of `DatabaseInstanceFromSnapshot` and `ServerlessClusterFromSnapshot`) will have `admin` user with an auto-generated password.\nAn alternative username (and password) may be specified for the admin user instead of the default.\n\nThe following examples use a `DatabaseInstance`, but the same usage is applicable to `DatabaseCluster`.\n\n```python\n# vpc: ec2.Vpc\n\nengine = rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3)\nrds.DatabaseInstance(self, \"InstanceWithUsername\",\n    engine=engine,\n    vpc=vpc,\n    credentials=rds.Credentials.from_generated_secret(\"postgres\")\n)\n\nrds.DatabaseInstance(self, \"InstanceWithUsernameAndPassword\",\n    engine=engine,\n    vpc=vpc,\n    credentials=rds.Credentials.from_password(\"postgres\", SecretValue.ssm_secure(\"/dbPassword\", \"1\"))\n)\n\nmy_secret = secretsmanager.Secret.from_secret_name(self, \"DBSecret\", \"myDBLoginInfo\")\nrds.DatabaseInstance(self, \"InstanceWithSecretLogin\",\n    engine=engine,\n    vpc=vpc,\n    credentials=rds.Credentials.from_secret(my_secret)\n)\n```\n\nSecrets generated by `fromGeneratedSecret()` can be customized:\n\n```python\n# vpc: ec2.Vpc\n\nengine = rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3)\nmy_key = kms.Key(self, \"MyKey\")\n\nrds.DatabaseInstance(self, \"InstanceWithCustomizedSecret\",\n    engine=engine,\n    vpc=vpc,\n    credentials=rds.Credentials.from_generated_secret(\"postgres\",\n        secret_name=\"my-cool-name\",\n        encryption_key=my_key,\n        exclude_characters=\"!&*^#@()\",\n        replica_regions=[secretsmanager.ReplicaRegion(region=\"eu-west-1\"), secretsmanager.ReplicaRegion(region=\"eu-west-2\")]\n    )\n)\n```\n\n### Snapshot credentials\n\nAs noted above, Databases created with `DatabaseInstanceFromSnapshot` or `ServerlessClusterFromSnapshot` will not create user and auto-generated password by default because it's not possible to change the master username for a snapshot. Instead, they will use the existing username and password from the snapshot. You can still generate a new password - to generate a secret similarly to the other constructs, pass in credentials with `fromGeneratedSecret()` or `fromGeneratedPassword()`.\n\n```python\n# vpc: ec2.Vpc\n\nengine = rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3)\nmy_key = kms.Key(self, \"MyKey\")\n\nrds.DatabaseInstanceFromSnapshot(self, \"InstanceFromSnapshotWithCustomizedSecret\",\n    engine=engine,\n    vpc=vpc,\n    snapshot_identifier=\"mySnapshot\",\n    credentials=rds.SnapshotCredentials.from_generated_secret(\"username\",\n        encryption_key=my_key,\n        exclude_characters=\"!&*^#@()\",\n        replica_regions=[secretsmanager.ReplicaRegion(region=\"eu-west-1\"), secretsmanager.ReplicaRegion(region=\"eu-west-2\")]\n    )\n)\n```\n\n## Connecting\n\nTo control who can access the cluster or instance, use the `.connections` attribute. RDS databases have\na default port, so you don't need to specify the port:\n\n```python\n# cluster: rds.DatabaseCluster\n\ncluster.connections.allow_from_any_ipv4(ec2.Port.all_traffic(), \"Open to the world\")\n```\n\nThe endpoints to access your database cluster will be available as the `.clusterEndpoint` and `.readerEndpoint`\nattributes:\n\n```python\n# cluster: rds.DatabaseCluster\n\nwrite_address = cluster.cluster_endpoint.socket_address\n```\n\nFor an instance database:\n\n```python\n# instance: rds.DatabaseInstance\n\naddress = instance.instance_endpoint.socket_address\n```\n\n## Rotating credentials\n\nWhen the master password is generated and stored in AWS Secrets Manager, it can be rotated automatically:\n\n```python\nimport aws_cdk.core as cdk\n\n# instance: rds.DatabaseInstance\n\ninstance.add_rotation_single_user(\n    automatically_after=cdk.Duration.days(7),  # defaults to 30 days\n    exclude_characters=\"!@#$%^&*\"\n)\n```\n\n```python\ncluster = rds.DatabaseCluster(stack, \"Database\",\n    engine=rds.DatabaseClusterEngine.AURORA,\n    instance_props=rds.InstanceProps(\n        instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.SMALL),\n        vpc=vpc\n    )\n)\n\ncluster.add_rotation_single_user()\n```\n\nThe multi user rotation scheme is also available:\n\n```python\n# instance: rds.DatabaseInstance\n# my_imported_secret: rds.DatabaseSecret\n\ninstance.add_rotation_multi_user(\"MyUser\",\n    secret=my_imported_secret\n)\n```\n\nIt's also possible to create user credentials together with the instance/cluster and add rotation:\n\n```python\n# instance: rds.DatabaseInstance\n\nmy_user_secret = rds.DatabaseSecret(self, \"MyUserSecret\",\n    username=\"myuser\",\n    secret_name=\"my-user-secret\",  # optional, defaults to a CloudFormation-generated name\n    master_secret=instance.secret,\n    exclude_characters=\"{}[]()'\\\"/\\\\\"\n)\nmy_user_secret_attached = my_user_secret.attach(instance) # Adds DB connections information in the secret\n\ninstance.add_rotation_multi_user(\"MyUser\",  # Add rotation using the multi user scheme\n    secret=my_user_secret_attached)\n```\n\n**Note**: This user must be created manually in the database using the master credentials.\nThe rotation will start as soon as this user exists.\n\nAccess to the Secrets Manager API is required for the secret rotation. This can be achieved either with\ninternet connectivity (through NAT) or with a VPC interface endpoint. By default, the rotation Lambda function\nis deployed in the same subnets as the instance/cluster. If access to the Secrets Manager API is not possible from\nthose subnets or using the default API endpoint, use the `vpcSubnets` and/or `endpoint` options:\n\n```python\n# instance: rds.DatabaseInstance\n# my_endpoint: ec2.InterfaceVpcEndpoint\n\n\ninstance.add_rotation_single_user(\n    vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT),  # Place rotation Lambda in private subnets\n    endpoint=my_endpoint\n)\n```\n\nSee also [@aws-cdk/aws-secretsmanager](https://github.com/aws/aws-cdk/blob/master/packages/%40aws-cdk/aws-secretsmanager/README.md) for credentials rotation of existing clusters/instances.\n\n## IAM Authentication\n\nYou can also authenticate to a database instance using AWS Identity and Access Management (IAM) database authentication;\nSee [https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html) for more information\nand a list of supported versions and limitations.\n\n**Note**: `grantConnect()` does not currently work - see [this GitHub issue](https://github.com/aws/aws-cdk/issues/11851).\n\nThe following example shows enabling IAM authentication for a database instance and granting connection access to an IAM role.\n\n```python\n# vpc: ec2.Vpc\n\ninstance = rds.DatabaseInstance(self, \"Instance\",\n    engine=rds.DatabaseInstanceEngine.mysql(version=rds.MysqlEngineVersion.VER_8_0_19),\n    vpc=vpc,\n    iam_authentication=True\n)\nrole = iam.Role(self, \"DBRole\", assumed_by=iam.AccountPrincipal(self.account))\ninstance.grant_connect(role)\n```\n\nThe following example shows granting connection access for RDS Proxy to an IAM role.\n\n```python\n# vpc: ec2.Vpc\n\ncluster = rds.DatabaseCluster(self, \"Database\",\n    engine=rds.DatabaseClusterEngine.AURORA,\n    instance_props=rds.InstanceProps(vpc=vpc)\n)\n\nproxy = rds.DatabaseProxy(self, \"Proxy\",\n    proxy_target=rds.ProxyTarget.from_cluster(cluster),\n    secrets=[cluster.secret],\n    vpc=vpc\n)\n\nrole = iam.Role(self, \"DBProxyRole\", assumed_by=iam.AccountPrincipal(self.account))\nproxy.grant_connect(role, \"admin\")\n```\n\n**Note**: In addition to the setup above, a database user will need to be created to support IAM auth.\nSee [https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.DBAccounts.html](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.DBAccounts.html) for setup instructions.\n\n## Kerberos Authentication\n\nYou can also authenticate using Kerberos to a database instance using AWS Managed Microsoft AD for authentication;\nSee [https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html) for more information\nand a list of supported versions and limitations.\n\nThe following example shows enabling domain support for a database instance and creating an IAM role to access\nDirectory Services.\n\n```python\n# vpc: ec2.Vpc\n\nrole = iam.Role(self, \"RDSDirectoryServicesRole\",\n    assumed_by=iam.ServicePrincipal(\"rds.amazonaws.com\"),\n    managed_policies=[\n        iam.ManagedPolicy.from_aws_managed_policy_name(\"service-role/AmazonRDSDirectoryServiceAccess\")\n    ]\n)\ninstance = rds.DatabaseInstance(self, \"Instance\",\n    engine=rds.DatabaseInstanceEngine.mysql(version=rds.MysqlEngineVersion.VER_8_0_19),\n    vpc=vpc,\n    domain=\"d-????????\",  # The ID of the domain for the instance to join.\n    domain_role=role\n)\n```\n\n**Note**: In addition to the setup above, you need to make sure that the database instance has network connectivity\nto the domain controllers. This includes enabling cross-VPC traffic if in a different VPC and setting up the\nappropriate security groups/network ACL to allow traffic between the database instance and domain controllers.\nOnce configured, see [https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html) for details\non configuring users for each available database engine.\n\n## Metrics\n\nDatabase instances and clusters both expose metrics (`cloudwatch.Metric`):\n\n```python\n# The number of database connections in use (average over 5 minutes)\n# instance: rds.DatabaseInstance\n\n# Average CPU utilization over 5 minutes\n# cluster: rds.DatabaseCluster\n\ndb_connections = instance.metric_database_connections()\ncpu_utilization = cluster.metric_cPUUtilization()\n\n# The average amount of time taken per disk I/O operation (average over 1 minute)\nread_latency = instance.metric(\"ReadLatency\", statistic=\"Average\", period=Duration.seconds(60))\n```\n\n## Enabling S3 integration\n\nData in S3 buckets can be imported to and exported from certain database engines using SQL queries. To enable this\nfunctionality, set the `s3ImportBuckets` and `s3ExportBuckets` properties for import and export respectively. When\nconfigured, the CDK automatically creates and configures IAM roles as required.\nAdditionally, the `s3ImportRole` and `s3ExportRole` properties can be used to set this role directly.\n\nYou can read more about loading data to (or from) S3 here:\n\n* Aurora MySQL - [import](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.LoadFromS3.html)\n  and [export](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.SaveIntoS3.html).\n* Aurora PostgreSQL - [import](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraPostgreSQL.Migrating.html#USER_PostgreSQL.S3Import)\n  and [export](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/postgresql-s3-export.html).\n* Microsoft SQL Server - [import and export](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/SQLServer.Procedural.Importing.html)\n* PostgreSQL - [import](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/PostgreSQL.Procedural.Importing.html)\n  and [export](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/postgresql-s3-export.html)\n* Oracle - [import and export](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-s3-integration.html)\n\nThe following snippet sets up a database cluster with different S3 buckets where the data is imported and exported -\n\n```python\nimport aws_cdk.aws_s3 as s3\n\n# vpc: ec2.Vpc\n\nimport_bucket = s3.Bucket(self, \"importbucket\")\nexport_bucket = s3.Bucket(self, \"exportbucket\")\nrds.DatabaseCluster(self, \"dbcluster\",\n    engine=rds.DatabaseClusterEngine.AURORA,\n    instance_props=rds.InstanceProps(\n        vpc=vpc\n    ),\n    s3_import_buckets=[import_bucket],\n    s3_export_buckets=[export_bucket]\n)\n```\n\n## Creating a Database Proxy\n\nAmazon RDS Proxy sits between your application and your relational database to efficiently manage\nconnections to the database and improve scalability of the application. Learn more about at [Amazon RDS Proxy](https://aws.amazon.com/rds/proxy/)\n\nThe following code configures an RDS Proxy for a `DatabaseInstance`.\n\n```python\n# vpc: ec2.Vpc\n# security_group: ec2.SecurityGroup\n# secrets: List[secretsmanager.Secret[]]\n# db_instance: rds.DatabaseInstance\n\n\nproxy = db_instance.add_proxy(\"proxy\",\n    borrow_timeout=Duration.seconds(30),\n    max_connections_percent=50,\n    secrets=secrets,\n    vpc=vpc\n)\n```\n\n## Exporting Logs\n\nYou can publish database logs to Amazon CloudWatch Logs. With CloudWatch Logs, you can perform real-time analysis of the log data,\nstore the data in highly durable storage, and manage the data with the CloudWatch Logs Agent. This is available for both database\ninstances and clusters; the types of logs available depend on the database type and engine being used.\n\n```python\nimport aws_cdk.aws_logs as logs\n# my_logs_publishing_role: iam.Role\n# vpc: ec2.Vpc\n\n\n# Exporting logs from a cluster\ncluster = rds.DatabaseCluster(self, \"Database\",\n    engine=rds.DatabaseClusterEngine.aurora(\n        version=rds.AuroraEngineVersion.VER_1_17_9\n    ),\n    instance_props=rds.InstanceProps(\n        vpc=vpc\n    ),\n    cloudwatch_logs_exports=[\"error\", \"general\", \"slowquery\", \"audit\"],  # Export all available MySQL-based logs\n    cloudwatch_logs_retention=logs.RetentionDays.THREE_MONTHS,  # Optional - default is to never expire logs\n    cloudwatch_logs_retention_role=my_logs_publishing_role\n)\n\n# Exporting logs from an instance\ninstance = rds.DatabaseInstance(self, \"Instance\",\n    engine=rds.DatabaseInstanceEngine.postgres(\n        version=rds.PostgresEngineVersion.VER_12_3\n    ),\n    vpc=vpc,\n    cloudwatch_logs_exports=[\"postgresql\"]\n)\n```\n\n## Option Groups\n\nSome DB engines offer additional features that make it easier to manage data and databases, and to provide additional security for your database.\nAmazon RDS uses option groups to enable and configure these features. An option group can specify features, called options,\nthat are available for a particular Amazon RDS DB instance.\n\n```python\n# vpc: ec2.Vpc\n# security_group: ec2.SecurityGroup\n\n\nrds.OptionGroup(self, \"Options\",\n    engine=rds.DatabaseInstanceEngine.oracle_se2(\n        version=rds.OracleEngineVersion.VER_19\n    ),\n    configurations=[rds.OptionConfiguration(\n        name=\"OEM\",\n        port=5500,\n        vpc=vpc,\n        security_groups=[security_group]\n    )\n    ]\n)\n```\n\n## Parameter Groups\n\nDatabase parameters specify how the database is configured.\nFor example, database parameters can specify the amount of resources, such as memory, to allocate to a database.\nYou manage your database configuration by associating your DB instances with parameter groups.\nAmazon RDS defines parameter groups with default settings.\n\nYou can create your own parameter group for your cluster or instance and associate it with your database:\n\n```python\n# vpc: ec2.Vpc\n\n\nparameter_group = rds.ParameterGroup(self, \"ParameterGroup\",\n    engine=rds.DatabaseInstanceEngine.sql_server_ee(\n        version=rds.SqlServerEngineVersion.VER_11\n    ),\n    parameters={\n        \"locks\": \"100\"\n    }\n)\n\nrds.DatabaseInstance(self, \"Database\",\n    engine=rds.DatabaseInstanceEngine.SQL_SERVER_EE,\n    vpc=vpc,\n    parameter_group=parameter_group\n)\n```\n\nAnother way to specify parameters is to use the inline field `parameters` that creates an RDS parameter group for you.\nYou can use this if you do not want to reuse the parameter group instance for different instances:\n\n```python\n# vpc: ec2.Vpc\n\n\nrds.DatabaseInstance(self, \"Database\",\n    engine=rds.DatabaseInstanceEngine.sql_server_ee(version=rds.SqlServerEngineVersion.VER_11),\n    vpc=vpc,\n    parameters={\n        \"locks\": \"100\"\n    }\n)\n```\n\nYou cannot specify a parameter map and a parameter group at the same time.\n\n## Serverless\n\n[Amazon Aurora Serverless](https://aws.amazon.com/rds/aurora/serverless/) is an on-demand, auto-scaling configuration for Amazon\nAurora. The database will automatically start up, shut down, and scale capacity\nup or down based on your application's needs. It enables you to run your database\nin the cloud without managing any database instances.\n\nThe following example initializes an Aurora Serverless PostgreSql cluster.\nAurora Serverless clusters can specify scaling properties which will be used to\nautomatically scale the database cluster seamlessly based on the workload.\n\n```python\n# vpc: ec2.Vpc\n\n\ncluster = rds.ServerlessCluster(self, \"AnotherCluster\",\n    engine=rds.DatabaseClusterEngine.AURORA_POSTGRESQL,\n    parameter_group=rds.ParameterGroup.from_parameter_group_name(self, \"ParameterGroup\", \"default.aurora-postgresql10\"),\n    vpc=vpc,\n    scaling=rds.ServerlessScalingOptions(\n        auto_pause=Duration.minutes(10),  # default is to pause after 5 minutes of idle time\n        min_capacity=rds.AuroraCapacityUnit.ACU_8,  # default is 2 Aurora capacity units (ACUs)\n        max_capacity=rds.AuroraCapacityUnit.ACU_32\n    )\n)\n```\n\nAurora Serverless Clusters do not support the following features:\n\n* Loading data from an Amazon S3 bucket\n* Saving data to an Amazon S3 bucket\n* Invoking an AWS Lambda function with an Aurora MySQL native function\n* Aurora replicas\n* Backtracking\n* Multi-master clusters\n* Database cloning\n* IAM database cloning\n* IAM database authentication\n* Restoring a snapshot from MySQL DB instance\n* Performance Insights\n* RDS Proxy\n\nRead more about the [limitations of Aurora Serverless](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless.html#aurora-serverless.limitations)\n\nLearn more about using Amazon Aurora Serverless by reading the [documentation](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless.html)\n\nUse `ServerlessClusterFromSnapshot` to create a serverless cluster from a snapshot:\n\n```python\n# vpc: ec2.Vpc\n\nrds.ServerlessClusterFromSnapshot(self, \"Cluster\",\n    engine=rds.DatabaseClusterEngine.AURORA_MYSQL,\n    vpc=vpc,\n    snapshot_identifier=\"mySnapshot\"\n)\n```\n\n### Data API\n\nYou can access your Aurora Serverless DB cluster using the built-in Data API. The Data API doesn't require a persistent connection to the DB cluster. Instead, it provides a secure HTTP endpoint and integration with AWS SDKs.\n\nThe following example shows granting Data API access to a Lamba function.\n\n```python\n# vpc: ec2.Vpc\n\n# code: lambda.Code\n\n\ncluster = rds.ServerlessCluster(self, \"AnotherCluster\",\n    engine=rds.DatabaseClusterEngine.AURORA_MYSQL,\n    vpc=vpc,  # this parameter is optional for serverless Clusters\n    enable_data_api=True\n)\nfn = lambda_.Function(self, \"MyFunction\",\n    runtime=lambda_.Runtime.NODEJS_14_X,\n    handler=\"index.handler\",\n    code=code,\n    environment={\n        \"CLUSTER_ARN\": cluster.cluster_arn,\n        \"SECRET_ARN\": cluster.secret.secret_arn\n    }\n)\ncluster.grant_data_api_access(fn)\n```\n\n**Note**: To invoke the Data API, the resource will need to read the secret associated with the cluster.\n\nTo learn more about using the Data API, see the [documentation](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html).\n\n### Default VPC\n\nThe `vpc` parameter is optional.\n\nIf not provided, the cluster will be created in the default VPC of the account and region.\nAs this VPC is not deployed with AWS CDK, you can't configure the `vpcSubnets`, `subnetGroup` or `securityGroups` of the Aurora Serverless Cluster.\nIf you want to provide one of `vpcSubnets`, `subnetGroup` or `securityGroups` parameter, please provide a `vpc`.\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "The CDK Construct Library for AWS::RDS",
    "version": "1.204.0",
    "project_urls": {
        "Homepage": "https://github.com/aws/aws-cdk",
        "Source": "https://github.com/aws/aws-cdk.git"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8a105be97e627771ad07005ee0d13c474764921c41406a0bdcad46dae7bb3451",
                "md5": "b4001351906a6bfbad2b90e3319d51ee",
                "sha256": "dcaa94439ea1b2797178bac81532b4b6feec9471d7555e91030c3dd7168bf37f"
            },
            "downloads": -1,
            "filename": "aws_cdk.aws_rds-1.204.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "b4001351906a6bfbad2b90e3319d51ee",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "~=3.7",
            "size": 976224,
            "upload_time": "2023-06-19T21:00:27",
            "upload_time_iso_8601": "2023-06-19T21:00:27.219030Z",
            "url": "https://files.pythonhosted.org/packages/8a/10/5be97e627771ad07005ee0d13c474764921c41406a0bdcad46dae7bb3451/aws_cdk.aws_rds-1.204.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b347ff7131880b0797321fb992906a8edb1848c2202fac3080e157e7de428245",
                "md5": "2a04d1d713a7a70b786e061bc236b775",
                "sha256": "009dcdbd49f6eb3b97e045fc860380a74efd64152b938b5ebcb0c270ad85623c"
            },
            "downloads": -1,
            "filename": "aws-cdk.aws-rds-1.204.0.tar.gz",
            "has_sig": false,
            "md5_digest": "2a04d1d713a7a70b786e061bc236b775",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "~=3.7",
            "size": 980853,
            "upload_time": "2023-06-19T21:06:47",
            "upload_time_iso_8601": "2023-06-19T21:06:47.663270Z",
            "url": "https://files.pythonhosted.org/packages/b3/47/ff7131880b0797321fb992906a8edb1848c2202fac3080e157e7de428245/aws-cdk.aws-rds-1.204.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-06-19 21:06:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "aws",
    "github_project": "aws-cdk",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "aws-cdk.aws-rds"
}
        
Elapsed time: 0.09880s