Skip navigation links

Package software.amazon.awscdk.services.rds

Amazon Relational Database Service Construct Library

See: Description

Package software.amazon.awscdk.services.rds Description

Amazon Relational Database Service Construct Library

---

cfn-resources: Stable

cdk-constructs: Stable


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

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(rds.DatabaseClusterEngine.auroraMysql(Map.of("version", rds.AuroraMysqlEngineVersion.getVER_2_08_1())))
         .credentials(rds.Credentials.fromGeneratedSecret("clusteradmin"))// Optional - will default to 'admin' username and generated password
         .instanceProps(Map.of(
                 // optional , defaults to t3.medium
                 "instanceType", ec2.InstanceType.of(ec2.InstanceClass.getBURSTABLE2(), ec2.InstanceSize.getSMALL()),
                 "vpcSubnets", Map.of(
                         "subnetType", ec2.SubnetType.getPRIVATE()),
                 "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.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object customEngineVersion = rds.AuroraMysqlEngineVersion.of("5.7.mysql_aurora.2.08.1");
 

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

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

Use DatabaseClusterFromSnapshot to create a cluster from a snapshot:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 DatabaseClusterFromSnapshot.Builder.create(stack, "Database")
         .engine(rds.DatabaseClusterEngine.aurora(Map.of("version", rds.AuroraEngineVersion.getVER_1_22_2())))
         .instanceProps(Map.of(
                 "vpc", vpc))
         .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:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object instance = DatabaseInstance.Builder.create(this, "Instance")
         .engine(rds.DatabaseInstanceEngine.oracleSe2(Map.of("version", rds.OracleEngineVersion.getVER_19_0_0_0_2020_04_R1())))
         // optional, defaults to m5.large
         .instanceType(ec2.InstanceType.of(ec2.InstanceClass.getBURSTABLE3(), ec2.InstanceSize.getSMALL()))
         .credentials(rds.Credentials.fromGeneratedSecret("syscdk"))// Optional - will default to 'admin' username and generated password
         .vpc(vpc)
         .vpcSubnets(Map.of(
                 "subnetType", ec2.SubnetType.getPRIVATE()))
         .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.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object customEngineVersion = rds.OracleEngineVersion.of("19.0.0.0.ru-2020-04.rur-2020-04.r1", "19");
 

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

To use the storage auto scaling option of RDS you can specify the maximum allocated storage. This is the upper limit to which RDS can automatically scale the storage. More info can be found here Example for max storage configuration:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object instance = DatabaseInstance.Builder.create(this, "Instance")
         .engine(rds.DatabaseInstanceEngine.postgres(Map.of("version", rds.PostgresEngineVersion.getVER_12_3())))
         // optional, defaults to m5.large
         .instanceType(ec2.InstanceType.of(ec2.InstanceClass.getBURSTABLE2(), ec2.InstanceSize.getSMALL()))
         .vpc(vpc)
         .maxAllocatedStorage(200)
         .build();
 

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

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 DatabaseInstanceFromSnapshot.Builder.create(stack, "Instance")
         .snapshotIdentifier("my-snapshot")
         .engine(rds.DatabaseInstanceEngine.postgres(Map.of("version", rds.PostgresEngineVersion.getVER_12_3())))
         // optional, defaults to m5.large
         .instanceType(ec2.InstanceType.of(ec2.InstanceClass.getBURSTABLE2(), ec2.InstanceSize.getLARGE()))
         .vpc(vpc)
         .build();
 
 DatabaseInstanceReadReplica.Builder.create(stack, "ReadReplica")
         .sourceDatabaseInstance(sourceInstance)
         .instanceType(ec2.InstanceType.of(ec2.InstanceClass.getBURSTABLE2(), ec2.InstanceSize.getLARGE()))
         .vpc(vpc)
         .build();
 

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

 // Example automatically generated. See https://github.com/aws/jsii/issues/826
 // Set open cursors with parameter group
 ParameterGroup parameterGroup = new ParameterGroup(this, "ParameterGroup", new ParameterGroupProps()
         .engine(rds.DatabaseInstanceEngine.oracleSe2(new OracleSe2InstanceEngineProps().version(rds.OracleEngineVersion.getVER_19_0_0_0_2020_04_R1())))
         .parameters(Map.of(
                 "open_cursors", "2500")));
 
 OptionGroup optionGroup = new OptionGroup(this, "OptionGroup", new OptionGroupProps()
         .engine(rds.DatabaseInstanceEngine.oracleSe2(new OracleSe2InstanceEngineProps().version(rds.OracleEngineVersion.getVER_19_0_0_0_2020_04_R1())))
         .configurations(asList(new OptionConfiguration()
                 .name("LOCATOR"), new OptionConfiguration()
                 .name("OEM")
                 .port(1158)
                 .vpc(vpc))));
 
 // Allow connections to OEM
 optionGroup.optionConnections.OEM.connections.allowDefaultPortFromAnyIpv4();
 
 // Database instance with production values
 DatabaseInstance instance = new DatabaseInstance(this, "Instance", new DatabaseInstanceProps()
         .engine(rds.DatabaseInstanceEngine.oracleSe2(new OracleSe2InstanceEngineProps().version(rds.OracleEngineVersion.getVER_19_0_0_0_2020_04_R1())))
         .licenseModel(rds.LicenseModel.getBRING_YOUR_OWN_LICENSE())
         .instanceType(ec2.InstanceType.of(ec2.InstanceClass.getBURSTABLE3(), ec2.InstanceSize.getMEDIUM()))
         .multiAz(true)
         .storageType(rds.StorageType.getIO1())
         .credentials(rds.Credentials.fromUsername("syscdk"))
         .vpc(vpc)
         .databaseName("ORCL")
         .storageEncrypted(true)
         .backupRetention(cdk.Duration.days(7))
         .monitoringInterval(cdk.Duration.seconds(60))
         .enablePerformanceInsights(true)
         .cloudwatchLogsExports(asList("trace", "audit", "alert", "listener"))
         .cloudwatchLogsRetention(logs.RetentionDays.getONE_MONTH())
         .autoMinorVersionUpgrade(false)
         .optionGroup(optionGroup)
         .parameterGroup(parameterGroup));
 
 // 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
 new Alarm(this, "HighCPU", new AlarmProps()
         .metric(instance.metricCPUUtilization())
         .threshold(90)
         .evaluationPeriods(1));
 
 // Trigger Lambda function on instance availability events
 Function fn = new Function(this, "Function", new FunctionProps()
         .code(lambda.Code.fromInline("exports.handler = (event) => console.log(event);"))
         .handler("index.handler")
         .runtime(lambda.Runtime.getNODEJS_10_X()));
 
 Rule availabilityRule = instance.onEvent("Availability", new OnEventOptions().target(new LambdaFunction(fn)));
 availabilityRule.addEventPattern(new EventPattern()
         .detail(Map.of(
                 "EventCategories", asList("availability"))));
 

Add XMLDB and OEM with option group

 // Example automatically generated. See https://github.com/aws/jsii/issues/826
 // Set open cursors with parameter group
 ParameterGroup parameterGroup = new ParameterGroup(this, "ParameterGroup", new ParameterGroupProps()
         .engine(rds.DatabaseInstanceEngine.oracleSe2(new OracleSe2InstanceEngineProps().version(rds.OracleEngineVersion.getVER_19_0_0_0_2020_04_R1())))
         .parameters(Map.of(
                 "open_cursors", "2500")));
 
 OptionGroup optionGroup = new OptionGroup(this, "OptionGroup", new OptionGroupProps()
         .engine(rds.DatabaseInstanceEngine.oracleSe2(new OracleSe2InstanceEngineProps().version(rds.OracleEngineVersion.getVER_19_0_0_0_2020_04_R1())))
         .configurations(asList(new OptionConfiguration()
                 .name("LOCATOR"), new OptionConfiguration()
                 .name("OEM")
                 .port(1158)
                 .vpc(vpc))));
 
 // Allow connections to OEM
 optionGroup.optionConnections.OEM.connections.allowDefaultPortFromAnyIpv4();
 
 // Database instance with production values
 DatabaseInstance instance = new DatabaseInstance(this, "Instance", new DatabaseInstanceProps()
         .engine(rds.DatabaseInstanceEngine.oracleSe2(new OracleSe2InstanceEngineProps().version(rds.OracleEngineVersion.getVER_19_0_0_0_2020_04_R1())))
         .licenseModel(rds.LicenseModel.getBRING_YOUR_OWN_LICENSE())
         .instanceType(ec2.InstanceType.of(ec2.InstanceClass.getBURSTABLE3(), ec2.InstanceSize.getMEDIUM()))
         .multiAz(true)
         .storageType(rds.StorageType.getIO1())
         .credentials(rds.Credentials.fromUsername("syscdk"))
         .vpc(vpc)
         .databaseName("ORCL")
         .storageEncrypted(true)
         .backupRetention(cdk.Duration.days(7))
         .monitoringInterval(cdk.Duration.seconds(60))
         .enablePerformanceInsights(true)
         .cloudwatchLogsExports(asList("trace", "audit", "alert", "listener"))
         .cloudwatchLogsRetention(logs.RetentionDays.getONE_MONTH())
         .autoMinorVersionUpgrade(false)
         .optionGroup(optionGroup)
         .parameterGroup(parameterGroup));
 
 // 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
 new Alarm(this, "HighCPU", new AlarmProps()
         .metric(instance.metricCPUUtilization())
         .threshold(90)
         .evaluationPeriods(1));
 
 // Trigger Lambda function on instance availability events
 Function fn = new Function(this, "Function", new FunctionProps()
         .code(lambda.Code.fromInline("exports.handler = (event) => console.log(event);"))
         .handler("index.handler")
         .runtime(lambda.Runtime.getNODEJS_10_X()));
 
 Rule availabilityRule = instance.onEvent("Availability", new OnEventOptions().target(new LambdaFunction(fn)));
 availabilityRule.addEventPattern(new EventPattern()
         .detail(Map.of(
                 "EventCategories", asList("availability"))));
 

Setting Public Accessibility

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

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Setting public accessibility for DB instance
 // Setting public accessibility for DB instance
 DatabaseInstance.Builder.create(stack, "Instance")
         .engine(rds.DatabaseInstanceEngine.mysql(Map.of(
                 "version", rds.MysqlEngineVersion.getVER_8_0_19())))
         .vpc(vpc)
         .vpcSubnets(Map.of(
                 "subnetType", ec2.SubnetType.getPRIVATE()))
         .publiclyAccessible(true)
         .build();
 
 // Setting public accessibility for DB cluster
 // Setting public accessibility for DB cluster
 DatabaseCluster.Builder.create(stack, "DatabaseCluster")
         .engine(DatabaseClusterEngine.getAURORA())
         .instanceProps(Map.of(
                 "vpc", vpc,
                 "vpcSubnets", Map.of(
                         "subnetType", ec2.SubnetType.getPRIVATE()),
                 "publiclyAccessible", true,
                 "copyTagsToSnapshot", true))
         .build();
 

Instance events

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

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object rule = instance.onEvent("InstanceEvent", Map.of("target", new LambdaFunction(fn)));
 

Login credentials

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

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

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object engine = rds.DatabaseInstanceEngine.postgres(Map.of("version", rds.PostgresEngineVersion.getVER_12_3()));
 DatabaseInstance.Builder.create(this, "InstanceWithUsername")
         .engine(engine)
         .vpc(vpc)
         .credentials(rds.Credentials.fromGeneratedSecret("postgres"))
         .build();
 
 DatabaseInstance.Builder.create(this, "InstanceWithUsernameAndPassword")
         .engine(engine)
         .vpc(vpc)
         .credentials(rds.Credentials.fromPassword("postgres", SecretValue.ssmSecure("/dbPassword", "1")))
         .build();
 
 Object mySecret = secretsmanager.Secret.fromSecretName(this, "DBSecret", "myDBLoginInfo");
 DatabaseInstance.Builder.create(this, "InstanceWithSecretLogin")
         .engine(engine)
         .vpc(vpc)
         .credentials(rds.Credentials.fromSecret(mySecret))
         .build();
 

Secrets generated by fromGeneratedSecret() can be customized:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object myKey = kms.Key(this, "MyKey");
 
 DatabaseInstance.Builder.create(this, "InstanceWithCustomizedSecret")
         .engine(engine)
         .vpc(vpc)
         .credentials(rds.Credentials.fromGeneratedSecret("postgres", Map.of(
                 "secretName", "my-cool-name",
                 "encryptionKey", myKey,
                 "excludeCharacters", asList("!&*^#@()"),
                 "replicaRegions", asList(Map.of("region", "eu-west-1"), Map.of("region", "eu-west-2")))))
         .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:

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

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

 // Example automatically generated. See https://github.com/aws/jsii/issues/826
 Object writeAddress = cluster.clusterEndpoint.getSocketAddress();
 

For an instance database:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object address = instance.instanceEndpoint.getSocketAddress();
 

Rotating credentials

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

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 instance.addRotationSingleUser(Map.of(
         "automaticallyAfter", cdk.Duration.days(7), // defaults to 30 days
         "excludeCharacters", "!@#$%^&*"));
 

 // Example automatically generated. See https://github.com/aws/jsii/issues/826
 DatabaseCluster cluster = new DatabaseCluster(stack, "Database", new DatabaseClusterProps()
         .engine(rds.DatabaseClusterEngine.getAURORA())
         .instanceProps(Map.of(
                 "instanceType", ec2.InstanceType.of(ec2.InstanceClass.getBURSTABLE3(), ec2.InstanceSize.getSMALL()),
                 "vpc", vpc)));
 
 cluster.addRotationSingleUser();
 

The multi user rotation scheme is also available:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 instance.addRotationMultiUser("MyUser", Map.of(
         "secret", myImportedSecret));
 

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

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object myUserSecret = DatabaseSecret.Builder.create(this, "MyUserSecret")
         .username("myuser")
         .secretName("my-user-secret")// optional, defaults to a CloudFormation-generated name
         .masterSecret(instance.getSecret())
         .excludeCharacters("{}[]()'\"/\\")
         .build();
 Object myUserSecretAttached = myUserSecret.attach(instance);// Adds DB connections information in the secret
 
 instance.addRotationMultiUser("MyUser", Map.of(// Add rotation using the multi user scheme
         "secret", myUserSecretAttached));
 

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

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

IAM Authentication

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

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

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object instance = DatabaseInstance.Builder.create(stack, "Instance")
         .engine(rds.DatabaseInstanceEngine.mysql(Map.of("version", rds.MysqlEngineVersion.getVER_8_0_19())))
         .vpc(vpc)
         .iamAuthentication(true)
         .build();
 Object role = Role.Builder.create(stack, "DBRole").assumedBy(new AccountPrincipal(stack.getAccount())).build();
 instance.grantConnect(role);
 

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

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object cluster = DatabaseCluster.Builder.create(stack, "Database")
         .engine(rds.DatabaseClusterEngine.getAURORA())
         .instanceProps(Map.of("vpc", vpc))
         .build();
 
 Object proxy = DatabaseProxy.Builder.create(stack, "Proxy")
         .proxyTarget(rds.ProxyTarget.fromCluster(cluster))
         .secrets(asList(cluster.getSecret()))
         .vpc(vpc)
         .build();
 
 Object role = Role.Builder.create(stack, "DBProxyRole").assumedBy(new AccountPrincipal(stack.getAccount())).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.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Role role = new Role(stack, "RDSDirectoryServicesRole", new RoleProps()
         .assumedBy(new ServicePrincipal("rds.amazonaws.com"))
         .managedPolicies(asList(iam.ManagedPolicy.fromAwsManagedPolicyName("service-role/AmazonRDSDirectoryServiceAccess"))));
 Object instance = DatabaseInstance.Builder.create(stack, "Instance")
         .engine(rds.DatabaseInstanceEngine.mysql(Map.of("version", rds.MysqlEngineVersion.getVER_8_0_19())))
         .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):

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // The number of database connections in use (average over 5 minutes)
 Object dbConnections = instance.metricDatabaseConnections();
 
 // Average CPU utilization over 5 minutes
 Object cpuUtilization = cluster.metricCPUUtilization();
 
 // The average amount of time taken per disk I/O operation (average over 1 minute)
 Object readLatency = instance.metric("ReadLatency", Map.of("statistic", "Average", "periodSec", 60));
 

Enabling S3 integration

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

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

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

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.s3.*;
 
 Bucket importBucket = new Bucket(this, "importbucket");
 Bucket exportBucket = new Bucket(this, "exportbucket");
 DatabaseCluster.Builder.create(this, "dbcluster")
         // ...
         .s3ImportBuckets(asList(importBucket))
         .s3ExportBuckets(asList(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.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.core.*;
 import software.amazon.awscdk.services.ec2.*;
 import software.amazon.awscdk.services.rds.*;
 import software.amazon.awscdk.services.secretsmanager.*;
 
 IVpc vpc = ;
 ISecurityGroup securityGroup = ;
 Array secrets = asList(...);
 IDatabaseInstance dbInstance = ;
 
 DatabaseProxy proxy = dbInstance.addProxy("proxy", new DatabaseProxyOptions()
         .connectionBorrowTimeout(cdk.Duration.seconds(30))
         .maxConnectionsPercent(50)
         .secrets(secrets)
         .vpc(vpc));
 

Exporting Logs

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

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Exporting logs from a cluster
 Object cluster = DatabaseCluster.Builder.create(this, "Database")
         .engine(rds.DatabaseClusterEngine.aurora(Map.of(
                 "version", rds.AuroraEngineVersion.getVER_1_17_9()), cloudwatchLogsExports, asList("error", "general", "slowquery", "audit"), cloudwatchLogsRetention, logs.RetentionDays.getTHREE_MONTHS(), cloudwatchLogsRetentionRole, myLogsPublishingRole))
         .build();
 
 // Exporting logs from an instance
 Object instance = DatabaseInstance.Builder.create(this, "Instance")
         .engine(rds.DatabaseInstanceEngine.postgres(Map.of(
                 "version", rds.PostgresEngineVersion.getVER_12_3())))
         // ...
         .cloudwatchLogsExports(asList("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.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object vpc = ;
 Object securityGroup = ;
 OptionGroup.Builder.create(stack, "Options")
         .engine(rds.DatabaseInstanceEngine.oracleSe2(Map.of(
                 "version", rds.OracleEngineVersion.getVER_19())))
         .configurations(asList(Map.of(
                 "name", "OEM",
                 "port", 5500,
                 "vpc", vpc,
                 "securityGroups", asList(securityGroup))))
         .build();
 

Serverless

Amazon Aurora Serverless is an on-demand, auto-scaling configuration for Amazon Aurora. The database will automatically start up, shut down, and scale capacity up or down based on your application's needs. It enables you to run your database in the cloud without managing any database instances.

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

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.ec2.*;
 import software.amazon.awscdk.services.rds.*;
 
 Vpc vpc = new Vpc(this, "myrdsvpc");
 
 ServerlessCluster cluster = new ServerlessCluster(this, "AnotherCluster", new ServerlessClusterProps()
         .engine(rds.DatabaseClusterEngine.getAURORA_POSTGRESQL())
         .parameterGroup(rds.ParameterGroup.fromParameterGroupName(this, "ParameterGroup", "default.aurora-postgresql10"))
         .vpc(vpc)
         .scaling(new ServerlessScalingOptions()
                 .autoPause(Duration.minutes(10))// default is to pause after 5 minutes of idle time
                 .minCapacity(rds.AuroraCapacityUnit.getACU_8())// default is 2 Aurora capacity units (ACUs)
                 .maxCapacity(rds.AuroraCapacityUnit.getACU_32())));
 

Aurora Serverless Clusters do not support the following features:

Read more about the limitations of Aurora Serverless

Learn more about using Amazon Aurora Serverless by reading the documentation

Data API

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

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

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.ec2.*;
 import software.amazon.awscdk.services.lambda.*;
 import software.amazon.awscdk.services.rds.*;
 
 Vpc vpc = new Vpc(this, "MyVPC");
 
 ServerlessCluster cluster = new ServerlessCluster(this, "AnotherCluster", new ServerlessClusterProps()
         .engine(rds.DatabaseClusterEngine.getAURORA_MYSQL())
         .vpc(vpc)
         .enableDataApi(true));
 
 Function fn = new Function(this, "MyFunction", new FunctionProps()
         .runtime(lambda.Runtime.getNODEJS_12_X())
         .handler("index.handler")
         .code(lambda.Code.fromAsset(path.join(__dirname, "lambda-handler")))
         .environment(Map.of(
                 "CLUSTER_ARN", cluster.getClusterArn(),
                 "SECRET_ARN", cluster.secret.getSecretArn())));
 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.

Skip navigation links