Package software.amazon.awscdk.services.rds
Amazon Relational Database Service Construct Library
---
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:
- 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.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
-
ClassDescriptionAurora capacity units (ACUs).Creation properties of the plain Aurora database cluster engine.A builder for
AuroraClusterEnginePropsAn implementation forAuroraClusterEnginePropsThe versions for the Aurora cluster engine (those returned byDatabaseClusterEngine.aurora).Creation properties of the Aurora MySQL database cluster engine.A builder forAuroraMysqlClusterEnginePropsAn implementation forAuroraMysqlClusterEnginePropsThe versions for the Aurora MySQL cluster engine (those returned byDatabaseClusterEngine.auroraMysql).Creation properties of the Aurora PostgreSQL database cluster engine.A builder forAuroraPostgresClusterEnginePropsAn implementation forAuroraPostgresClusterEnginePropsFeatures supported by this version of the Aurora Postgres cluster engine.A builder forAuroraPostgresEngineFeaturesAn implementation forAuroraPostgresEngineFeaturesThe versions for the Aurora PostgreSQL cluster engine (those returned byDatabaseClusterEngine.auroraPostgres).Backup configuration for RDS databases.A builder forBackupPropsAn implementation forBackupPropsA CloudFormationAWS::RDS::DBCluster.A fluent builder forCfnDBCluster.Describes an AWS Identity and Access Management (IAM) role that is associated with a DB cluster.A builder forCfnDBCluster.DBClusterRolePropertyAn implementation forCfnDBCluster.DBClusterRolePropertyTheEndpointreturn value specifies the connection endpoint for the primary instance of the DB cluster.A builder forCfnDBCluster.EndpointPropertyAn implementation forCfnDBCluster.EndpointPropertyTheMasterUserSecretreturn value specifies the secret managed by RDS in AWS Secrets Manager for the master user password.A builder forCfnDBCluster.MasterUserSecretPropertyAn implementation forCfnDBCluster.MasterUserSecretPropertyTheReadEndpointreturn value specifies the reader endpoint for the DB cluster.A builder forCfnDBCluster.ReadEndpointPropertyAn implementation forCfnDBCluster.ReadEndpointPropertyTheScalingConfigurationproperty type specifies the scaling configuration of an Aurora Serverless DB cluster.A builder forCfnDBCluster.ScalingConfigurationPropertyAn implementation forCfnDBCluster.ScalingConfigurationPropertyTheServerlessV2ScalingConfigurationproperty type specifies the scaling configuration of an Aurora Serverless V2 DB cluster.A builder forCfnDBCluster.ServerlessV2ScalingConfigurationPropertyAn implementation forCfnDBCluster.ServerlessV2ScalingConfigurationPropertyA CloudFormationAWS::RDS::DBClusterParameterGroup.A fluent builder forCfnDBClusterParameterGroup.Properties for defining aCfnDBClusterParameterGroup.A builder forCfnDBClusterParameterGroupPropsAn implementation forCfnDBClusterParameterGroupPropsProperties for defining aCfnDBCluster.A builder forCfnDBClusterPropsAn implementation forCfnDBClusterPropsA CloudFormationAWS::RDS::DBInstance.A fluent builder forCfnDBInstance.Returns the details of the DB instance’s server certificate.A builder forCfnDBInstance.CertificateDetailsPropertyAn implementation forCfnDBInstance.CertificateDetailsPropertyDescribes an AWS Identity and Access Management (IAM) role that is associated with a DB instance.A builder forCfnDBInstance.DBInstanceRolePropertyAn implementation forCfnDBInstance.DBInstanceRolePropertyThis data type represents the information you need to connect to an Amazon RDS DB instance.A builder forCfnDBInstance.EndpointPropertyAn implementation forCfnDBInstance.EndpointPropertyTheMasterUserSecretreturn value specifies the secret managed by RDS in AWS Secrets Manager for the master user password.A builder forCfnDBInstance.MasterUserSecretPropertyAn implementation forCfnDBInstance.MasterUserSecretPropertyTheProcessorFeatureproperty type specifies the processor features of a DB instance class status.A builder forCfnDBInstance.ProcessorFeaturePropertyAn implementation forCfnDBInstance.ProcessorFeaturePropertyProperties for defining aCfnDBInstance.A builder forCfnDBInstancePropsAn implementation forCfnDBInstancePropsA CloudFormationAWS::RDS::DBParameterGroup.A fluent builder forCfnDBParameterGroup.Properties for defining aCfnDBParameterGroup.A builder forCfnDBParameterGroupPropsAn implementation forCfnDBParameterGroupPropsA CloudFormationAWS::RDS::DBProxy.Specifies the details of authentication used by a proxy to log in as a specific database user.A builder forCfnDBProxy.AuthFormatPropertyAn implementation forCfnDBProxy.AuthFormatPropertyA fluent builder forCfnDBProxy.Metadata assigned to a DB proxy consisting of a key-value pair.A builder forCfnDBProxy.TagFormatPropertyAn implementation forCfnDBProxy.TagFormatPropertyA CloudFormationAWS::RDS::DBProxyEndpoint.A fluent builder forCfnDBProxyEndpoint.Metadata assigned to a DB proxy endpoint consisting of a key-value pair.A builder forCfnDBProxyEndpoint.TagFormatPropertyAn implementation forCfnDBProxyEndpoint.TagFormatPropertyProperties for defining aCfnDBProxyEndpoint.A builder forCfnDBProxyEndpointPropsAn implementation forCfnDBProxyEndpointPropsProperties for defining aCfnDBProxy.A builder forCfnDBProxyPropsAn implementation forCfnDBProxyPropsA CloudFormationAWS::RDS::DBProxyTargetGroup.A fluent builder forCfnDBProxyTargetGroup.Specifies the settings that control the size and behavior of the connection pool associated with aDBProxyTargetGroup.An implementation forCfnDBProxyTargetGroup.ConnectionPoolConfigurationInfoFormatPropertyProperties for defining aCfnDBProxyTargetGroup.A builder forCfnDBProxyTargetGroupPropsAn implementation forCfnDBProxyTargetGroupPropsA CloudFormationAWS::RDS::DBSecurityGroup.A fluent builder forCfnDBSecurityGroup.TheIngressproperty type specifies an individual ingress rule within anAWS::RDS::DBSecurityGroupresource.A builder forCfnDBSecurityGroup.IngressPropertyAn implementation forCfnDBSecurityGroup.IngressPropertyA CloudFormationAWS::RDS::DBSecurityGroupIngress.A fluent builder forCfnDBSecurityGroupIngress.Properties for defining aCfnDBSecurityGroupIngress.A builder forCfnDBSecurityGroupIngressPropsAn implementation forCfnDBSecurityGroupIngressPropsProperties for defining aCfnDBSecurityGroup.A builder forCfnDBSecurityGroupPropsAn implementation forCfnDBSecurityGroupPropsA CloudFormationAWS::RDS::DBSubnetGroup.A fluent builder forCfnDBSubnetGroup.Properties for defining aCfnDBSubnetGroup.A builder forCfnDBSubnetGroupPropsAn implementation forCfnDBSubnetGroupPropsA CloudFormationAWS::RDS::EventSubscription.A fluent builder forCfnEventSubscription.Properties for defining aCfnEventSubscription.A builder forCfnEventSubscriptionPropsAn implementation forCfnEventSubscriptionPropsA CloudFormationAWS::RDS::GlobalCluster.A fluent builder forCfnGlobalCluster.Properties for defining aCfnGlobalCluster.A builder forCfnGlobalClusterPropsAn implementation forCfnGlobalClusterPropsA CloudFormationAWS::RDS::OptionGroup.A fluent builder forCfnOptionGroup.TheOptionConfigurationproperty type specifies an individual option, and its settings, within anAWS::RDS::OptionGroupresource.A builder forCfnOptionGroup.OptionConfigurationPropertyAn implementation forCfnOptionGroup.OptionConfigurationPropertyTheOptionSettingproperty type specifies the value for an option within anOptionSettingproperty.A builder forCfnOptionGroup.OptionSettingPropertyAn implementation forCfnOptionGroup.OptionSettingPropertyProperties for defining aCfnOptionGroup.A builder forCfnOptionGroupPropsAn implementation forCfnOptionGroupPropsThe extra options passed to theIClusterEngine.bindToClustermethod.A builder forClusterEngineBindOptionsAn implementation forClusterEngineBindOptionsThe type returned from theIClusterEngine.bindToClustermethod.A builder forClusterEngineConfigAn implementation forClusterEngineConfigRepresents Database Engine features.A builder forClusterEngineFeaturesAn implementation forClusterEngineFeaturesProperties common to single-user and multi-user rotation options.A builder forCommonRotationUserOptionsAn implementation forCommonRotationUserOptionsUsername and password combination.Base options for creating Credentials.A builder forCredentialsBaseOptionsAn implementation forCredentialsBaseOptionsOptions for creating Credentials from a username.A builder forCredentialsFromUsernameOptionsAn implementation forCredentialsFromUsernameOptionsCreate a clustered database with a given number of instances.A fluent builder forDatabaseCluster.Properties that describe an existing cluster instance.A builder forDatabaseClusterAttributesAn implementation forDatabaseClusterAttributesA new or imported clustered database.A database cluster engine.A database cluster restored from a snapshot.A fluent builder forDatabaseClusterFromSnapshot.Properties forDatabaseClusterFromSnapshot.A builder forDatabaseClusterFromSnapshotPropsAn implementation forDatabaseClusterFromSnapshotPropsProperties for a new database cluster.A builder forDatabaseClusterPropsAn implementation forDatabaseClusterPropsA database instance.A fluent builder forDatabaseInstance.Properties that describe an existing instance.A builder forDatabaseInstanceAttributesAn implementation forDatabaseInstanceAttributesA 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 forDatabaseInstanceFromSnapshotPropsAn implementation forDatabaseInstanceFromSnapshotPropsConstruction properties for a DatabaseInstanceNew.A builder forDatabaseInstanceNewPropsAn implementation forDatabaseInstanceNewPropsConstruction properties for a DatabaseInstance.A builder forDatabaseInstancePropsAn implementation forDatabaseInstancePropsA read replica database instance.A fluent builder forDatabaseInstanceReadReplica.Construction properties for a DatabaseInstanceReadReplica.A builder forDatabaseInstanceReadReplicaPropsAn implementation forDatabaseInstanceReadReplicaPropsConstruction properties for a DatabaseInstanceSource.A builder forDatabaseInstanceSourcePropsAn implementation forDatabaseInstanceSourcePropsRDS Database Proxy.A fluent builder forDatabaseProxy.Properties that describe an existing DB Proxy.A builder forDatabaseProxyAttributesAn implementation forDatabaseProxyAttributesOptions for a new DatabaseProxy.A builder forDatabaseProxyOptionsAn implementation forDatabaseProxyOptionsConstruction properties for a DatabaseProxy.A builder forDatabaseProxyPropsAn implementation forDatabaseProxyPropsA database secret.A fluent builder forDatabaseSecret.Construction properties for a DatabaseSecret.A builder forDatabaseSecretPropsAn implementation forDatabaseSecretPropsConnection endpoint of a database cluster or instance.A version of an engine - for either a cluster, or instance.A builder forEngineVersionAn implementation forEngineVersionThe 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.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 forInstanceEngineBindOptionsAn implementation forInstanceEngineBindOptionsThe type returned from theIInstanceEngine.bindmethod.A builder forInstanceEngineConfigAn implementation forInstanceEngineConfigRepresents Database Engine features.A builder forInstanceEngineFeaturesAn implementation forInstanceEngineFeaturesInstance properties for database instances.A builder forInstancePropsAn implementation forInstancePropsAn 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 forMariaDbInstanceEnginePropsAn implementation forMariaDbInstanceEnginePropsThe versions for the MySQL instance engines (those returned byDatabaseInstanceEngine.mysql).Properties for MySQL instance engines.A builder forMySqlInstanceEnginePropsAn implementation forMySqlInstanceEnginePropsConfiguration properties for an option.A builder forOptionConfigurationAn implementation forOptionConfigurationAn option group.A fluent builder forOptionGroup.Construction properties for an OptionGroup.A builder forOptionGroupPropsAn implementation forOptionGroupPropsProperties for Oracle Enterprise Edition instance engines.A builder forOracleEeInstanceEnginePropsAn implementation forOracleEeInstanceEnginePropsThe versions for the Oracle instance engines (those returned byDatabaseInstanceEngine.oracleSe2andDatabaseInstanceEngine.oracleEe).Deprecated.instances can no longer be created with these engine versions.Deprecated.instances can no longer be created with this engine.Deprecated.Deprecated.Properties for Oracle Standard Edition 2 instance engines.A builder forOracleSe2InstanceEnginePropsAn implementation forOracleSe2InstanceEnginePropsDeprecated.instances can no longer be created with this engine.Deprecated.Deprecated.A parameter group.A fluent builder forParameterGroup.Options forIParameterGroup.bindToCluster.A builder forParameterGroupClusterBindOptionsAn implementation forParameterGroupClusterBindOptionsThe type returned fromIParameterGroup.bindToCluster.A builder forParameterGroupClusterConfigAn implementation forParameterGroupClusterConfigOptions forIParameterGroup.bindToInstance.A builder forParameterGroupInstanceBindOptionsAn implementation forParameterGroupInstanceBindOptionsThe type returned fromIParameterGroup.bindToInstance.A builder forParameterGroupInstanceConfigAn implementation forParameterGroupInstanceConfigProperties for a parameter group.A builder forParameterGroupPropsAn implementation forParameterGroupPropsThe retention period for Performance Insight.Features supported by the Postgres database engine.A builder forPostgresEngineFeaturesAn implementation forPostgresEngineFeaturesThe versions for the PostgreSQL instance engines (those returned byDatabaseInstanceEngine.postgres).Properties for PostgreSQL instance engines.A builder forPostgresInstanceEnginePropsAn implementation forPostgresInstanceEnginePropsThe processor features.A builder forProcessorFeaturesAn implementation forProcessorFeaturesProxy target: Instance or Cluster.The result of binding aProxyTargetto aDatabaseProxy.A builder forProxyTargetConfigAn implementation forProxyTargetConfigOptions to add the multi user rotation.A builder forRotationMultiUserOptionsAn implementation forRotationMultiUserOptionsOptions to add the multi user rotation.A builder forRotationSingleUserOptionsAn implementation forRotationSingleUserOptionsCreate an Aurora Serverless Cluster.A fluent builder forServerlessCluster.Properties that describe an existing cluster instance.A builder forServerlessClusterAttributesAn implementation forServerlessClusterAttributesA Aurora Serverless Cluster restored from a snapshot.A fluent builder forServerlessClusterFromSnapshot.Properties forServerlessClusterFromSnapshot.A builder forServerlessClusterFromSnapshotPropsAn implementation forServerlessClusterFromSnapshotPropsProperties for a new Aurora Serverless Cluster.A builder forServerlessClusterPropsAn implementation forServerlessClusterPropsOptions for configuring scaling on an Aurora Serverless cluster.A builder forServerlessScalingOptionsAn implementation forServerlessScalingOptionsSessionPinningFilter.Credentials to update the password for aDatabaseInstanceFromSnapshot.Options used in theSnapshotCredentials.fromGeneratedPasswordmethod.A builder forSnapshotCredentialsFromGeneratedPasswordOptionsAn implementation forSnapshotCredentialsFromGeneratedPasswordOptionsProperties for SQL Server Enterprise Edition instance engines.A builder forSqlServerEeInstanceEnginePropsAn implementation forSqlServerEeInstanceEnginePropsThe versions for the SQL Server instance engines (those returned byDatabaseInstanceEngine.sqlServerSe,DatabaseInstanceEngine.sqlServerEx,DatabaseInstanceEngine.sqlServerWebandDatabaseInstanceEngine.sqlServerEe).Properties for SQL Server Express Edition instance engines.A builder forSqlServerExInstanceEnginePropsAn implementation forSqlServerExInstanceEnginePropsProperties for SQL Server Standard Edition instance engines.A builder forSqlServerSeInstanceEnginePropsAn implementation forSqlServerSeInstanceEnginePropsProperties for SQL Server Web Edition instance engines.A builder forSqlServerWebInstanceEnginePropsAn implementation forSqlServerWebInstanceEnginePropsThe type of storage.Class for creating a RDS DB subnet group.A fluent builder forSubnetGroup.Properties for creating a SubnetGroup.A builder forSubnetGroupPropsAn implementation forSubnetGroupProps