Package software.amazon.awscdk.services.rds


package software.amazon.awscdk.services.rds

Amazon Relational Database Service Construct Library

 import software.amazon.awscdk.services.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:

You must specify the instance to use as the writer, along with an optional list of readers (up to 15).

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder().version(AuroraMysqlEngineVersion.VER_3_01_0).build()))
         .credentials(Credentials.fromGeneratedSecret("clusteradmin")) // Optional - will default to 'admin' username and generated password
         .writer(ClusterInstance.provisioned("writer", ProvisionedClusterInstanceProps.builder()
                 .publiclyAccessible(false)
                 .build()))
         .readers(List.of(ClusterInstance.provisioned("reader1", ProvisionedClusterInstanceProps.builder().promotionTier(1).build()), ClusterInstance.serverlessV2("reader2")))
         .vpcSubnets(SubnetSelection.builder()
                 .subnetType(SubnetType.PRIVATE_WITH_EGRESS)
                 .build())
         .vpc(vpc)
         .build();
 

To adopt Aurora I/O-Optimized, specify DBClusterStorageType.AURORA_IOPT1 on the storageType property.

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraPostgres(AuroraPostgresClusterEngineProps.builder().version(AuroraPostgresEngineVersion.VER_15_2).build()))
         .credentials(Credentials.fromUsername("adminuser", CredentialsFromUsernameOptions.builder().password(SecretValue.unsafePlainText("7959866cacc02c2d243ecfe177464fe6")).build()))
         .writer(ClusterInstance.provisioned("writer", ProvisionedClusterInstanceProps.builder()
                 .publiclyAccessible(false)
                 .build()))
         .readers(List.of(ClusterInstance.provisioned("reader")))
         .storageType(DBClusterStorageType.AURORA_IOPT1)
         .vpcSubnets(SubnetSelection.builder()
                 .subnetType(SubnetType.PRIVATE_WITH_EGRESS)
                 .build())
         .vpc(vpc)
         .build();
 

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.

 AuroraMysqlEngineVersion customEngineVersion = 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.

To use dual-stack mode, specify NetworkType.DUAL on the networkType property:

 Vpc vpc;
 // VPC and subnets must have IPv6 CIDR blocks
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder().version(AuroraMysqlEngineVersion.VER_3_02_1).build()))
         .writer(ClusterInstance.provisioned("writer", ProvisionedClusterInstanceProps.builder()
                 .publiclyAccessible(false)
                 .build()))
         .vpc(vpc)
         .networkType(NetworkType.DUAL)
         .build();
 

For more information about dual-stack mode, see Working with a DB cluster in a VPC.

Use DatabaseClusterFromSnapshot to create a cluster from a snapshot:

 Vpc vpc;
 
 DatabaseClusterFromSnapshot.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.aurora(AuroraClusterEngineProps.builder().version(AuroraEngineVersion.VER_1_22_2).build()))
         .writer(ClusterInstance.provisioned("writer"))
         .vpc(vpc)
         .snapshotIdentifier("mySnapshot")
         .build();
 

Updating the database instances in a cluster

Database cluster instances may be updated in bulk or on a rolling basis.

An update to all instances in a cluster may cause significant downtime. To reduce the downtime, set the instanceUpdateBehavior property in DatabaseClusterBaseProps to InstanceUpdateBehavior.ROLLING. This adds a dependency between each instance so the update is performed on only one instance at a time.

Use InstanceUpdateBehavior.BULK to update all instances at once.

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder().version(AuroraMysqlEngineVersion.VER_3_01_0).build()))
         .writer(ClusterInstance.provisioned("Instance", ProvisionedClusterInstanceProps.builder()
                 .instanceType(InstanceType.of(InstanceClass.BURSTABLE3, InstanceSize.SMALL))
                 .build()))
         .readers(List.of(ClusterInstance.provisioned("reader")))
         .instanceUpdateBehaviour(InstanceUpdateBehaviour.ROLLING) // Optional - defaults to rds.InstanceUpdateBehaviour.BULK
         .vpc(vpc)
         .build();
 

Serverless V2 instances in a Cluster

It is possible to create an RDS cluster with both serverlessV2 and provisioned instances. For example, this will create a cluster with a provisioned writer and a serverless v2 reader.

Note Before getting starting with this type of cluster it is highly recommended that you read through the Developer Guide which goes into much more detail on the things you need to take into consideration.

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder().version(AuroraMysqlEngineVersion.VER_3_01_0).build()))
         .writer(ClusterInstance.provisioned("writer"))
         .readers(List.of(ClusterInstance.serverlessV2("reader")))
         .vpc(vpc)
         .build();
 

Monitoring

There are some CloudWatch metrics that are important for Aurora Serverless v2.

  • ServerlessDatabaseCapacity: An instance-level metric that can also be evaluated at the cluster level. At the cluster-level it represents the average capacity of all the instances in the cluster.
  • ACUUtilization: Value of the ServerlessDatabaseCapacity/ max ACU of the cluster.

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder().version(AuroraMysqlEngineVersion.VER_3_01_0).build()))
         .writer(ClusterInstance.provisioned("writer"))
         .readers(List.of(ClusterInstance.serverlessV2("reader")))
         .vpc(vpc)
         .build();
 
 cluster.metricServerlessDatabaseCapacity(MetricOptions.builder()
         .period(Duration.minutes(10))
         .build()).createAlarm(this, "capacity", CreateAlarmOptions.builder()
         .threshold(1.5)
         .evaluationPeriods(3)
         .build());
 cluster.metricACUUtilization(MetricOptions.builder()
         .period(Duration.minutes(10))
         .build()).createAlarm(this, "alarm", CreateAlarmOptions.builder()
         .evaluationPeriods(3)
         .threshold(90)
         .build());
 

Capacity & Scaling

There are some things to take into consideration with Aurora Serverless v2.

To create a cluster that can support serverless v2 instances you configure a minimum and maximum capacity range on the cluster. This is an example showing the default values:

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder().version(AuroraMysqlEngineVersion.VER_3_01_0).build()))
         .writer(ClusterInstance.serverlessV2("writer"))
         .serverlessV2MinCapacity(0.5)
         .serverlessV2MaxCapacity(2)
         .vpc(vpc)
         .build();
 

The capacity is defined as a number of Aurora capacity units (ACUs). You can specify in half-step increments (40, 40.5, 41, etc). Each serverless instance in the cluster inherits the capacity that is defined on the cluster. It is not possible to configure separate capacity at the instance level.

The maximum capacity is mainly used for budget control since it allows you to set a cap on how high your instance can scale.

The minimum capacity is a little more involved. This controls a couple different things.

  • The scale-up rate is proportional to the current capacity (larger instances scale up faster)

    • Adjust the minimum capacity to obtain a suitable scaling rate
  • Network throughput is proportional to capacity

Info More complete details can be found in the docs

Another way that you control the capacity/scaling of your serverless v2 reader instances is based on the promotion tier which can be between 0-15. Any serverless v2 instance in the 0-1 tiers will scale alongside the writer even if the current read load does not require the capacity. This is because instances in the 0-1 tier are first priority for failover and Aurora wants to ensure that in the event of a failover the reader that gets promoted is scaled to handle the write load.

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder().version(AuroraMysqlEngineVersion.VER_3_01_0).build()))
         .writer(ClusterInstance.serverlessV2("writer"))
         .readers(List.of(ClusterInstance.serverlessV2("reader1", ServerlessV2ClusterInstanceProps.builder().scaleWithWriter(true).build()), ClusterInstance.serverlessV2("reader2")))
         .vpc(vpc)
         .build();
 

  • When the writer scales up, any readers in tier 0-1 will scale up to match
  • Scaling for tier 2-15 is independent of what is happening on the writer
  • Readers in tier 2-15 scale up based on read load against the individual reader

When configuring your cluster it is important to take this into consideration and ensure that in the event of a failover there is an instance that is scaled up to take over.

Mixing Serverless v2 and Provisioned instances

You are able to create a cluster that has both provisioned and serverless instances. This blog post has an excellent guide on choosing between serverless and provisioned instances based on use case.

There are a couple of high level differences:

  • Engine Version (serverless only supports MySQL 8+ & PostgreSQL 13+)
  • Memory up to 256GB can be supported by serverless

Provisioned writer

With a provisioned writer and serverless v2 readers, some of the serverless readers will need to be configured to scale with the writer so they can act as failover targets. You will need to determine the correct capacity based on the provisioned instance type and it's utilization.

As an example, if the CPU utilization for a db.r6g.4xlarge (128 GB) instance stays at 10% most times, then the minimum ACUs may be set at 6.5 ACUs (10% of 128 GB) and maximum may be set at 64 ACUs (64x2GB=128GB). Keep in mind that the speed at which the serverless instance can scale up is determined by the minimum capacity so if your cluster has spiky workloads you may need to set a higher minimum capacity.

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder().version(AuroraMysqlEngineVersion.VER_3_01_0).build()))
         .writer(ClusterInstance.provisioned("writer", ProvisionedClusterInstanceProps.builder()
                 .instanceType(InstanceType.of(InstanceClass.R6G, InstanceSize.XLARGE4))
                 .build()))
         .serverlessV2MinCapacity(6.5)
         .serverlessV2MaxCapacity(64)
         .readers(List.of(ClusterInstance.serverlessV2("reader1", ServerlessV2ClusterInstanceProps.builder().scaleWithWriter(true).build()), ClusterInstance.serverlessV2("reader2")))
         .vpc(vpc)
         .build();
 

In the above example reader1 will scale with the writer based on the writer's utilization. So if the writer were to go to 50% utilization then reader1 would scale up to use 32 ACUs. If the read load stayed consistent then reader2 may remain at 6.5 since it is not configured to scale with the writer.

If one of your Aurora Serverless v2 DB instances consistently reaches the limit of its maximum capacity, Aurora indicates this condition by setting the DB instance to a status of incompatible-parameters. While the DB instance has the incompatible-parameters status, some operations are blocked. For example, you can't upgrade the engine version.

CA certificate

Use the caCertificate property to specify the CA certificates to use for a cluster instances:

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder().version(AuroraMysqlEngineVersion.VER_3_01_0).build()))
         .writer(ClusterInstance.provisioned("writer", ProvisionedClusterInstanceProps.builder()
                 .caCertificate(CaCertificate.RDS_CA_RDS2048_G1)
                 .build()))
         .readers(List.of(ClusterInstance.serverlessV2("reader", ServerlessV2ClusterInstanceProps.builder()
                 .caCertificate(CaCertificate.of("custom-ca"))
                 .build())))
         .vpc(vpc)
         .build();
 

Migrating from instanceProps

Creating instances in a DatabaseCluster using instanceProps & instances is deprecated. To migrate to the new properties you can provide the isFromLegacyInstanceProps property.

For example, in order to migrate from this deprecated config:

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder()
                 .version(AuroraMysqlEngineVersion.VER_3_03_0)
                 .build()))
         .instances(2)
         .instanceProps(InstanceProps.builder()
                 .instanceType(InstanceType.of(InstanceClass.BURSTABLE3, InstanceSize.SMALL))
                 .vpcSubnets(SubnetSelection.builder().subnetType(SubnetType.PUBLIC).build())
                 .vpc(vpc)
                 .build())
         .build();
 

You would need to migrate to this. The old method of providing instanceProps and instances will create the number of instances that you provide. The first instance will be the writer and the rest will be the readers. It's important that the id that you provide is Instance{NUMBER}. The writer should always be Instance1 and the readers will increment from there.

Make sure to run a cdk diff before deploying to make sure that all changes are expected. Always test the migration in a non-production environment first.

 Vpc vpc;
 Map<String, Object> instanceProps = Map.of(
         "instanceType", InstanceType.of(InstanceClass.BURSTABLE3, InstanceSize.SMALL),
         "isFromLegacyInstanceProps", true);
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder()
                 .version(AuroraMysqlEngineVersion.VER_3_03_0)
                 .build()))
         .vpcSubnets(SubnetSelection.builder().subnetType(SubnetType.PUBLIC).build())
         .vpc(vpc)
         .writer(ClusterInstance.provisioned("Instance1", ProvisionedClusterInstanceProps.builder()
                 .instanceType(instanceProps.getInstanceType())
                 .isFromLegacyInstanceProps(instanceProps.getIsFromLegacyInstanceProps())
                 .build()))
         .readers(List.of(ClusterInstance.provisioned("Instance2", ProvisionedClusterInstanceProps.builder()
                 .instanceType(instanceProps.getInstanceType())
                 .isFromLegacyInstanceProps(instanceProps.getIsFromLegacyInstanceProps())
                 .build())))
         .build();
 

Starting an instance database

To set up an 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:

 Vpc vpc;
 
 DatabaseInstance instance = DatabaseInstance.Builder.create(this, "Instance")
         .engine(DatabaseInstanceEngine.oracleSe2(OracleSe2InstanceEngineProps.builder().version(OracleEngineVersion.VER_19_0_0_0_2020_04_R1).build()))
         // optional, defaults to m5.large
         .instanceType(InstanceType.of(InstanceClass.BURSTABLE3, InstanceSize.SMALL))
         .credentials(Credentials.fromGeneratedSecret("syscdk")) // Optional - will default to 'admin' username and generated password
         .vpc(vpc)
         .vpcSubnets(SubnetSelection.builder()
                 .subnetType(SubnetType.PRIVATE_WITH_EGRESS)
                 .build())
         .build();
 

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.

 OracleEngineVersion customEngineVersion = 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:

 Vpc vpc;
 
 DatabaseInstance instance = DatabaseInstance.Builder.create(this, "Instance")
         .engine(DatabaseInstanceEngine.postgres(PostgresInstanceEngineProps.builder().version(PostgresEngineVersion.VER_15_2).build()))
         // optional, defaults to m5.large
         .instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.SMALL))
         .vpc(vpc)
         .maxAllocatedStorage(200)
         .build();
 

To use dual-stack mode, specify NetworkType.DUAL on the networkType property:

 Vpc vpc;
 // VPC and subnets must have IPv6 CIDR blocks
 DatabaseInstance instance = DatabaseInstance.Builder.create(this, "Instance")
         .engine(DatabaseInstanceEngine.postgres(PostgresInstanceEngineProps.builder().version(PostgresEngineVersion.VER_15_2).build()))
         .vpc(vpc)
         .networkType(NetworkType.DUAL)
         .publiclyAccessible(false)
         .build();
 

For more information about dual-stack mode, see Working with a DB instance in a VPC.

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

 Vpc vpc;
 
 DatabaseInstance sourceInstance;
 
 DatabaseInstanceFromSnapshot.Builder.create(this, "Instance")
         .snapshotIdentifier("my-snapshot")
         .engine(DatabaseInstanceEngine.postgres(PostgresInstanceEngineProps.builder().version(PostgresEngineVersion.VER_15_2).build()))
         // optional, defaults to m5.large
         .instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.LARGE))
         .vpc(vpc)
         .build();
 DatabaseInstanceReadReplica.Builder.create(this, "ReadReplica")
         .sourceDatabaseInstance(sourceInstance)
         .instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.LARGE))
         .vpc(vpc)
         .build();
 

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:

 // Set open cursors with parameter group
 ParameterGroup parameterGroup = ParameterGroup.Builder.create(this, "ParameterGroup")
         .engine(DatabaseInstanceEngine.oracleSe2(OracleSe2InstanceEngineProps.builder().version(OracleEngineVersion.VER_19_0_0_0_2020_04_R1).build()))
         .parameters(Map.of(
                 "open_cursors", "2500"))
         .build();
 
 OptionGroup optionGroup = OptionGroup.Builder.create(this, "OptionGroup")
         .engine(DatabaseInstanceEngine.oracleSe2(OracleSe2InstanceEngineProps.builder().version(OracleEngineVersion.VER_19_0_0_0_2020_04_R1).build()))
         .configurations(List.of(OptionConfiguration.builder()
                 .name("LOCATOR")
                 .build(), OptionConfiguration.builder()
                 .name("OEM")
                 .port(1158)
                 .vpc(vpc)
                 .build()))
         .build();
 
 // Allow connections to OEM
 optionGroup.optionConnections.OEM.connections.allowDefaultPortFromAnyIpv4();
 
 // Database instance with production values
 DatabaseInstance instance = DatabaseInstance.Builder.create(this, "Instance")
         .engine(DatabaseInstanceEngine.oracleSe2(OracleSe2InstanceEngineProps.builder().version(OracleEngineVersion.VER_19_0_0_0_2020_04_R1).build()))
         .licenseModel(LicenseModel.BRING_YOUR_OWN_LICENSE)
         .instanceType(InstanceType.of(InstanceClass.BURSTABLE3, InstanceSize.MEDIUM))
         .multiAz(true)
         .storageType(StorageType.IO1)
         .credentials(Credentials.fromUsername("syscdk"))
         .vpc(vpc)
         .databaseName("ORCL")
         .storageEncrypted(true)
         .backupRetention(Duration.days(7))
         .monitoringInterval(Duration.seconds(60))
         .enablePerformanceInsights(true)
         .cloudwatchLogsExports(List.of("trace", "audit", "alert", "listener"))
         .cloudwatchLogsRetention(RetentionDays.ONE_MONTH)
         .autoMinorVersionUpgrade(true) // required to be true if LOCATOR is used in the option group
         .optionGroup(optionGroup)
         .parameterGroup(parameterGroup)
         .removalPolicy(RemovalPolicy.DESTROY)
         .build();
 
 // Allow connections on default port from any IPV4
 instance.connections.allowDefaultPortFromAnyIpv4();
 
 // Rotate the master user password every 30 days
 instance.addRotationSingleUser();
 
 // Add alarm for high CPU
 // Add alarm for high CPU
 Alarm.Builder.create(this, "HighCPU")
         .metric(instance.metricCPUUtilization())
         .threshold(90)
         .evaluationPeriods(1)
         .build();
 
 // Trigger Lambda function on instance availability events
 Function fn = Function.Builder.create(this, "Function")
         .code(Code.fromInline("exports.handler = (event) => console.log(event);"))
         .handler("index.handler")
         .runtime(Runtime.NODEJS_18_X)
         .build();
 
 Rule availabilityRule = instance.onEvent("Availability", OnEventOptions.builder().target(new LambdaFunction(fn)).build());
 availabilityRule.addEventPattern(EventPattern.builder()
         .detail(Map.of(
                 "EventCategories", List.of("availability")))
         .build());
 

Add XMLDB and OEM with option group

 // Set open cursors with parameter group
 ParameterGroup parameterGroup = ParameterGroup.Builder.create(this, "ParameterGroup")
         .engine(DatabaseInstanceEngine.oracleSe2(OracleSe2InstanceEngineProps.builder().version(OracleEngineVersion.VER_19_0_0_0_2020_04_R1).build()))
         .parameters(Map.of(
                 "open_cursors", "2500"))
         .build();
 
 OptionGroup optionGroup = OptionGroup.Builder.create(this, "OptionGroup")
         .engine(DatabaseInstanceEngine.oracleSe2(OracleSe2InstanceEngineProps.builder().version(OracleEngineVersion.VER_19_0_0_0_2020_04_R1).build()))
         .configurations(List.of(OptionConfiguration.builder()
                 .name("LOCATOR")
                 .build(), OptionConfiguration.builder()
                 .name("OEM")
                 .port(1158)
                 .vpc(vpc)
                 .build()))
         .build();
 
 // Allow connections to OEM
 optionGroup.optionConnections.OEM.connections.allowDefaultPortFromAnyIpv4();
 
 // Database instance with production values
 DatabaseInstance instance = DatabaseInstance.Builder.create(this, "Instance")
         .engine(DatabaseInstanceEngine.oracleSe2(OracleSe2InstanceEngineProps.builder().version(OracleEngineVersion.VER_19_0_0_0_2020_04_R1).build()))
         .licenseModel(LicenseModel.BRING_YOUR_OWN_LICENSE)
         .instanceType(InstanceType.of(InstanceClass.BURSTABLE3, InstanceSize.MEDIUM))
         .multiAz(true)
         .storageType(StorageType.IO1)
         .credentials(Credentials.fromUsername("syscdk"))
         .vpc(vpc)
         .databaseName("ORCL")
         .storageEncrypted(true)
         .backupRetention(Duration.days(7))
         .monitoringInterval(Duration.seconds(60))
         .enablePerformanceInsights(true)
         .cloudwatchLogsExports(List.of("trace", "audit", "alert", "listener"))
         .cloudwatchLogsRetention(RetentionDays.ONE_MONTH)
         .autoMinorVersionUpgrade(true) // required to be true if LOCATOR is used in the option group
         .optionGroup(optionGroup)
         .parameterGroup(parameterGroup)
         .removalPolicy(RemovalPolicy.DESTROY)
         .build();
 
 // Allow connections on default port from any IPV4
 instance.connections.allowDefaultPortFromAnyIpv4();
 
 // Rotate the master user password every 30 days
 instance.addRotationSingleUser();
 
 // Add alarm for high CPU
 // Add alarm for high CPU
 Alarm.Builder.create(this, "HighCPU")
         .metric(instance.metricCPUUtilization())
         .threshold(90)
         .evaluationPeriods(1)
         .build();
 
 // Trigger Lambda function on instance availability events
 Function fn = Function.Builder.create(this, "Function")
         .code(Code.fromInline("exports.handler = (event) => console.log(event);"))
         .handler("index.handler")
         .runtime(Runtime.NODEJS_18_X)
         .build();
 
 Rule availabilityRule = instance.onEvent("Availability", OnEventOptions.builder().target(new LambdaFunction(fn)).build());
 availabilityRule.addEventPattern(EventPattern.builder()
         .detail(Map.of(
                 "EventCategories", List.of("availability")))
         .build());
 

Use the storageType property to specify the type of storage to use for the instance:

 Vpc vpc;
 
 
 DatabaseInstance iopsInstance = DatabaseInstance.Builder.create(this, "IopsInstance")
         .engine(DatabaseInstanceEngine.mysql(MySqlInstanceEngineProps.builder().version(MysqlEngineVersion.VER_8_0_30).build()))
         .vpc(vpc)
         .storageType(StorageType.IO1)
         .iops(5000)
         .build();
 
 DatabaseInstance gp3Instance = DatabaseInstance.Builder.create(this, "Gp3Instance")
         .engine(DatabaseInstanceEngine.mysql(MySqlInstanceEngineProps.builder().version(MysqlEngineVersion.VER_8_0_30).build()))
         .vpc(vpc)
         .allocatedStorage(500)
         .storageType(StorageType.GP3)
         .storageThroughput(500)
         .build();
 

Use the allocatedStorage property to specify the amount of storage (in gigabytes) that is initially allocated for the instance to use for the instance:

 Vpc vpc;
 
 // Setting allocatedStorage for DatabaseInstance replica
 // Note: If allocatedStorage isn't set here, the replica instance will inherit the allocatedStorage of the source instance
 DatabaseInstance sourceInstance;
 
 
 // Setting allocatedStorage for DatabaseInstance
 DatabaseInstance iopsInstance = DatabaseInstance.Builder.create(this, "IopsInstance")
         .engine(DatabaseInstanceEngine.mysql(MySqlInstanceEngineProps.builder().version(MysqlEngineVersion.VER_8_0_30).build()))
         .vpc(vpc)
         .storageType(StorageType.IO1)
         .iops(5000)
         .allocatedStorage(500)
         .build();
 DatabaseInstanceReadReplica.Builder.create(this, "ReadReplica")
         .sourceDatabaseInstance(sourceInstance)
         .instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.LARGE))
         .vpc(vpc)
         .allocatedStorage(500)
         .build();
 

Use the caCertificate property to specify the CA certificates to use for the instance:

 Vpc vpc;
 
 
 DatabaseInstance.Builder.create(this, "Instance")
         .engine(DatabaseInstanceEngine.mysql(MySqlInstanceEngineProps.builder().version(MysqlEngineVersion.VER_8_0_30).build()))
         .vpc(vpc)
         .caCertificate(CaCertificate.RDS_CA_RDS2048_G1)
         .build();
 

You can specify a custom CA certificate with:

 Vpc vpc;
 
 
 DatabaseInstance.Builder.create(this, "Instance")
         .engine(DatabaseInstanceEngine.mysql(MySqlInstanceEngineProps.builder().version(MysqlEngineVersion.VER_8_0_30).build()))
         .vpc(vpc)
         .caCertificate(CaCertificate.of("future-rds-ca"))
         .build();
 

Setting Public Accessibility

You can set public accessibility for the DatabaseInstance or the ClusterInstance 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 will be true if vpcSubnets is subnetType: SubnetType.PUBLIC, false otherwise. In the case of a cluster, the default value will be determined on the vpc placement of the DatabaseCluster otherwise it will be determined based on the vpc placement of standalone DatabaseInstance.

 Vpc vpc;
 
 // Setting public accessibility for DB instance
 // Setting public accessibility for DB instance
 DatabaseInstance.Builder.create(this, "Instance")
         .engine(DatabaseInstanceEngine.mysql(MySqlInstanceEngineProps.builder()
                 .version(MysqlEngineVersion.VER_8_0_19)
                 .build()))
         .vpc(vpc)
         .vpcSubnets(SubnetSelection.builder()
                 .subnetType(SubnetType.PRIVATE_WITH_EGRESS)
                 .build())
         .publiclyAccessible(true)
         .build();
 
 // Setting public accessibility for DB cluster instance
 // Setting public accessibility for DB cluster instance
 DatabaseCluster.Builder.create(this, "DatabaseCluster")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder()
                 .version(AuroraMysqlEngineVersion.VER_3_03_0)
                 .build()))
         .writer(ClusterInstance.serverlessV2("Writer", ServerlessV2ClusterInstanceProps.builder()
                 .publiclyAccessible(true)
                 .build()))
         .vpc(vpc)
         .vpcSubnets(SubnetSelection.builder()
                 .subnetType(SubnetType.PRIVATE_WITH_EGRESS)
                 .build())
         .build();
 

Instance events

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

 DatabaseInstance instance;
 Function fn;
 
 Rule rule = instance.onEvent("InstanceEvent", OnEventOptions.builder().target(new LambdaFunction(fn)).build());
 

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.

 Vpc vpc;
 
 IInstanceEngine engine = DatabaseInstanceEngine.postgres(PostgresInstanceEngineProps.builder().version(PostgresEngineVersion.VER_15_2).build());
 DatabaseInstance.Builder.create(this, "InstanceWithUsername")
         .engine(engine)
         .vpc(vpc)
         .credentials(Credentials.fromGeneratedSecret("postgres"))
         .build();
 
 DatabaseInstance.Builder.create(this, "InstanceWithUsernameAndPassword")
         .engine(engine)
         .vpc(vpc)
         .credentials(Credentials.fromPassword("postgres", SecretValue.ssmSecure("/dbPassword", "1")))
         .build();
 
 ISecret mySecret = Secret.fromSecretName(this, "DBSecret", "myDBLoginInfo");
 DatabaseInstance.Builder.create(this, "InstanceWithSecretLogin")
         .engine(engine)
         .vpc(vpc)
         .credentials(Credentials.fromSecret(mySecret))
         .build();
 

Secrets generated by fromGeneratedSecret() can be customized:

 Vpc vpc;
 
 IInstanceEngine engine = DatabaseInstanceEngine.postgres(PostgresInstanceEngineProps.builder().version(PostgresEngineVersion.VER_15_2).build());
 Key myKey = new Key(this, "MyKey");
 
 DatabaseInstance.Builder.create(this, "InstanceWithCustomizedSecret")
         .engine(engine)
         .vpc(vpc)
         .credentials(Credentials.fromGeneratedSecret("postgres", CredentialsBaseOptions.builder()
                 .secretName("my-cool-name")
                 .encryptionKey(myKey)
                 .excludeCharacters("!&*^#@()")
                 .replicaRegions(List.of(ReplicaRegion.builder().region("eu-west-1").build(), ReplicaRegion.builder().region("eu-west-2").build()))
                 .build()))
         .build();
 

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

 Vpc vpc;
 
 IInstanceEngine engine = DatabaseInstanceEngine.postgres(PostgresInstanceEngineProps.builder().version(PostgresEngineVersion.VER_15_2).build());
 Key myKey = new Key(this, "MyKey");
 
 DatabaseInstanceFromSnapshot.Builder.create(this, "InstanceFromSnapshotWithCustomizedSecret")
         .engine(engine)
         .vpc(vpc)
         .snapshotIdentifier("mySnapshot")
         .credentials(SnapshotCredentials.fromGeneratedSecret("username", SnapshotCredentialsFromGeneratedPasswordOptions.builder()
                 .encryptionKey(myKey)
                 .excludeCharacters("!&*^#@()")
                 .replicaRegions(List.of(ReplicaRegion.builder().region("eu-west-1").build(), ReplicaRegion.builder().region("eu-west-2").build()))
                 .build()))
         .build();
 

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:

 DatabaseCluster cluster;
 
 cluster.connections.allowFromAnyIpv4(Port.allTraffic(), "Open to the world");
 

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

 DatabaseCluster cluster;
 
 String writeAddress = cluster.getClusterEndpoint().getSocketAddress();
 

For an instance database:

 DatabaseInstance instance;
 
 String address = instance.getInstanceEndpoint().getSocketAddress();
 

Rotating credentials

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

 DatabaseInstance instance;
 SecurityGroup mySecurityGroup;
 
 
 instance.addRotationSingleUser(RotationSingleUserOptions.builder()
         .automaticallyAfter(Duration.days(7)) // defaults to 30 days
         .excludeCharacters("!@#$%^&*") // defaults to the set " %+~`#/// here*()|[]{}:;<>?!'/@\"\\"
         .securityGroup(mySecurityGroup)
         .build());
 

 DatabaseCluster cluster = DatabaseCluster.Builder.create(stack, "Database")
         .engine(DatabaseClusterEngine.AURORA)
         .instanceProps(InstanceProps.builder()
                 .instanceType(InstanceType.of(InstanceClass.BURSTABLE3, InstanceSize.SMALL))
                 .vpc(vpc)
                 .build())
         .build();
 
 cluster.addRotationSingleUser();
 
 DatabaseCluster clusterWithCustomRotationOptions = DatabaseCluster.Builder.create(stack, "CustomRotationOptions")
         .engine(DatabaseClusterEngine.AURORA)
         .instanceProps(InstanceProps.builder()
                 .instanceType(InstanceType.of(InstanceClass.BURSTABLE3, InstanceSize.SMALL))
                 .vpc(vpc)
                 .build())
         .build();
 clusterWithCustomRotationOptions.addRotationSingleUser(RotationSingleUserOptions.builder()
         .automaticallyAfter(Duration.days(7))
         .excludeCharacters("!@#$%^&*")
         .securityGroup(securityGroup)
         .vpcSubnets(SubnetSelection.builder().subnetType(SubnetType.PRIVATE_WITH_EGRESS).build())
         .endpoint(endpoint)
         .build());
 

The multi user rotation scheme is also available:

 DatabaseInstance instance;
 DatabaseSecret myImportedSecret;
 
 instance.addRotationMultiUser("MyUser", RotationMultiUserOptions.builder()
         .secret(myImportedSecret)
         .build());
 

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

 DatabaseInstance instance;
 
 DatabaseSecret myUserSecret = DatabaseSecret.Builder.create(this, "MyUserSecret")
         .username("myuser")
         .secretName("my-user-secret") // optional, defaults to a CloudFormation-generated name
         .dbname("mydb") //optional, defaults to the main database of the RDS cluster this secret gets attached to
         .masterSecret(instance.getSecret())
         .excludeCharacters("{}[]()'\"/\\")
         .build();
 ISecret myUserSecretAttached = myUserSecret.attach(instance); // Adds DB connections information in the secret
 
 instance.addRotationMultiUser("MyUser", RotationMultiUserOptions.builder() // Add rotation using the multi user scheme
         .secret(myUserSecretAttached).build());
 

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:

 DatabaseInstance instance;
 InterfaceVpcEndpoint myEndpoint;
 
 
 instance.addRotationSingleUser(RotationSingleUserOptions.builder()
         .vpcSubnets(SubnetSelection.builder().subnetType(SubnetType.PRIVATE_WITH_EGRESS).build()) // Place rotation Lambda in private subnets
         .endpoint(myEndpoint)
         .build());
 

See also aws-cdk-lib/aws-secretsmanager for credentials rotation of existing clusters/instances.

By default, any stack updates will cause AWS Secrets Manager to rotate a secret immediately. To prevent this behavior and wait until the next scheduled rotation window specified via the automaticallyAfter property, set the rotateImmediatelyOnUpdate property to false:

 DatabaseInstance instance;
 SecurityGroup mySecurityGroup;
 
 
 instance.addRotationSingleUser(RotationSingleUserOptions.builder()
         .automaticallyAfter(Duration.days(7)) // defaults to 30 days
         .excludeCharacters("!@#$%^&*") // defaults to the set " %+~`#/// here*()|[]{}:;<>?!'/@\"\\"
         .securityGroup(mySecurityGroup) // defaults to an auto-created security group
         .rotateImmediatelyOnUpdate(false)
         .build());
 

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.

Instance

 Vpc vpc;
 
 DatabaseInstance instance = DatabaseInstance.Builder.create(this, "Instance")
         .engine(DatabaseInstanceEngine.mysql(MySqlInstanceEngineProps.builder().version(MysqlEngineVersion.VER_8_0_19).build()))
         .vpc(vpc)
         .iamAuthentication(true)
         .build();
 Role role = Role.Builder.create(this, "DBRole").assumedBy(new AccountPrincipal(this.account)).build();
 instance.grantConnect(role);
 

Proxy

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

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder()
                 .version(AuroraMysqlEngineVersion.VER_3_03_0)
                 .build()))
         .writer(ClusterInstance.provisioned("writer"))
         .vpc(vpc)
         .build();
 
 DatabaseProxy proxy = DatabaseProxy.Builder.create(this, "Proxy")
         .proxyTarget(ProxyTarget.fromCluster(cluster))
         .secrets(List.of(cluster.getSecret()))
         .vpc(vpc)
         .build();
 
 Role role = Role.Builder.create(this, "DBProxyRole").assumedBy(new AccountPrincipal(this.account)).build();
 proxy.grantConnect(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 for setup instructions.

To specify the details of authentication used by a proxy to log in as a specific database user use the clientPasswordAuthType property:

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder()
                 .version(AuroraMysqlEngineVersion.VER_3_03_0)
                 .build()))
         .writer(ClusterInstance.provisioned("writer"))
         .vpc(vpc)
         .build();
 
 DatabaseProxy proxy = DatabaseProxy.Builder.create(this, "Proxy")
         .proxyTarget(ProxyTarget.fromCluster(cluster))
         .secrets(List.of(cluster.getSecret()))
         .vpc(vpc)
         .clientPasswordAuthType(ClientPasswordAuthType.MYSQL_NATIVE_PASSWORD)
         .build();
 

Cluster

The following example shows granting connection access for an IAM role to an Aurora Cluster.

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder()
                 .version(AuroraMysqlEngineVersion.VER_3_03_0)
                 .build()))
         .writer(ClusterInstance.provisioned("writer"))
         .vpc(vpc)
         .build();
 Role role = Role.Builder.create(this, "AppRole").assumedBy(new ServicePrincipal("someservice.amazonaws.com")).build();
 cluster.grantConnect(role, "somedbuser");
 

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.

 Vpc vpc;
 
 Role role = Role.Builder.create(this, "RDSDirectoryServicesRole")
         .assumedBy(new CompositePrincipal(
         new ServicePrincipal("rds.amazonaws.com"),
         new ServicePrincipal("directoryservice.rds.amazonaws.com")))
         .managedPolicies(List.of(ManagedPolicy.fromAwsManagedPolicyName("service-role/AmazonRDSDirectoryServiceAccess")))
         .build();
 DatabaseInstance instance = DatabaseInstance.Builder.create(this, "Instance")
         .engine(DatabaseInstanceEngine.mysql(MySqlInstanceEngineProps.builder().version(MysqlEngineVersion.VER_8_0_19).build()))
         .vpc(vpc)
         .domain("d-????????") // The ID of the domain for the instance to join.
         .domainRole(role)
         .build();
 

You can also use the Kerberos authentication for an Aurora database cluster.

 Vpc vpc;
 
 Role iamRole = Role.Builder.create(this, "Role")
         .assumedBy(new CompositePrincipal(
         new ServicePrincipal("rds.amazonaws.com"),
         new ServicePrincipal("directoryservice.rds.amazonaws.com")))
         .managedPolicies(List.of(ManagedPolicy.fromAwsManagedPolicyName("service-role/AmazonRDSDirectoryServiceAccess")))
         .build();
 
 DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder().version(AuroraMysqlEngineVersion.VER_3_05_1).build()))
         .writer(ClusterInstance.provisioned("Instance", ProvisionedClusterInstanceProps.builder()
                 .instanceType(InstanceType.of(InstanceClass.BURSTABLE3, InstanceSize.MEDIUM))
                 .build()))
         .vpc(vpc)
         .domain("d-????????") // The ID of the domain for the cluster to join.
         .domainRole(iamRole)
         .build();
 

Note: In addition to the setup above, you need to make sure that the database instance or cluster 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):

 // The number of database connections in use (average over 5 minutes)
 DatabaseInstance instance;
 
 // Average CPU utilization over 5 minutes
 DatabaseCluster cluster;
 
 Metric dbConnections = instance.metricDatabaseConnections();
 Metric cpuUtilization = cluster.metricCPUUtilization();
 
 // The average amount of time taken per disk I/O operation (average over 1 minute)
 Metric readLatency = instance.metric("ReadLatency", MetricOptions.builder().statistic("Average").period(Duration.seconds(60)).build());
 

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 -

 import software.amazon.awscdk.services.s3.*;
 
 Vpc vpc;
 
 Bucket importBucket = new Bucket(this, "importbucket");
 Bucket exportBucket = new Bucket(this, "exportbucket");
 DatabaseCluster.Builder.create(this, "dbcluster")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder()
                 .version(AuroraMysqlEngineVersion.VER_3_03_0)
                 .build()))
         .writer(ClusterInstance.provisioned("writer"))
         .vpc(vpc)
         .s3ImportBuckets(List.of(importBucket))
         .s3ExportBuckets(List.of(exportBucket))
         .build();
 

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.

RDS Proxy is supported for MySQL, MariaDB, Postgres, and SQL Server.

The following code configures an RDS Proxy for a DatabaseInstance.

 Vpc vpc;
 SecurityGroup securityGroup;
 Secret[] secrets;
 DatabaseInstance dbInstance;
 
 
 DatabaseProxy proxy = dbInstance.addProxy("proxy", DatabaseProxyOptions.builder()
         .borrowTimeout(Duration.seconds(30))
         .maxConnectionsPercent(50)
         .secrets(secrets)
         .vpc(vpc)
         .build());
 

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.

 import software.amazon.awscdk.services.logs.*;
 Role myLogsPublishingRole;
 Vpc vpc;
 
 
 // Exporting logs from a cluster
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.aurora(AuroraClusterEngineProps.builder()
                 .version(AuroraEngineVersion.VER_1_17_9)
                 .build()))
         .writer(ClusterInstance.provisioned("writer"))
         .vpc(vpc)
         .cloudwatchLogsExports(List.of("error", "general", "slowquery", "audit")) // Export all available MySQL-based logs
         .cloudwatchLogsRetention(RetentionDays.THREE_MONTHS) // Optional - default is to never expire logs
         .cloudwatchLogsRetentionRole(myLogsPublishingRole)
         .build();
 
 // When 'cloudwatchLogsExports' is set, each export value creates its own log group in DB cluster.
 // Specify an export value to access its log group.
 ILogGroup errorLogGroup = cluster.getCloudwatchLogGroups()["error"];
 ILogGroup auditLogGroup = cluster.getCloudwatchLogGroups().getAudit();
 
 // Exporting logs from an instance
 DatabaseInstance instance = DatabaseInstance.Builder.create(this, "Instance")
         .engine(DatabaseInstanceEngine.postgres(PostgresInstanceEngineProps.builder()
                 .version(PostgresEngineVersion.VER_15_2)
                 .build()))
         .vpc(vpc)
         .cloudwatchLogsExports(List.of("postgresql")) // Export the PostgreSQL logs
         .cloudwatchLogsRetention(RetentionDays.THREE_MONTHS)
         .build();
 
 // When 'cloudwatchLogsExports' is set, each export value creates its own log group in DB instance.
 // Specify an export value to access its log group.
 ILogGroup postgresqlLogGroup = instance.getCloudwatchLogGroups()["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.

 Vpc vpc;
 SecurityGroup securityGroup;
 
 
 OptionGroup.Builder.create(this, "Options")
         .engine(DatabaseInstanceEngine.oracleSe2(OracleSe2InstanceEngineProps.builder()
                 .version(OracleEngineVersion.VER_19)
                 .build()))
         .configurations(List.of(OptionConfiguration.builder()
                 .name("OEM")
                 .port(5500)
                 .vpc(vpc)
                 .securityGroups(List.of(securityGroup))
                 .build()))
         .build();
 

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:

 Vpc vpc;
 
 
 ParameterGroup parameterGroup = ParameterGroup.Builder.create(this, "ParameterGroup")
         .engine(DatabaseInstanceEngine.sqlServerEe(SqlServerEeInstanceEngineProps.builder()
                 .version(SqlServerEngineVersion.VER_11)
                 .build()))
         .parameters(Map.of(
                 "locks", "100"))
         .build();
 
 DatabaseInstance.Builder.create(this, "Database")
         .engine(DatabaseInstanceEngine.SQL_SERVER_EE)
         .vpc(vpc)
         .parameterGroup(parameterGroup)
         .build();
 

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:

 Vpc vpc;
 
 
 DatabaseInstance.Builder.create(this, "Database")
         .engine(DatabaseInstanceEngine.sqlServerEe(SqlServerEeInstanceEngineProps.builder().version(SqlServerEngineVersion.VER_11).build()))
         .vpc(vpc)
         .parameters(Map.of(
                 "locks", "100"))
         .build();
 

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

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.

 Vpc vpc;
 
 
 ServerlessCluster cluster = ServerlessCluster.Builder.create(this, "AnotherCluster")
         .engine(DatabaseClusterEngine.AURORA_POSTGRESQL)
         .copyTagsToSnapshot(true) // whether to save the cluster tags when creating the snapshot. Default is 'true'
         .parameterGroup(ParameterGroup.fromParameterGroupName(this, "ParameterGroup", "default.aurora-postgresql11"))
         .vpc(vpc)
         .scaling(ServerlessScalingOptions.builder()
                 .autoPause(Duration.minutes(10)) // default is to pause after 5 minutes of idle time
                 .minCapacity(AuroraCapacityUnit.ACU_8) // default is 2 Aurora capacity units (ACUs)
                 .maxCapacity(AuroraCapacityUnit.ACU_32) // default is 16 Aurora capacity units (ACUs)
                 .timeout(Duration.seconds(100)) // default is 5 minutes
                 .timeoutAction(TimeoutAction.FORCE_APPLY_CAPACITY_CHANGE)
                 .build())
         .build();
 

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

Use ServerlessClusterFromSnapshot to create a serverless cluster from a snapshot:

 Vpc vpc;
 
 ServerlessClusterFromSnapshot.Builder.create(this, "Cluster")
         .engine(DatabaseClusterEngine.AURORA_MYSQL)
         .vpc(vpc)
         .snapshotIdentifier("mySnapshot")
         .build();
 

Data API

You can access your Aurora 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.

 Vpc vpc;
 Function fn;
 
 
 // Create a serverless V1 cluster
 ServerlessCluster serverlessV1Cluster = ServerlessCluster.Builder.create(this, "AnotherCluster")
         .engine(DatabaseClusterEngine.AURORA_MYSQL)
         .vpc(vpc) // this parameter is optional for serverless Clusters
         .enableDataApi(true)
         .build();
 serverlessV1Cluster.grantDataApiAccess(fn);
 
 // Create an Aurora cluster
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Cluster")
         .engine(DatabaseClusterEngine.AURORA_MYSQL)
         .vpc(vpc)
         .enableDataApi(true)
         .build();
 cluster.grantDataApiAccess(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.

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.

Preferred Maintenance Window

When creating an RDS cluster, it is possible to (optionally) specify a preferred maintenance window for the cluster as well as the instances under the cluster. See AWS docs for more information regarding maintenance windows.

The following code snippet shows an example of setting the cluster's maintenance window to 22:15-22:45 (UTC) on Saturdays, but setting the instances' maintenance window to 23:15-23:45 on Sundays

 Vpc vpc;
 
 DatabaseCluster.Builder.create(this, "DatabaseCluster")
         .engine(DatabaseClusterEngine.AURORA)
         .instanceProps(InstanceProps.builder()
                 .vpc(vpc)
                 .preferredMaintenanceWindow("Sun:23:15-Sun:23:45")
                 .build())
         .preferredMaintenanceWindow("Sat:22:15-Sat:22:45")
         .build();