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 theServerlessDatabaseCapacity
/ 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_RSA2048_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_16_3).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_16_3).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_16_3).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_RSA2048_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_16_3).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_16_3).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_16_3).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.
Note: To use s3ImportRole
and s3ExportRole
with Aurora PostgreSQL, you must also enable the S3 import and export features when you create the DatabaseClusterEngine.
You can read more about loading data to (or from) S3 here:
- Aurora MySQL - import and export.
- Aurora PostgreSQL - import and export.
- Microsoft SQL Server - import and export
- PostgreSQL - import and export
- Oracle - import and export
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_16_3) .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())) .name("my-parameter-group") .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 v1
Amazon Aurora Serverless v1 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 v1 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();
Note: The rds.ServerlessCluster
class is for Aurora Serverless v1. If you want to use Aurora Serverless v2, use the rds.DatabaseCluster
class.
Aurora Serverless v1 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 v1
Learn more about using Amazon Aurora Serverless v1 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();
You can also set the preferred maintenance window via reader and writer props:
Vpc vpc; DatabaseCluster.Builder.create(this, "DatabaseCluster") .engine(DatabaseClusterEngine.AURORA) .vpc(vpc) .writer(ClusterInstance.provisioned("WriterInstance", ProvisionedClusterInstanceProps.builder() .preferredMaintenanceWindow("Sat:22:15-Sat:22:45") .build())) .preferredMaintenanceWindow("Sat:22:15-Sat:22:45") .build();
-
ClassDescriptionAurora capacity units (ACUs).Creation properties of the plain Aurora database cluster engine.A builder for
AuroraClusterEngineProps
An implementation forAuroraClusterEngineProps
The versions for the Aurora cluster engine (those returned byDatabaseClusterEngine.aurora
).Creation properties of the Aurora MySQL database cluster engine.A builder forAuroraMysqlClusterEngineProps
An implementation forAuroraMysqlClusterEngineProps
The versions for the Aurora MySQL cluster engine (those returned byDatabaseClusterEngine.auroraMysql
).Creation properties of the Aurora PostgreSQL database cluster engine.A builder forAuroraPostgresClusterEngineProps
An implementation forAuroraPostgresClusterEngineProps
Features supported by this version of the Aurora Postgres cluster engine.A builder forAuroraPostgresEngineFeatures
An implementation forAuroraPostgresEngineFeatures
The versions for the Aurora PostgreSQL cluster engine (those returned byDatabaseClusterEngine.auroraPostgres
).Backup configuration for RDS databases.A builder forBackupProps
An implementation forBackupProps
The CA certificate used for a DB instance.Creates a custom DB engine version (CEV).A fluent builder forCfnCustomDBEngineVersion
.Properties for defining aCfnCustomDBEngineVersion
.A builder forCfnCustomDBEngineVersionProps
An implementation forCfnCustomDBEngineVersionProps
TheAWS::RDS::DBCluster
resource creates an Amazon Aurora DB cluster or Multi-AZ DB cluster.A fluent builder forCfnDBCluster
.Describes an AWS Identity and Access Management (IAM) role that is associated with a DB cluster.A builder forCfnDBCluster.DBClusterRoleProperty
An implementation forCfnDBCluster.DBClusterRoleProperty
TheEndpoint
return value specifies the connection endpoint for the primary instance of the DB cluster.A builder forCfnDBCluster.EndpointProperty
An implementation forCfnDBCluster.EndpointProperty
TheMasterUserSecret
return value specifies the secret managed by RDS in AWS Secrets Manager for the master user password.A builder forCfnDBCluster.MasterUserSecretProperty
An implementation forCfnDBCluster.MasterUserSecretProperty
TheReadEndpoint
return value specifies the reader endpoint for the DB cluster.A builder forCfnDBCluster.ReadEndpointProperty
An implementation forCfnDBCluster.ReadEndpointProperty
TheScalingConfiguration
property type specifies the scaling configuration of an Aurora Serverless v1 DB cluster.A builder forCfnDBCluster.ScalingConfigurationProperty
An implementation forCfnDBCluster.ScalingConfigurationProperty
TheServerlessV2ScalingConfiguration
property type specifies the scaling configuration of an Aurora Serverless V2 DB cluster.A builder forCfnDBCluster.ServerlessV2ScalingConfigurationProperty
An implementation forCfnDBCluster.ServerlessV2ScalingConfigurationProperty
TheAWS::RDS::DBClusterParameterGroup
resource creates a new Amazon RDS DB cluster parameter group.A fluent builder forCfnDBClusterParameterGroup
.Properties for defining aCfnDBClusterParameterGroup
.A builder forCfnDBClusterParameterGroupProps
An implementation forCfnDBClusterParameterGroupProps
Properties for defining aCfnDBCluster
.A builder forCfnDBClusterProps
An implementation forCfnDBClusterProps
TheAWS::RDS::DBInstance
resource creates an Amazon DB instance.A fluent builder forCfnDBInstance
.The details of the DB instance’s server certificate.A builder forCfnDBInstance.CertificateDetailsProperty
An implementation forCfnDBInstance.CertificateDetailsProperty
Information about an AWS Identity and Access Management (IAM) role that is associated with a DB instance.A builder forCfnDBInstance.DBInstanceRoleProperty
An implementation forCfnDBInstance.DBInstanceRoleProperty
This data type represents the information you need to connect to an Amazon RDS DB instance.A builder forCfnDBInstance.EndpointProperty
An implementation forCfnDBInstance.EndpointProperty
TheMasterUserSecret
return value specifies the secret managed by RDS in AWS Secrets Manager for the master user password.A builder forCfnDBInstance.MasterUserSecretProperty
An implementation forCfnDBInstance.MasterUserSecretProperty
TheProcessorFeature
property type specifies the processor features of a DB instance class.A builder forCfnDBInstance.ProcessorFeatureProperty
An implementation forCfnDBInstance.ProcessorFeatureProperty
Properties for defining aCfnDBInstance
.A builder forCfnDBInstanceProps
An implementation forCfnDBInstanceProps
TheAWS::RDS::DBParameterGroup
resource creates a custom parameter group for an RDS database family.A fluent builder forCfnDBParameterGroup
.Properties for defining aCfnDBParameterGroup
.A builder forCfnDBParameterGroupProps
An implementation forCfnDBParameterGroupProps
TheAWS::RDS::DBProxy
resource creates or updates a DB proxy.Specifies the details of authentication used by a proxy to log in as a specific database user.A builder forCfnDBProxy.AuthFormatProperty
An implementation forCfnDBProxy.AuthFormatProperty
A fluent builder forCfnDBProxy
.Metadata assigned to an Amazon RDS resource consisting of a key-value pair.A builder forCfnDBProxy.TagFormatProperty
An implementation forCfnDBProxy.TagFormatProperty
TheAWS::RDS::DBProxyEndpoint
resource creates or updates a DB proxy endpoint.A fluent builder forCfnDBProxyEndpoint
.Metadata assigned to an Amazon RDS resource consisting of a key-value pair.A builder forCfnDBProxyEndpoint.TagFormatProperty
An implementation forCfnDBProxyEndpoint.TagFormatProperty
Properties for defining aCfnDBProxyEndpoint
.A builder forCfnDBProxyEndpointProps
An implementation forCfnDBProxyEndpointProps
Properties for defining aCfnDBProxy
.A builder forCfnDBProxyProps
An implementation forCfnDBProxyProps
TheAWS::RDS::DBProxyTargetGroup
resource represents a set of RDS DB instances, Aurora DB clusters, or both that a proxy can connect to.A fluent builder forCfnDBProxyTargetGroup
.Specifies the settings that control the size and behavior of the connection pool associated with aDBProxyTargetGroup
.An implementation forCfnDBProxyTargetGroup.ConnectionPoolConfigurationInfoFormatProperty
Properties for defining aCfnDBProxyTargetGroup
.A builder forCfnDBProxyTargetGroupProps
An implementation forCfnDBProxyTargetGroupProps
TheAWS::RDS::DBSecurityGroup
resource creates or updates an Amazon RDS DB security group.A fluent builder forCfnDBSecurityGroup
.TheIngress
property type specifies an individual ingress rule within anAWS::RDS::DBSecurityGroup
resource.A builder forCfnDBSecurityGroup.IngressProperty
An implementation forCfnDBSecurityGroup.IngressProperty
TheAWS::RDS::DBSecurityGroupIngress
resource enables ingress to a DB security group using one of two forms of authorization.A fluent builder forCfnDBSecurityGroupIngress
.Properties for defining aCfnDBSecurityGroupIngress
.A builder forCfnDBSecurityGroupIngressProps
An implementation forCfnDBSecurityGroupIngressProps
Properties for defining aCfnDBSecurityGroup
.A builder forCfnDBSecurityGroupProps
An implementation forCfnDBSecurityGroupProps
TheAWS::RDS::DBSubnetGroup
resource creates a database subnet group.A fluent builder forCfnDBSubnetGroup
.Properties for defining aCfnDBSubnetGroup
.A builder forCfnDBSubnetGroupProps
An implementation forCfnDBSubnetGroupProps
TheAWS::RDS::EventSubscription
resource allows you to receive notifications for Amazon Relational Database Service events through the Amazon Simple Notification Service (Amazon SNS).A fluent builder forCfnEventSubscription
.Properties for defining aCfnEventSubscription
.A builder forCfnEventSubscriptionProps
An implementation forCfnEventSubscriptionProps
TheAWS::RDS::GlobalCluster
resource creates or updates an Amazon Aurora global database spread across multiple AWS Regions.A fluent builder forCfnGlobalCluster
.Properties for defining aCfnGlobalCluster
.A builder forCfnGlobalClusterProps
An implementation forCfnGlobalClusterProps
A zero-ETL integration with Amazon Redshift.A fluent builder forCfnIntegration
.Properties for defining aCfnIntegration
.A builder forCfnIntegrationProps
An implementation forCfnIntegrationProps
TheAWS::RDS::OptionGroup
resource creates or updates an option group, to enable and configure features that are specific to a particular DB engine.A fluent builder forCfnOptionGroup
.TheOptionConfiguration
property type specifies an individual option, and its settings, within anAWS::RDS::OptionGroup
resource.A builder forCfnOptionGroup.OptionConfigurationProperty
An implementation forCfnOptionGroup.OptionConfigurationProperty
TheOptionSetting
property type specifies the value for an option within anOptionSetting
property.A builder forCfnOptionGroup.OptionSettingProperty
An implementation forCfnOptionGroup.OptionSettingProperty
Properties for defining aCfnOptionGroup
.A builder forCfnOptionGroupProps
An implementation forCfnOptionGroupProps
Client password authentication type used by a proxy to log in as a specific database user.The extra options passed to theIClusterEngine.bindToCluster
method.A builder forClusterEngineBindOptions
An implementation forClusterEngineBindOptions
The type returned from theIClusterEngine.bindToCluster
method.A builder forClusterEngineConfig
An implementation forClusterEngineConfig
Represents Database Engine features.A builder forClusterEngineFeatures
An implementation forClusterEngineFeatures
Create an RDS Aurora Cluster Instance.Options for binding the instance to the cluster.A builder forClusterInstanceBindOptions
An implementation forClusterInstanceBindOptions
Common options for creating a cluster instance.A builder forClusterInstanceOptions
An implementation forClusterInstanceOptions
Common options for creating cluster instances (both serverless and provisioned).A builder forClusterInstanceProps
An implementation forClusterInstanceProps
The type of Aurora Cluster Instance.Properties common to single-user and multi-user rotation options.A builder forCommonRotationUserOptions
An implementation forCommonRotationUserOptions
Username and password combination.Base options for creating Credentials.A builder forCredentialsBaseOptions
An implementation forCredentialsBaseOptions
Options for creating Credentials from a username.A builder forCredentialsFromUsernameOptions
An implementation forCredentialsFromUsernameOptions
Create a clustered database with a given number of instances.A fluent builder forDatabaseCluster
.Properties that describe an existing cluster instance.A builder forDatabaseClusterAttributes
An implementation forDatabaseClusterAttributes
A new or imported clustered database.A database cluster engine.A database cluster restored from a snapshot.A fluent builder forDatabaseClusterFromSnapshot
.Properties forDatabaseClusterFromSnapshot
.A builder forDatabaseClusterFromSnapshotProps
An implementation forDatabaseClusterFromSnapshotProps
Properties for a new database cluster.A builder forDatabaseClusterProps
An implementation forDatabaseClusterProps
A database instance.A fluent builder forDatabaseInstance
.Properties that describe an existing instance.A builder forDatabaseInstanceAttributes
An implementation forDatabaseInstanceAttributes
A new or imported database instance.A database instance engine.A database instance restored from a snapshot.A fluent builder forDatabaseInstanceFromSnapshot
.Construction properties for a DatabaseInstanceFromSnapshot.A builder forDatabaseInstanceFromSnapshotProps
An implementation forDatabaseInstanceFromSnapshotProps
Construction properties for a DatabaseInstanceNew.A builder forDatabaseInstanceNewProps
An implementation forDatabaseInstanceNewProps
Construction properties for a DatabaseInstance.A builder forDatabaseInstanceProps
An implementation forDatabaseInstanceProps
A read replica database instance.A fluent builder forDatabaseInstanceReadReplica
.Construction properties for a DatabaseInstanceReadReplica.A builder forDatabaseInstanceReadReplicaProps
An implementation forDatabaseInstanceReadReplicaProps
Construction properties for a DatabaseInstanceSource.A builder forDatabaseInstanceSourceProps
An implementation forDatabaseInstanceSourceProps
RDS Database Proxy.A fluent builder forDatabaseProxy
.Properties that describe an existing DB Proxy.A builder forDatabaseProxyAttributes
An implementation forDatabaseProxyAttributes
Options for a new DatabaseProxy.A builder forDatabaseProxyOptions
An implementation forDatabaseProxyOptions
Construction properties for a DatabaseProxy.A builder forDatabaseProxyProps
An implementation forDatabaseProxyProps
A database secret.A fluent builder forDatabaseSecret
.Construction properties for a DatabaseSecret.A builder forDatabaseSecretProps
An implementation forDatabaseSecretProps
The storage type to be associated with the DB cluster.Connection endpoint of a database cluster or instance.A version of an engine - for either a cluster, or instance.A builder forEngineVersion
An implementation forEngineVersion
An Aurora Cluster Instance.Internal default implementation forIAuroraClusterInstance
.A proxy class which represents a concrete javascript instance of this type.The interface representing a database cluster (as opposed to instance) engine.Internal default implementation forIClusterEngine
.A proxy class which represents a concrete javascript instance of this type.Represents an Aurora cluster instance This can be either a provisioned instance or a serverless v2 instance.Internal default implementation forIClusterInstance
.A proxy class which represents a concrete javascript instance of this type.Create a clustered database with a given number of instances.Internal default implementation forIDatabaseCluster
.A proxy class which represents a concrete javascript instance of this type.A database instance.Internal default implementation forIDatabaseInstance
.A proxy class which represents a concrete javascript instance of this type.DB Proxy.Internal default implementation forIDatabaseProxy
.A proxy class which represents a concrete javascript instance of this type.A common interface for database engines.Internal default implementation forIEngine
.A proxy class which represents a concrete javascript instance of this type.Interface representing a database instance (as opposed to cluster) engine.Internal default implementation forIInstanceEngine
.A proxy class which represents a concrete javascript instance of this type.The options passed toIInstanceEngine.bind
.A builder forInstanceEngineBindOptions
An implementation forInstanceEngineBindOptions
The type returned from theIInstanceEngine.bind
method.A builder forInstanceEngineConfig
An implementation forInstanceEngineConfig
Represents Database Engine features.A builder forInstanceEngineFeatures
An implementation forInstanceEngineFeatures
Instance properties for database instances.A builder forInstanceProps
An implementation forInstanceProps
The orchestration of updates of multiple instances.An option group.Internal default implementation forIOptionGroup
.A proxy class which represents a concrete javascript instance of this type.A parameter group.Internal default implementation forIParameterGroup
.A proxy class which represents a concrete javascript instance of this type.Interface representing a serverless database cluster.Internal default implementation forIServerlessCluster
.A proxy class which represents a concrete javascript instance of this type.Interface for a subnet group.Internal default implementation forISubnetGroup
.A proxy class which represents a concrete javascript instance of this type.The license model.The versions for the MariaDB instance engines (those returned byDatabaseInstanceEngine.mariaDb
).Properties for MariaDB instance engines.A builder forMariaDbInstanceEngineProps
An implementation forMariaDbInstanceEngineProps
The versions for the MySQL instance engines (those returned byDatabaseInstanceEngine.mysql
).Properties for MySQL instance engines.A builder forMySqlInstanceEngineProps
An implementation forMySqlInstanceEngineProps
The network type of the DB instance.Configuration properties for an option.A builder forOptionConfiguration
An implementation forOptionConfiguration
An option group.A fluent builder forOptionGroup
.Construction properties for an OptionGroup.A builder forOptionGroupProps
An implementation forOptionGroupProps
Properties for Oracle Enterprise Edition (CDB) instance engines.A builder forOracleEeCdbInstanceEngineProps
An implementation forOracleEeCdbInstanceEngineProps
Properties for Oracle Enterprise Edition instance engines.A builder forOracleEeInstanceEngineProps
An implementation forOracleEeInstanceEngineProps
The versions for the Oracle instance engines.Properties for Oracle Standard Edition 2 (CDB) instance engines.A builder forOracleSe2CdbInstanceEngineProps
An implementation forOracleSe2CdbInstanceEngineProps
Properties for Oracle Standard Edition 2 instance engines.A builder forOracleSe2InstanceEngineProps
An implementation forOracleSe2InstanceEngineProps
A parameter group.A fluent builder forParameterGroup
.Options forIParameterGroup.bindToCluster
.A builder forParameterGroupClusterBindOptions
An implementation forParameterGroupClusterBindOptions
The type returned fromIParameterGroup.bindToCluster
.A builder forParameterGroupClusterConfig
An implementation forParameterGroupClusterConfig
Options forIParameterGroup.bindToInstance
.A builder forParameterGroupInstanceBindOptions
An implementation forParameterGroupInstanceBindOptions
The type returned fromIParameterGroup.bindToInstance
.A builder forParameterGroupInstanceConfig
An implementation forParameterGroupInstanceConfig
Properties for a parameter group.A builder forParameterGroupProps
An implementation forParameterGroupProps
The retention period for Performance Insight data, in days.Features supported by the Postgres database engine.A builder forPostgresEngineFeatures
An implementation forPostgresEngineFeatures
The versions for the PostgreSQL instance engines (those returned byDatabaseInstanceEngine.postgres
).Properties for PostgreSQL instance engines.A builder forPostgresInstanceEngineProps
An implementation forPostgresInstanceEngineProps
The processor features.A builder forProcessorFeatures
An implementation forProcessorFeatures
Options for creating a provisioned instance.A builder forProvisionedClusterInstanceProps
An implementation forProvisionedClusterInstanceProps
Proxy target: Instance or Cluster.The result of binding aProxyTarget
to aDatabaseProxy
.A builder forProxyTargetConfig
An implementation forProxyTargetConfig
Options to add the multi user rotation.A builder forRotationMultiUserOptions
An implementation forRotationMultiUserOptions
Options to add the multi user rotation.A builder forRotationSingleUserOptions
An implementation forRotationSingleUserOptions
Create an Aurora Serverless v1 Cluster.A fluent builder forServerlessCluster
.Properties that describe an existing cluster instance.A builder forServerlessClusterAttributes
An implementation forServerlessClusterAttributes
A Aurora Serverless v1 Cluster restored from a snapshot.A fluent builder forServerlessClusterFromSnapshot
.Properties forServerlessClusterFromSnapshot
.A builder forServerlessClusterFromSnapshotProps
An implementation forServerlessClusterFromSnapshotProps
Properties for a new Aurora Serverless v1 Cluster.A builder forServerlessClusterProps
An implementation forServerlessClusterProps
Options for configuring scaling on an Aurora Serverless v1 Cluster.A builder forServerlessScalingOptions
An implementation forServerlessScalingOptions
Options for creating a serverless v2 instance.A builder forServerlessV2ClusterInstanceProps
An implementation forServerlessV2ClusterInstanceProps
SessionPinningFilter.Credentials to update the password for aDatabaseInstanceFromSnapshot
.Options used in theSnapshotCredentials.fromGeneratedPassword
method.A builder forSnapshotCredentialsFromGeneratedPasswordOptions
An implementation forSnapshotCredentialsFromGeneratedPasswordOptions
Properties for SQL Server Enterprise Edition instance engines.A builder forSqlServerEeInstanceEngineProps
An implementation forSqlServerEeInstanceEngineProps
The versions for the SQL Server instance engines (those returned byDatabaseInstanceEngine.sqlServerSe
,DatabaseInstanceEngine.sqlServerEx
,DatabaseInstanceEngine.sqlServerWeb
andDatabaseInstanceEngine.sqlServerEe
).Properties for SQL Server Express Edition instance engines.A builder forSqlServerExInstanceEngineProps
An implementation forSqlServerExInstanceEngineProps
Properties for SQL Server Standard Edition instance engines.A builder forSqlServerSeInstanceEngineProps
An implementation forSqlServerSeInstanceEngineProps
Properties for SQL Server Web Edition instance engines.A builder forSqlServerWebInstanceEngineProps
An implementation forSqlServerWebInstanceEngineProps
The type of storage.Class for creating a RDS DB subnet group.A fluent builder forSubnetGroup
.Properties for creating a SubnetGroup.A builder forSubnetGroupProps
An implementation forSubnetGroupProps
TimeoutAction defines the action to take when a timeout occurs if a scaling point is not found.