Skip to main content

The CDK Construct Library for AWS::RDS

Project description

Amazon Relational Database Service Construct Library

cfn-resources: Stable

cdk-constructs: Stable


# Example automatically generated. See https://github.com/aws/jsii/issues/826
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:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
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={
        # optional , defaults to t3.medium
        "instance_type": ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.SMALL),
        "vpc_subnets": {
            "subnet_type": ec2.SubnetType.PRIVATE
        },
        "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.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
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:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
rds.DatabaseClusterFromSnapshot(stack, "Database",
    engine=rds.DatabaseClusterEngine.aurora(version=rds.AuroraEngineVersion.VER_1_22_2),
    instance_props={
        "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:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
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={
        "subnet_type": ec2.SubnetType.PRIVATE
    }
)

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.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
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 Example for max storage configuration:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
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:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
rds.DatabaseInstanceFromSnapshot(stack, "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(stack, "ReadReplica",
    source_database_instance=source_instance,
    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.LARGE),
    vpc=vpc
)

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

# Example automatically generated. See https://github.com/aws/jsii/issues/826
# 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=[OptionConfiguration(
        name="LOCATOR"
    ), 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=False,
    option_group=option_group,
    parameter_group=parameter_group
)

# 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_10_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

# Example automatically generated. See https://github.com/aws/jsii/issues/826
# 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=[OptionConfiguration(
        name="LOCATOR"
    ), 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=False,
    option_group=option_group,
    parameter_group=parameter_group
)

# 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_10_X
)

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

Instance events

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

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
rule = instance.on_event("InstanceEvent", target=targets.LambdaFunction(fn))

Login credentials

By default, database instances and clusters 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.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
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)
)

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:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
cluster.connections.allow_from_any_ipv4("Open to the world")

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

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
write_address = cluster.cluster_endpoint.socket_address

For an instance database:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
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:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
instance.add_rotation_single_user(
    automatically_after=cdk.Duration.days(7), # defaults to 30 days
    exclude_characters="!@#$%^&*"
)
# Example automatically generated. See https://github.com/aws/jsii/issues/826
cluster = rds.DatabaseCluster(stack, "Database",
    engine=rds.DatabaseClusterEngine.AURORA,
    instance_props={
        "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:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
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:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
my_user_secret = rds.DatabaseSecret(self, "MyUserSecret",
    username="myuser",
    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.

See also @aws-cdk/aws-secretsmanager 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 for more information and a list of supported versions and limitations.

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

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
instance = rds.DatabaseInstance(stack, "Instance",
    engine=rds.DatabaseInstanceEngine.mysql(version=rds.MysqlEngineVersion.VER_8_0_19),
    vpc=vpc,
    iam_authentication=True
)
role = Role(stack, "DBRole", assumed_by=AccountPrincipal(stack.account))
instance.grant_connect(role)

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 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 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.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
role = iam.Role(stack, "RDSDirectoryServicesRole",
    assumed_by=iam.ServicePrincipal("rds.amazonaws.com"),
    managed_policies=[
        iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AmazonRDSDirectoryServiceAccess")
    ]
)
instance = rds.DatabaseInstance(stack, "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 for details on configuring users for each available database engine.

Metrics

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

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# The number of database connections in use (average over 5 minutes)
db_connections = instance.metric_database_connections()

# Average CPU utilization over 5 minutes
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_sec=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:

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

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_s3 as s3

import_bucket = s3.Bucket(self, "importbucket")
export_bucket = s3.Bucket(self, "exportbucket")
rds.DatabaseCluster(self, "dbcluster",
    # ...
    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

The following code configures an RDS Proxy for a DatabaseInstance.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.core as cdk
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_rds as rds
import aws_cdk.aws_secretsmanager as secrets

vpc =
security_group =
secrets = [...]
db_instance =

proxy = db_instance.add_proxy("proxy",
    connection_borrow_timeout=cdk.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.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# Exporting logs from a cluster
cluster = rds.DatabaseCluster(self, "Database",
    engine=rds.DatabaseClusterEngine.aurora({
        "version": rds.AuroraEngineVersion.VER_1_17_9
    }, cloudwatch_logs_exports, ["error", "general", "slowquery", "audit"], cloudwatch_logs_retention, logs.RetentionDays.THREE_MONTHS, 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
    ),
    # ...
    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.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
vpc =
security_group =
rds.OptionGroup(stack, "Options",
    engine=rds.DatabaseInstanceEngine.oracle_se2(
        version=rds.OracleEngineVersion.VER_19
    ),
    configurations=[{
        "name": "OEM",
        "port": 5500,
        "vpc": vpc,
        "security_groups": [security_group]
    }
    ]
)

Serverless

Amazon 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.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_rds as rds

vpc = ec2.Vpc(self, "myrdsvpc")

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=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

Learn more about using Amazon Aurora Serverless by reading the documentation

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.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_lambda as lambda_
import aws_cdk.aws_rds as rds

vpc = ec2.Vpc(self, "MyVPC")

cluster = rds.ServerlessCluster(self, "AnotherCluster",
    engine=rds.DatabaseClusterEngine.AURORA_MYSQL,
    vpc=vpc,
    enable_data_api=True
)

fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_10_X,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    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.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for aws-cdk.aws-rds, version 1.75.0
Filename, size File type Python version Upload date Hashes
Filename, size aws_cdk.aws_rds-1.75.0-py3-none-any.whl (402.4 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size aws-cdk.aws-rds-1.75.0.tar.gz (409.9 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page