Package software.amazon.awscdk.services.rds


@Stability(Stable) @Deprecated package software.amazon.awscdk.services.rds
Deprecated.

Amazon Relational Database Service Construct Library

---

End-of-Support

AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2.

For more information on how to migrate, see the Migrating to AWS CDK v2 guide.


 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:

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(DatabaseClusterEngine.auroraMysql(AuroraMysqlClusterEngineProps.builder().version(AuroraMysqlEngineVersion.VER_2_08_1).build()))
         .credentials(Credentials.fromGeneratedSecret("clusteradmin")) // Optional - will default to 'admin' username and generated password
         .instanceProps(InstanceProps.builder()
                 // optional , defaults to t3.medium
                 .instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.SMALL))
                 .vpcSubnets(SubnetSelection.builder()
                         .subnetType(SubnetType.PRIVATE_WITH_NAT)
                         .build())
                 .vpc(vpc)
                 .build())
         .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.

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()))
         .instanceProps(InstanceProps.builder()
                 .vpc(vpc)
                 .build())
         .snapshotIdentifier("mySnapshot")
         .build();
 

Starting an instance database

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

 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_NAT)
                 .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_12_3).build()))
         // optional, defaults to m5.large
         .instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.SMALL))
         .vpc(vpc)
         .maxAllocatedStorage(200)
         .build();
 

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_12_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_14_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_14_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());
 

Setting Public Accessibility

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

 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_NAT)
                 .build())
         .publiclyAccessible(true)
         .build();
 
 // Setting public accessibility for DB cluster
 // Setting public accessibility for DB cluster
 DatabaseCluster.Builder.create(this, "DatabaseCluster")
         .engine(DatabaseClusterEngine.AURORA)
         .instanceProps(InstanceProps.builder()
                 .vpc(vpc)
                 .vpcSubnets(SubnetSelection.builder()
                         .subnetType(SubnetType.PRIVATE_WITH_NAT)
                         .build())
                 .publiclyAccessible(true)
                 .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_12_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_12_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_12_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:

 import software.amazon.awscdk.core.*;
 
 DatabaseInstance instance;
 
 instance.addRotationSingleUser(RotationSingleUserOptions.builder()
         .automaticallyAfter(Duration.days(7)) // defaults to 30 days
         .excludeCharacters("!@#$%^&*")
         .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();
 

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
         .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_NAT).build()) // Place rotation Lambda in private subnets
         .endpoint(myEndpoint)
         .build());
 

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

IAM Authentication

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

Note: grantConnect() does not currently work - see this GitHub issue.

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

 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);
 

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.AURORA)
         .instanceProps(InstanceProps.builder().vpc(vpc).build())
         .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.

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 ServicePrincipal("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();
 

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

Metrics

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

 // 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.AURORA)
         .instanceProps(InstanceProps.builder()
                 .vpc(vpc)
                 .build())
         .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

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()))
         .instanceProps(InstanceProps.builder()
                 .vpc(vpc)
                 .build())
         .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();
 
 // Exporting logs from an instance
 DatabaseInstance instance = DatabaseInstance.Builder.create(this, "Instance")
         .engine(DatabaseInstanceEngine.postgres(PostgresInstanceEngineProps.builder()
                 .version(PostgresEngineVersion.VER_12_3)
                 .build()))
         .vpc(vpc)
         .cloudwatchLogsExports(List.of("postgresql"))
         .build();
 

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)
         .parameterGroup(ParameterGroup.fromParameterGroupName(this, "ParameterGroup", "default.aurora-postgresql10"))
         .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)
                 .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 Serverless DB cluster using the built-in Data API. The Data API doesn't require a persistent connection to the DB cluster. Instead, it provides a secure HTTP endpoint and integration with AWS SDKs.

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

 Vpc vpc;
 
 Code code;
 
 
 ServerlessCluster cluster = ServerlessCluster.Builder.create(this, "AnotherCluster")
         .engine(DatabaseClusterEngine.AURORA_MYSQL)
         .vpc(vpc) // this parameter is optional for serverless Clusters
         .enableDataApi(true)
         .build();
 Function fn = Function.Builder.create(this, "MyFunction")
         .runtime(Runtime.NODEJS_14_X)
         .handler("index.handler")
         .code(code)
         .environment(Map.of(
                 "CLUSTER_ARN", cluster.getClusterArn(),
                 "SECRET_ARN", cluster.getSecret().getSecretArn()))
         .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. Deprecated: AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2. For more information on how to migrate, see https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html