Namespace Amazon.CDK.AWS.RDS
Amazon Relational Database Service Construct Library
using Amazon.CDK.AWS.RDS;
Starting a clustered database
To set up a clustered database (like Aurora), define a DatabaseCluster
. You must
always launch a database in a VPC. Use the vpcSubnets
attribute to control whether
your instances will be launched privately or publicly:
You must specify the instance to use as the writer, along with an optional list of readers (up to 15).
Vpc vpc;
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps { Version = AuroraMysqlEngineVersion.VER_3_01_0 }),
Credentials = Credentials.FromGeneratedSecret("clusteradmin"), // Optional - will default to 'admin' username and generated password
Writer = ClusterInstance.Provisioned("writer", new ProvisionedClusterInstanceProps {
PubliclyAccessible = false
}),
Readers = new [] { ClusterInstance.Provisioned("reader1", new ProvisionedClusterInstanceProps { PromotionTier = 1 }), ClusterInstance.ServerlessV2("reader2") },
VpcSubnets = new SubnetSelection {
SubnetType = SubnetType.PRIVATE_WITH_EGRESS
},
Vpc = vpc
});
To adopt Aurora I/O-Optimized, specify DBClusterStorageType.AURORA_IOPT1
on the storageType
property.
Vpc vpc;
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraPostgres(new AuroraPostgresClusterEngineProps { Version = AuroraPostgresEngineVersion.VER_15_2 }),
Credentials = Credentials.FromUsername("adminuser", new CredentialsFromUsernameOptions { Password = SecretValue.UnsafePlainText("7959866cacc02c2d243ecfe177464fe6") }),
Writer = ClusterInstance.Provisioned("writer", new ProvisionedClusterInstanceProps {
PubliclyAccessible = false
}),
Readers = new [] { ClusterInstance.Provisioned("reader") },
StorageType = DBClusterStorageType.AURORA_IOPT1,
VpcSubnets = new SubnetSelection {
SubnetType = SubnetType.PRIVATE_WITH_EGRESS
},
Vpc = vpc
});
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.
var customEngineVersion = AuroraMysqlEngineVersion.Of("5.7.mysql_aurora.2.08.1");
By default, the master password will be generated and stored in AWS Secrets Manager with auto-generated description.
Your cluster will be empty by default. To add a default database upon construction, specify the
defaultDatabaseName
attribute.
To use dual-stack mode, specify NetworkType.DUAL
on the networkType
property:
Vpc vpc;
// VPC and subnets must have IPv6 CIDR blocks
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps { Version = AuroraMysqlEngineVersion.VER_3_02_1 }),
Writer = ClusterInstance.Provisioned("writer", new ProvisionedClusterInstanceProps {
PubliclyAccessible = false
}),
Vpc = vpc,
NetworkType = NetworkType.DUAL
});
For more information about dual-stack mode, see Working with a DB cluster in a VPC.
If you want to issue read/write transactions directly on an Aurora Replica, you can use local write forwarding. Local write forwarding allows read replicas to accept write transactions and forward them to the writer DB instance to be committed.
To enable local write forwarding, set the enableLocalWriteForwarding
property to true
:
IVpc vpc;
new DatabaseCluster(this, "DatabaseCluster", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps { Version = AuroraMysqlEngineVersion.VER_3_07_0 }),
Writer = ClusterInstance.ServerlessV2("writerInstance"),
Readers = new [] { ClusterInstance.ServerlessV2("readerInstance1") },
Vpc = vpc,
EnableLocalWriteForwarding = true
});
Note: Local write forwarding is only supported for Aurora MySQL 3.04 and higher.
Use DatabaseClusterFromSnapshot
to create a cluster from a snapshot:
Vpc vpc;
new DatabaseClusterFromSnapshot(this, "Database", new DatabaseClusterFromSnapshotProps {
Engine = DatabaseClusterEngine.Aurora(new AuroraClusterEngineProps { Version = AuroraEngineVersion.VER_1_22_2 }),
Writer = ClusterInstance.Provisioned("writer"),
Vpc = vpc,
SnapshotIdentifier = "mySnapshot"
});
Updating the database instances in a cluster
Database cluster instances may be updated in bulk or on a rolling basis.
An update to all instances in a cluster may cause significant downtime. To reduce the downtime, set the
instanceUpdateBehavior
property in DatabaseClusterBaseProps
to InstanceUpdateBehavior.ROLLING
.
This adds a dependency between each instance so the update is performed on only one instance at a time.
Use InstanceUpdateBehavior.BULK
to update all instances at once.
Vpc vpc;
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps { Version = AuroraMysqlEngineVersion.VER_3_01_0 }),
Writer = ClusterInstance.Provisioned("Instance", new ProvisionedClusterInstanceProps {
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.SMALL)
}),
Readers = new [] { ClusterInstance.Provisioned("reader") },
InstanceUpdateBehaviour = InstanceUpdateBehaviour.ROLLING, // Optional - defaults to rds.InstanceUpdateBehaviour.BULK
Vpc = vpc
});
Serverless V2 instances in a Cluster
It is possible to create an RDS cluster with both serverlessV2 and provisioned instances. For example, this will create a cluster with a provisioned writer and a serverless v2 reader.
Note Before getting starting with this type of cluster it is highly recommended that you read through the Developer Guide which goes into much more detail on the things you need to take into consideration.
Vpc vpc;
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps { Version = AuroraMysqlEngineVersion.VER_3_01_0 }),
Writer = ClusterInstance.Provisioned("writer"),
Readers = new [] { ClusterInstance.ServerlessV2("reader") },
Vpc = vpc
});
Monitoring
There are some CloudWatch metrics that are important for Aurora Serverless v2.
Vpc vpc;
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps { Version = AuroraMysqlEngineVersion.VER_3_01_0 }),
Writer = ClusterInstance.Provisioned("writer"),
Readers = new [] { ClusterInstance.ServerlessV2("reader") },
Vpc = vpc
});
cluster.MetricServerlessDatabaseCapacity(new MetricOptions {
Period = Duration.Minutes(10)
}).CreateAlarm(this, "capacity", new CreateAlarmOptions {
Threshold = 1.5,
EvaluationPeriods = 3
});
cluster.MetricACUUtilization(new MetricOptions {
Period = Duration.Minutes(10)
}).CreateAlarm(this, "alarm", new CreateAlarmOptions {
EvaluationPeriods = 3,
Threshold = 90
});
Capacity & Scaling
There are some things to take into consideration with Aurora Serverless v2.
To create a cluster that can support serverless v2 instances you configure a minimum and maximum capacity range on the cluster. This is an example showing the default values:
Vpc vpc;
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps { Version = AuroraMysqlEngineVersion.VER_3_01_0 }),
Writer = ClusterInstance.ServerlessV2("writer"),
ServerlessV2MinCapacity = 0.5,
ServerlessV2MaxCapacity = 2,
Vpc = vpc
});
The capacity is defined as a number of Aurora capacity units (ACUs). You can specify in half-step increments (40, 40.5, 41, etc). Each serverless instance in the cluster inherits the capacity that is defined on the cluster. It is not possible to configure separate capacity at the instance level.
The maximum capacity is mainly used for budget control since it allows you to set a cap on how high your instance can scale.
The minimum capacity is a little more involved. This controls a couple different things.
Info More complete details can be found in the docs
Another way that you control the capacity/scaling of your serverless v2 reader instances is based on the promotion tier which can be between 0-15. Any serverless v2 instance in the 0-1 tiers will scale alongside the writer even if the current read load does not require the capacity. This is because instances in the 0-1 tier are first priority for failover and Aurora wants to ensure that in the event of a failover the reader that gets promoted is scaled to handle the write load.
Vpc vpc;
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps { Version = AuroraMysqlEngineVersion.VER_3_01_0 }),
Writer = ClusterInstance.ServerlessV2("writer"),
Readers = new [] { ClusterInstance.ServerlessV2("reader1", new ServerlessV2ClusterInstanceProps { ScaleWithWriter = true }), ClusterInstance.ServerlessV2("reader2") },
Vpc = vpc
});
When configuring your cluster it is important to take this into consideration and ensure that in the event of a failover there is an instance that is scaled up to take over.
Mixing Serverless v2 and Provisioned instances
You are able to create a cluster that has both provisioned and serverless instances. This blog post has an excellent guide on choosing between serverless and provisioned instances based on use case.
There are a couple of high level differences:
Provisioned writer
With a provisioned writer and serverless v2 readers, some of the serverless readers will need to be configured to scale with the writer so they can act as failover targets. You will need to determine the correct capacity based on the provisioned instance type and it's utilization.
As an example, if the CPU utilization for a db.r6g.4xlarge (128 GB) instance stays at 10% most times, then the minimum ACUs may be set at 6.5 ACUs (10% of 128 GB) and maximum may be set at 64 ACUs (64x2GB=128GB). Keep in mind that the speed at which the serverless instance can scale up is determined by the minimum capacity so if your cluster has spiky workloads you may need to set a higher minimum capacity.
Vpc vpc;
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps { Version = AuroraMysqlEngineVersion.VER_3_01_0 }),
Writer = ClusterInstance.Provisioned("writer", new ProvisionedClusterInstanceProps {
InstanceType = InstanceType.Of(InstanceClass.R6G, InstanceSize.XLARGE4)
}),
ServerlessV2MinCapacity = 6.5,
ServerlessV2MaxCapacity = 64,
Readers = new [] { ClusterInstance.ServerlessV2("reader1", new ServerlessV2ClusterInstanceProps { ScaleWithWriter = true }), ClusterInstance.ServerlessV2("reader2") },
Vpc = vpc
});
In the above example reader1
will scale with the writer based on the writer's
utilization. So if the writer were to go to 50%
utilization then reader1
would scale up to use 32
ACUs. If the read load stayed consistent then
reader2
may remain at 6.5
since it is not configured to scale with the
writer.
If one of your Aurora Serverless v2 DB instances consistently reaches the
limit of its maximum capacity, Aurora indicates this condition by setting the
DB instance to a status of incompatible-parameters
. While the DB instance has
the incompatible-parameters status, some operations are blocked. For example,
you can't upgrade the engine version.
CA certificate
Use the caCertificate
property to specify the CA certificates
to use for a cluster instances:
Vpc vpc;
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps { Version = AuroraMysqlEngineVersion.VER_3_01_0 }),
Writer = ClusterInstance.Provisioned("writer", new ProvisionedClusterInstanceProps {
CaCertificate = CaCertificate.RDS_CA_RSA2048_G1
}),
Readers = new [] { ClusterInstance.ServerlessV2("reader", new ServerlessV2ClusterInstanceProps {
CaCertificate = CaCertificate.Of("custom-ca")
}) },
Vpc = vpc
});
Migrating from instanceProps
Creating instances in a DatabaseCluster
using instanceProps
& instances
is
deprecated. To migrate to the new properties you can provide the
isFromLegacyInstanceProps
property.
For example, in order to migrate from this deprecated config:
Vpc vpc;
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps {
Version = AuroraMysqlEngineVersion.VER_3_03_0
}),
Instances = 2,
InstanceProps = new InstanceProps {
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.SMALL),
VpcSubnets = new SubnetSelection { SubnetType = SubnetType.PUBLIC },
Vpc = vpc
}
});
You would need to migrate to this. The old method of providing instanceProps
and instances
will create the number of instances
that you provide. The
first instance will be the writer and the rest will be the readers. It's
important that the id
that you provide is Instance{NUMBER}
. The writer
should always be Instance1
and the readers will increment from there.
Make sure to run a cdk diff
before deploying to make sure that all changes are
expected. Always test the migration in a non-production environment first.
Vpc vpc;
IDictionary<string, object> instanceProps = new Dictionary<string, object> {
{ "instanceType", InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.SMALL) },
{ "isFromLegacyInstanceProps", true }
};
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps {
Version = AuroraMysqlEngineVersion.VER_3_03_0
}),
VpcSubnets = new SubnetSelection { SubnetType = SubnetType.PUBLIC },
Vpc = vpc,
Writer = ClusterInstance.Provisioned("Instance1", new ProvisionedClusterInstanceProps {
InstanceType = instanceProps.InstanceType,
IsFromLegacyInstanceProps = instanceProps.IsFromLegacyInstanceProps
}),
Readers = new [] { ClusterInstance.Provisioned("Instance2", new ProvisionedClusterInstanceProps {
InstanceType = instanceProps.InstanceType,
IsFromLegacyInstanceProps = instanceProps.IsFromLegacyInstanceProps
}) }
});
Starting an instance database
To set up an instance database, define a DatabaseInstance
. You must
always launch a database in a VPC. Use the vpcSubnets
attribute to control whether
your instances will be launched privately or publicly:
Vpc vpc;
var instance = new DatabaseInstance(this, "Instance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.OracleSe2(new OracleSe2InstanceEngineProps { Version = OracleEngineVersion.VER_19_0_0_0_2020_04_R1 }),
// 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 = new SubnetSelection {
SubnetType = SubnetType.PRIVATE_WITH_EGRESS
}
});
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.
var 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;
var instance = new DatabaseInstance(this, "Instance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.Postgres(new PostgresInstanceEngineProps { Version = PostgresEngineVersion.VER_16_3 }),
// optional, defaults to m5.large
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE2, InstanceSize.SMALL),
Vpc = vpc,
MaxAllocatedStorage = 200
});
To use dual-stack mode, specify NetworkType.DUAL
on the networkType
property:
Vpc vpc;
// VPC and subnets must have IPv6 CIDR blocks
var instance = new DatabaseInstance(this, "Instance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.Postgres(new PostgresInstanceEngineProps { Version = PostgresEngineVersion.VER_16_3 }),
Vpc = vpc,
NetworkType = NetworkType.DUAL,
PubliclyAccessible = false
});
For more information about dual-stack mode, see Working with a DB instance in a VPC.
Use DatabaseInstanceFromSnapshot
and DatabaseInstanceReadReplica
to create an instance from snapshot or
a source database respectively:
Vpc vpc;
DatabaseInstance sourceInstance;
new DatabaseInstanceFromSnapshot(this, "Instance", new DatabaseInstanceFromSnapshotProps {
SnapshotIdentifier = "my-snapshot",
Engine = DatabaseInstanceEngine.Postgres(new PostgresInstanceEngineProps { Version = PostgresEngineVersion.VER_16_3 }),
// optional, defaults to m5.large
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE2, InstanceSize.LARGE),
Vpc = vpc
});
new DatabaseInstanceReadReplica(this, "ReadReplica", new DatabaseInstanceReadReplicaProps {
SourceDatabaseInstance = sourceInstance,
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE2, InstanceSize.LARGE),
Vpc = vpc
});
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
var parameterGroup = new ParameterGroup(this, "ParameterGroup", new ParameterGroupProps {
Engine = DatabaseInstanceEngine.OracleSe2(new OracleSe2InstanceEngineProps { Version = OracleEngineVersion.VER_19_0_0_0_2020_04_R1 }),
Parameters = new Dictionary<string, string> {
{ "open_cursors", "2500" }
}
});
var optionGroup = new OptionGroup(this, "OptionGroup", new OptionGroupProps {
Engine = DatabaseInstanceEngine.OracleSe2(new OracleSe2InstanceEngineProps { Version = OracleEngineVersion.VER_19_0_0_0_2020_04_R1 }),
Configurations = new [] { 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
var instance = new DatabaseInstance(this, "Instance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.OracleSe2(new OracleSe2InstanceEngineProps { Version = OracleEngineVersion.VER_19_0_0_0_2020_04_R1 }),
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 = new [] { "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
});
// 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
var fn = new Function(this, "Function", new FunctionProps {
Code = Code.FromInline("exports.handler = (event) => console.log(event);"),
Handler = "index.handler",
Runtime = Runtime.NODEJS_18_X
});
var availabilityRule = instance.OnEvent("Availability", new OnEventOptions { Target = new LambdaFunction(fn) });
availabilityRule.AddEventPattern(new EventPattern {
Detail = new Dictionary<string, object> {
{ "EventCategories", new [] { "availability" } }
}
});
Add XMLDB and OEM with option group
// Set open cursors with parameter group
var parameterGroup = new ParameterGroup(this, "ParameterGroup", new ParameterGroupProps {
Engine = DatabaseInstanceEngine.OracleSe2(new OracleSe2InstanceEngineProps { Version = OracleEngineVersion.VER_19_0_0_0_2020_04_R1 }),
Parameters = new Dictionary<string, string> {
{ "open_cursors", "2500" }
}
});
var optionGroup = new OptionGroup(this, "OptionGroup", new OptionGroupProps {
Engine = DatabaseInstanceEngine.OracleSe2(new OracleSe2InstanceEngineProps { Version = OracleEngineVersion.VER_19_0_0_0_2020_04_R1 }),
Configurations = new [] { 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
var instance = new DatabaseInstance(this, "Instance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.OracleSe2(new OracleSe2InstanceEngineProps { Version = OracleEngineVersion.VER_19_0_0_0_2020_04_R1 }),
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 = new [] { "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
});
// 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
var fn = new Function(this, "Function", new FunctionProps {
Code = Code.FromInline("exports.handler = (event) => console.log(event);"),
Handler = "index.handler",
Runtime = Runtime.NODEJS_18_X
});
var availabilityRule = instance.OnEvent("Availability", new OnEventOptions { Target = new LambdaFunction(fn) });
availabilityRule.AddEventPattern(new EventPattern {
Detail = new Dictionary<string, object> {
{ "EventCategories", new [] { "availability" } }
}
});
Use the storageType
property to specify the type of storage
to use for the instance:
Vpc vpc;
var iopsInstance = new DatabaseInstance(this, "IopsInstance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.Mysql(new MySqlInstanceEngineProps { Version = MysqlEngineVersion.VER_8_0_30 }),
Vpc = vpc,
StorageType = StorageType.IO1,
Iops = 5000
});
var gp3Instance = new DatabaseInstance(this, "Gp3Instance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.Mysql(new MySqlInstanceEngineProps { Version = MysqlEngineVersion.VER_8_0_30 }),
Vpc = vpc,
AllocatedStorage = 500,
StorageType = StorageType.GP3,
StorageThroughput = 500
});
Use the allocatedStorage
property to specify the amount of storage (in gigabytes) that is initially allocated for the instance
to use for the instance:
Vpc vpc;
// Setting allocatedStorage for DatabaseInstance replica
// Note: If allocatedStorage isn't set here, the replica instance will inherit the allocatedStorage of the source instance
DatabaseInstance sourceInstance;
// Setting allocatedStorage for DatabaseInstance
var iopsInstance = new DatabaseInstance(this, "IopsInstance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.Mysql(new MySqlInstanceEngineProps { Version = MysqlEngineVersion.VER_8_0_30 }),
Vpc = vpc,
StorageType = StorageType.IO1,
Iops = 5000,
AllocatedStorage = 500
});
new DatabaseInstanceReadReplica(this, "ReadReplica", new DatabaseInstanceReadReplicaProps {
SourceDatabaseInstance = sourceInstance,
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE2, InstanceSize.LARGE),
Vpc = vpc,
AllocatedStorage = 500
});
Use the caCertificate
property to specify the CA certificates
to use for the instance:
Vpc vpc;
new DatabaseInstance(this, "Instance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.Mysql(new MySqlInstanceEngineProps { Version = MysqlEngineVersion.VER_8_0_30 }),
Vpc = vpc,
CaCertificate = CaCertificate.RDS_CA_RSA2048_G1
});
You can specify a custom CA certificate with:
Vpc vpc;
new DatabaseInstance(this, "Instance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.Mysql(new MySqlInstanceEngineProps { Version = MysqlEngineVersion.VER_8_0_30 }),
Vpc = vpc,
CaCertificate = CaCertificate.Of("future-rds-ca")
});
Setting Public Accessibility
You can set public accessibility for the DatabaseInstance
or the ClusterInstance
using the publiclyAccessible
property.
If you specify true
, it creates an instance with a publicly resolvable DNS name, which resolves to a public IP address.
If you specify false
, it creates an internal instance with a DNS name that resolves to a private IP address.
The default value will be true
if vpcSubnets
is subnetType: SubnetType.PUBLIC
, false
otherwise. In the case of a
cluster, the default value will be determined on the vpc placement of the DatabaseCluster
otherwise it will be determined
based on the vpc placement of standalone DatabaseInstance
.
Vpc vpc;
// Setting public accessibility for DB instance
// Setting public accessibility for DB instance
new DatabaseInstance(this, "Instance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.Mysql(new MySqlInstanceEngineProps {
Version = MysqlEngineVersion.VER_8_0_19
}),
Vpc = vpc,
VpcSubnets = new SubnetSelection {
SubnetType = SubnetType.PRIVATE_WITH_EGRESS
},
PubliclyAccessible = true
});
// Setting public accessibility for DB cluster instance
// Setting public accessibility for DB cluster instance
new DatabaseCluster(this, "DatabaseCluster", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps {
Version = AuroraMysqlEngineVersion.VER_3_03_0
}),
Writer = ClusterInstance.ServerlessV2("Writer", new ServerlessV2ClusterInstanceProps {
PubliclyAccessible = true
}),
Vpc = vpc,
VpcSubnets = new SubnetSelection {
SubnetType = SubnetType.PRIVATE_WITH_EGRESS
}
});
Instance events
To define Amazon CloudWatch event rules for database instances, use the onEvent
method:
DatabaseInstance instance;
Function fn;
var rule = instance.OnEvent("InstanceEvent", new OnEventOptions { Target = new LambdaFunction(fn) });
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;
var engine = DatabaseInstanceEngine.Postgres(new PostgresInstanceEngineProps { Version = PostgresEngineVersion.VER_16_3 });
new DatabaseInstance(this, "InstanceWithUsername", new DatabaseInstanceProps {
Engine = engine,
Vpc = vpc,
Credentials = Credentials.FromGeneratedSecret("postgres")
});
new DatabaseInstance(this, "InstanceWithUsernameAndPassword", new DatabaseInstanceProps {
Engine = engine,
Vpc = vpc,
Credentials = Credentials.FromPassword("postgres", SecretValue.SsmSecure("/dbPassword", "1"))
});
var mySecret = Secret.FromSecretName(this, "DBSecret", "myDBLoginInfo");
new DatabaseInstance(this, "InstanceWithSecretLogin", new DatabaseInstanceProps {
Engine = engine,
Vpc = vpc,
Credentials = Credentials.FromSecret(mySecret)
});
Secrets generated by fromGeneratedSecret()
can be customized:
Vpc vpc;
var engine = DatabaseInstanceEngine.Postgres(new PostgresInstanceEngineProps { Version = PostgresEngineVersion.VER_16_3 });
var myKey = new Key(this, "MyKey");
new DatabaseInstance(this, "InstanceWithCustomizedSecret", new DatabaseInstanceProps {
Engine = engine,
Vpc = vpc,
Credentials = Credentials.FromGeneratedSecret("postgres", new CredentialsBaseOptions {
SecretName = "my-cool-name",
EncryptionKey = myKey,
ExcludeCharacters = "!&*^#@()",
ReplicaRegions = new [] { new ReplicaRegion { Region = "eu-west-1" }, new ReplicaRegion { Region = "eu-west-2" } }
})
});
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;
var engine = DatabaseInstanceEngine.Postgres(new PostgresInstanceEngineProps { Version = PostgresEngineVersion.VER_16_3 });
var myKey = new Key(this, "MyKey");
new DatabaseInstanceFromSnapshot(this, "InstanceFromSnapshotWithCustomizedSecret", new DatabaseInstanceFromSnapshotProps {
Engine = engine,
Vpc = vpc,
SnapshotIdentifier = "mySnapshot",
Credentials = SnapshotCredentials.FromGeneratedSecret("username", new SnapshotCredentialsFromGeneratedPasswordOptions {
EncryptionKey = myKey,
ExcludeCharacters = "!&*^#@()",
ReplicaRegions = new [] { new ReplicaRegion { Region = "eu-west-1" }, new ReplicaRegion { Region = "eu-west-2" } }
})
});
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;
var writeAddress = cluster.ClusterEndpoint.SocketAddress;
For an instance database:
DatabaseInstance instance;
var address = instance.InstanceEndpoint.SocketAddress;
Rotating credentials
When the master password is generated and stored in AWS Secrets Manager, it can be rotated automatically:
DatabaseInstance instance;
SecurityGroup mySecurityGroup;
instance.AddRotationSingleUser(new RotationSingleUserOptions {
AutomaticallyAfter = Duration.Days(7), // defaults to 30 days
ExcludeCharacters = "!@#$%^&*", // defaults to the set " %+~`#/// here*()|[]{}:;<>?!'/@\"\\"
SecurityGroup = mySecurityGroup
});
var cluster = new DatabaseCluster(stack, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AURORA,
InstanceProps = new InstanceProps {
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.SMALL),
Vpc = vpc
}
});
cluster.AddRotationSingleUser();
var clusterWithCustomRotationOptions = new DatabaseCluster(stack, "CustomRotationOptions", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AURORA,
InstanceProps = new InstanceProps {
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.SMALL),
Vpc = vpc
}
});
clusterWithCustomRotationOptions.AddRotationSingleUser(new RotationSingleUserOptions {
AutomaticallyAfter = Duration.Days(7),
ExcludeCharacters = "!@#$%^&*",
SecurityGroup = securityGroup,
VpcSubnets = new SubnetSelection { SubnetType = SubnetType.PRIVATE_WITH_EGRESS },
Endpoint = endpoint
});
The multi user rotation scheme is also available:
DatabaseInstance instance;
DatabaseSecret myImportedSecret;
instance.AddRotationMultiUser("MyUser", new RotationMultiUserOptions {
Secret = myImportedSecret
});
It's also possible to create user credentials together with the instance/cluster and add rotation:
DatabaseInstance instance;
var myUserSecret = new DatabaseSecret(this, "MyUserSecret", new DatabaseSecretProps {
Username = "myuser",
SecretName = "my-user-secret", // optional, defaults to a CloudFormation-generated name
Dbname = "mydb", //optional, defaults to the main database of the RDS cluster this secret gets attached to
MasterSecret = instance.Secret,
ExcludeCharacters = "{}[]()'\"/\\"
});
var myUserSecretAttached = myUserSecret.Attach(instance); // Adds DB connections information in the secret
instance.AddRotationMultiUser("MyUser", new RotationMultiUserOptions { // 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.
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(new RotationSingleUserOptions {
VpcSubnets = new SubnetSelection { SubnetType = SubnetType.PRIVATE_WITH_EGRESS }, // Place rotation Lambda in private subnets
Endpoint = myEndpoint
});
See also aws-cdk-lib/aws-secretsmanager for credentials rotation of existing clusters/instances.
By default, any stack updates will cause AWS Secrets Manager to rotate a secret immediately. To prevent this behavior and wait until the next scheduled rotation window specified via the automaticallyAfter
property, set the rotateImmediatelyOnUpdate
property to false:
DatabaseInstance instance;
SecurityGroup mySecurityGroup;
instance.AddRotationSingleUser(new RotationSingleUserOptions {
AutomaticallyAfter = Duration.Days(7), // defaults to 30 days
ExcludeCharacters = "!@#$%^&*", // defaults to the set " %+~`#/// here*()|[]{}:;<>?!'/@\"\\"
SecurityGroup = mySecurityGroup, // defaults to an auto-created security group
RotateImmediatelyOnUpdate = false
});
IAM Authentication
You can also authenticate to a database instance using AWS Identity and Access Management (IAM) database authentication; See https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html for more information and a list of supported versions and limitations.
The following example shows enabling IAM authentication for a database instance and granting connection access to an IAM role.
Instance
Vpc vpc;
var instance = new DatabaseInstance(this, "Instance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.Mysql(new MySqlInstanceEngineProps { Version = MysqlEngineVersion.VER_8_0_19 }),
Vpc = vpc,
IamAuthentication = true
});
var role = new Role(this, "DBRole", new RoleProps { AssumedBy = new AccountPrincipal(Account) });
instance.GrantConnect(role);
Proxy
The following example shows granting connection access for RDS Proxy to an IAM role.
Vpc vpc;
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps {
Version = AuroraMysqlEngineVersion.VER_3_03_0
}),
Writer = ClusterInstance.Provisioned("writer"),
Vpc = vpc
});
var proxy = new DatabaseProxy(this, "Proxy", new DatabaseProxyProps {
ProxyTarget = ProxyTarget.FromCluster(cluster),
Secrets = new [] { cluster.Secret },
Vpc = vpc
});
var role = new Role(this, "DBProxyRole", new RoleProps { AssumedBy = new AccountPrincipal(Account) });
proxy.GrantConnect(role, "admin");
Note: In addition to the setup above, a database user will need to be created to support IAM auth. See https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.DBAccounts.html for setup instructions.
To specify the details of authentication used by a proxy to log in as a specific database
user use the clientPasswordAuthType
property:
Vpc vpc;
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps {
Version = AuroraMysqlEngineVersion.VER_3_03_0
}),
Writer = ClusterInstance.Provisioned("writer"),
Vpc = vpc
});
var proxy = new DatabaseProxy(this, "Proxy", new DatabaseProxyProps {
ProxyTarget = ProxyTarget.FromCluster(cluster),
Secrets = new [] { cluster.Secret },
Vpc = vpc,
ClientPasswordAuthType = ClientPasswordAuthType.MYSQL_NATIVE_PASSWORD
});
Cluster
The following example shows granting connection access for an IAM role to an Aurora Cluster.
Vpc vpc;
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps {
Version = AuroraMysqlEngineVersion.VER_3_03_0
}),
Writer = ClusterInstance.Provisioned("writer"),
Vpc = vpc
});
var role = new Role(this, "AppRole", new RoleProps { AssumedBy = new ServicePrincipal("someservice.amazonaws.com") });
cluster.GrantConnect(role, "somedbuser");
Note: In addition to the setup above, a database user will need to be created to support IAM auth. See https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.DBAccounts.html for setup instructions.
Kerberos Authentication
You can also authenticate using Kerberos to a database instance using AWS Managed Microsoft AD for authentication; See https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html for more information and a list of supported versions and limitations.
The following example shows enabling domain support for a database instance and creating an IAM role to access Directory Services.
Vpc vpc;
var role = new Role(this, "RDSDirectoryServicesRole", new RoleProps {
AssumedBy = new CompositePrincipal(
new ServicePrincipal("rds.amazonaws.com"),
new ServicePrincipal("directoryservice.rds.amazonaws.com")),
ManagedPolicies = new [] { ManagedPolicy.FromAwsManagedPolicyName("service-role/AmazonRDSDirectoryServiceAccess") }
});
var instance = new DatabaseInstance(this, "Instance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.Mysql(new MySqlInstanceEngineProps { Version = MysqlEngineVersion.VER_8_0_19 }),
Vpc = vpc,
Domain = "d-????????", // The ID of the domain for the instance to join.
DomainRole = role
});
You can also use the Kerberos authentication for an Aurora database cluster.
Vpc vpc;
var iamRole = new Role(this, "Role", new RoleProps {
AssumedBy = new CompositePrincipal(
new ServicePrincipal("rds.amazonaws.com"),
new ServicePrincipal("directoryservice.rds.amazonaws.com")),
ManagedPolicies = new [] { ManagedPolicy.FromAwsManagedPolicyName("service-role/AmazonRDSDirectoryServiceAccess") }
});
new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps { Version = AuroraMysqlEngineVersion.VER_3_05_1 }),
Writer = ClusterInstance.Provisioned("Instance", new ProvisionedClusterInstanceProps {
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.MEDIUM)
}),
Vpc = vpc,
Domain = "d-????????", // The ID of the domain for the cluster to join.
DomainRole = iamRole
});
Note: In addition to the setup above, you need to make sure that the database instance or cluster has network connectivity to the domain controllers. This includes enabling cross-VPC traffic if in a different VPC and setting up the appropriate security groups/network ACL to allow traffic between the database instance and domain controllers. Once configured, see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html for details on configuring users for each available database engine.
Metrics
Database instances and clusters both expose metrics (cloudwatch.Metric
):
// The number of database connections in use (average over 5 minutes)
DatabaseInstance instance;
// Average CPU utilization over 5 minutes
DatabaseCluster cluster;
var dbConnections = instance.MetricDatabaseConnections();
var cpuUtilization = cluster.MetricCPUUtilization();
// The average amount of time taken per disk I/O operation (average over 1 minute)
var readLatency = instance.Metric("ReadLatency", new MetricOptions { Statistic = "Average", Period = Duration.Seconds(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.
Note: To use s3ImportRole
and s3ExportRole
with Aurora PostgreSQL, you must also enable the S3 import and export features when you create the DatabaseClusterEngine.
You can read more about loading data to (or from) S3 here:
The following snippet sets up a database cluster with different S3 buckets where the data is imported and exported -
using Amazon.CDK.AWS.S3;
Vpc vpc;
var importBucket = new Bucket(this, "importbucket");
var exportBucket = new Bucket(this, "exportbucket");
new DatabaseCluster(this, "dbcluster", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraMysql(new AuroraMysqlClusterEngineProps {
Version = AuroraMysqlEngineVersion.VER_3_03_0
}),
Writer = ClusterInstance.Provisioned("writer"),
Vpc = vpc,
S3ImportBuckets = new [] { importBucket },
S3ExportBuckets = new [] { exportBucket }
});
Creating a Database Proxy
Amazon RDS Proxy sits between your application and your relational database to efficiently manage connections to the database and improve scalability of the application. Learn more about at Amazon RDS Proxy.
RDS Proxy is supported for MySQL, MariaDB, Postgres, and SQL Server.
The following code configures an RDS Proxy for a DatabaseInstance
.
Vpc vpc;
SecurityGroup securityGroup;
Secret[] secrets;
DatabaseInstance dbInstance;
var proxy = dbInstance.AddProxy("proxy", new DatabaseProxyOptions {
BorrowTimeout = 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.
using Amazon.CDK.AWS.Logs;
Role myLogsPublishingRole;
Vpc vpc;
// Exporting logs from a cluster
var cluster = new DatabaseCluster(this, "Database", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.Aurora(new AuroraClusterEngineProps {
Version = AuroraEngineVersion.VER_1_17_9
}),
Writer = ClusterInstance.Provisioned("writer"),
Vpc = vpc,
CloudwatchLogsExports = new [] { "error", "general", "slowquery", "audit" }, // Export all available MySQL-based logs
CloudwatchLogsRetention = RetentionDays.THREE_MONTHS, // Optional - default is to never expire logs
CloudwatchLogsRetentionRole = myLogsPublishingRole
});
// When 'cloudwatchLogsExports' is set, each export value creates its own log group in DB cluster.
// Specify an export value to access its log group.
var errorLogGroup = cluster.CloudwatchLogGroups["error"];
var auditLogGroup = cluster.CloudwatchLogGroups.Audit;
// Exporting logs from an instance
var instance = new DatabaseInstance(this, "Instance", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.Postgres(new PostgresInstanceEngineProps {
Version = PostgresEngineVersion.VER_16_3
}),
Vpc = vpc,
CloudwatchLogsExports = new [] { "postgresql" }, // Export the PostgreSQL logs
CloudwatchLogsRetention = RetentionDays.THREE_MONTHS
});
// When 'cloudwatchLogsExports' is set, each export value creates its own log group in DB instance.
// Specify an export value to access its log group.
var postgresqlLogGroup = instance.CloudwatchLogGroups["postgresql"];
Option Groups
Some DB engines offer additional features that make it easier to manage data and databases, and to provide additional security for your database. Amazon RDS uses option groups to enable and configure these features. An option group can specify features, called options, that are available for a particular Amazon RDS DB instance.
Vpc vpc;
SecurityGroup securityGroup;
new OptionGroup(this, "Options", new OptionGroupProps {
Engine = DatabaseInstanceEngine.OracleSe2(new OracleSe2InstanceEngineProps {
Version = OracleEngineVersion.VER_19
}),
Configurations = new [] { new OptionConfiguration {
Name = "OEM",
Port = 5500,
Vpc = vpc,
SecurityGroups = new [] { securityGroup }
} }
});
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;
var parameterGroup = new ParameterGroup(this, "ParameterGroup", new ParameterGroupProps {
Engine = DatabaseInstanceEngine.SqlServerEe(new SqlServerEeInstanceEngineProps {
Version = SqlServerEngineVersion.VER_11
}),
Name = "my-parameter-group",
Parameters = new Dictionary<string, string> {
{ "locks", "100" }
}
});
new DatabaseInstance(this, "Database", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.SQL_SERVER_EE,
Vpc = vpc,
ParameterGroup = parameterGroup
});
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;
new DatabaseInstance(this, "Database", new DatabaseInstanceProps {
Engine = DatabaseInstanceEngine.SqlServerEe(new SqlServerEeInstanceEngineProps { Version = SqlServerEngineVersion.VER_11 }),
Vpc = vpc,
Parameters = new Dictionary<string, string> {
{ "locks", "100" }
}
});
You cannot specify a parameter map and a parameter group at the same time.
Serverless v1
Amazon Aurora Serverless v1 is an on-demand, auto-scaling configuration for Amazon Aurora. The database will automatically start up, shut down, and scale capacity up or down based on your application's needs. It enables you to run your database in the cloud without managing any database instances.
The following example initializes an Aurora Serverless v1 PostgreSql cluster. Aurora Serverless clusters can specify scaling properties which will be used to automatically scale the database cluster seamlessly based on the workload.
Vpc vpc;
var cluster = new ServerlessCluster(this, "AnotherCluster", new ServerlessClusterProps {
Engine = DatabaseClusterEngine.AURORA_POSTGRESQL,
CopyTagsToSnapshot = true, // whether to save the cluster tags when creating the snapshot. Default is 'true'
ParameterGroup = ParameterGroup.FromParameterGroupName(this, "ParameterGroup", "default.aurora-postgresql11"),
Vpc = vpc,
Scaling = new ServerlessScalingOptions {
AutoPause = Duration.Minutes(10), // default is to pause after 5 minutes of idle time
MinCapacity = AuroraCapacityUnit.ACU_8, // default is 2 Aurora capacity units (ACUs)
MaxCapacity = AuroraCapacityUnit.ACU_32, // default is 16 Aurora capacity units (ACUs)
Timeout = Duration.Seconds(100), // default is 5 minutes
TimeoutAction = TimeoutAction.FORCE_APPLY_CAPACITY_CHANGE
}
});
Note: The rds.ServerlessCluster
class is for Aurora Serverless v1. If you want to use Aurora Serverless v2, use the rds.DatabaseCluster
class.
Aurora Serverless v1 Clusters do not support the following features:
Read more about the limitations of Aurora Serverless v1
Learn more about using Amazon Aurora Serverless v1 by reading the documentation
Use ServerlessClusterFromSnapshot
to create a serverless cluster from a snapshot:
Vpc vpc;
new ServerlessClusterFromSnapshot(this, "Cluster", new ServerlessClusterFromSnapshotProps {
Engine = DatabaseClusterEngine.AURORA_MYSQL,
Vpc = vpc,
SnapshotIdentifier = "mySnapshot"
});
Data API
You can access your Aurora DB cluster using the built-in Data API. The Data API doesn't require a persistent connection to the DB cluster. Instead, it provides a secure HTTP endpoint and integration with AWS SDKs.
The following example shows granting Data API access to a Lamba function.
Vpc vpc;
Function fn;
// Create a serverless V1 cluster
var serverlessV1Cluster = new ServerlessCluster(this, "AnotherCluster", new ServerlessClusterProps {
Engine = DatabaseClusterEngine.AURORA_MYSQL,
Vpc = vpc, // this parameter is optional for serverless Clusters
EnableDataApi = true
});
serverlessV1Cluster.GrantDataApiAccess(fn);
// Create an Aurora cluster
var cluster = new DatabaseCluster(this, "Cluster", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AURORA_MYSQL,
Vpc = vpc,
EnableDataApi = true
});
cluster.GrantDataApiAccess(fn);
Note: To invoke the Data API, the resource will need to read the secret associated with the cluster.
To learn more about using the Data API, see the documentation.
Default VPC
The vpc
parameter is optional.
If not provided, the cluster will be created in the default VPC of the account and region.
As this VPC is not deployed with AWS CDK, you can't configure the vpcSubnets
, subnetGroup
or securityGroups
of the Aurora Serverless Cluster.
If you want to provide one of vpcSubnets
, subnetGroup
or securityGroups
parameter, please provide a vpc
.
Preferred Maintenance Window
When creating an RDS cluster, it is possible to (optionally) specify a preferred maintenance window for the cluster as well as the instances under the cluster. See AWS docs for more information regarding maintenance windows.
The following code snippet shows an example of setting the cluster's maintenance window to 22:15-22:45 (UTC) on Saturdays, but setting the instances' maintenance window to 23:15-23:45 on Sundays
Vpc vpc;
new DatabaseCluster(this, "DatabaseCluster", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AURORA,
InstanceProps = new InstanceProps {
Vpc = vpc,
PreferredMaintenanceWindow = "Sun:23:15-Sun:23:45"
},
PreferredMaintenanceWindow = "Sat:22:15-Sat:22:45"
});
You can also set the preferred maintenance window via reader and writer props:
Vpc vpc;
new DatabaseCluster(this, "DatabaseCluster", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AURORA,
Vpc = vpc,
Writer = ClusterInstance.Provisioned("WriterInstance", new ProvisionedClusterInstanceProps {
PreferredMaintenanceWindow = "Sat:22:15-Sat:22:45"
}),
PreferredMaintenanceWindow = "Sat:22:15-Sat:22:45"
});
Classes
AuroraCapacityUnit | Aurora capacity units (ACUs). |
AuroraClusterEngineProps | Creation properties of the plain Aurora database cluster engine. |
AuroraEngineVersion | The versions for the Aurora cluster engine (those returned by |
AuroraMysqlClusterEngineProps | Creation properties of the Aurora MySQL database cluster engine. |
AuroraMysqlEngineVersion | The versions for the Aurora MySQL cluster engine (those returned by |
AuroraPostgresClusterEngineProps | Creation properties of the Aurora PostgreSQL database cluster engine. |
AuroraPostgresEngineFeatures | Features supported by this version of the Aurora Postgres cluster engine. |
AuroraPostgresEngineVersion | The versions for the Aurora PostgreSQL cluster engine (those returned by |
BackupProps | Backup configuration for RDS databases. |
CaCertificate | The CA certificate used for a DB instance. |
CfnCustomDBEngineVersion | Creates a custom DB engine version (CEV). |
CfnCustomDBEngineVersionProps | Properties for defining a |
CfnDBCluster | The |
CfnDBCluster.DBClusterRoleProperty | Describes an AWS Identity and Access Management (IAM) role that is associated with a DB cluster. |
CfnDBCluster.EndpointProperty | The |
CfnDBCluster.MasterUserSecretProperty | The |
CfnDBCluster.ReadEndpointProperty | The |
CfnDBCluster.ScalingConfigurationProperty | The |
CfnDBCluster.ServerlessV2ScalingConfigurationProperty | The |
CfnDBClusterParameterGroup | The |
CfnDBClusterParameterGroupProps | Properties for defining a |
CfnDBClusterProps | Properties for defining a |
CfnDBInstance | The |
CfnDBInstance.CertificateDetailsProperty | The details of the DB instance’s server certificate. |
CfnDBInstance.DBInstanceRoleProperty | Information about an AWS Identity and Access Management (IAM) role that is associated with a DB instance. |
CfnDBInstance.EndpointProperty | This data type represents the information you need to connect to an Amazon RDS DB instance. |
CfnDBInstance.MasterUserSecretProperty | The |
CfnDBInstance.ProcessorFeatureProperty | The |
CfnDBInstanceProps | Properties for defining a |
CfnDBParameterGroup | The |
CfnDBParameterGroupProps | Properties for defining a |
CfnDBProxy | The |
CfnDBProxy.AuthFormatProperty | Specifies the details of authentication used by a proxy to log in as a specific database user. |
CfnDBProxy.TagFormatProperty | Metadata assigned to an Amazon RDS resource consisting of a key-value pair. |
CfnDBProxyEndpoint | The |
CfnDBProxyEndpoint.TagFormatProperty | Metadata assigned to an Amazon RDS resource consisting of a key-value pair. |
CfnDBProxyEndpointProps | Properties for defining a |
CfnDBProxyProps | Properties for defining a |
CfnDBProxyTargetGroup | The |
CfnDBProxyTargetGroup.ConnectionPoolConfigurationInfoFormatProperty | Specifies the settings that control the size and behavior of the connection pool associated with a |
CfnDBProxyTargetGroupProps | Properties for defining a |
CfnDBSecurityGroup | The |
CfnDBSecurityGroup.IngressProperty | The |
CfnDBSecurityGroupIngress | The |
CfnDBSecurityGroupIngressProps | Properties for defining a |
CfnDBSecurityGroupProps | Properties for defining a |
CfnDBSubnetGroup | The |
CfnDBSubnetGroupProps | Properties for defining a |
CfnEventSubscription | The |
CfnEventSubscriptionProps | Properties for defining a |
CfnGlobalCluster | The |
CfnGlobalClusterProps | Properties for defining a |
CfnIntegration | A zero-ETL integration with Amazon Redshift. |
CfnIntegrationProps | Properties for defining a |
CfnOptionGroup | The |
CfnOptionGroup.OptionConfigurationProperty | The |
CfnOptionGroup.OptionSettingProperty | The |
CfnOptionGroupProps | Properties for defining a |
ClientPasswordAuthType | Client password authentication type used by a proxy to log in as a specific database user. |
ClusterEngineBindOptions | The extra options passed to the |
ClusterEngineConfig | The type returned from the |
ClusterEngineFeatures | Represents Database Engine features. |
ClusterInstance | Create an RDS Aurora Cluster Instance. |
ClusterInstanceBindOptions | Options for binding the instance to the cluster. |
ClusterInstanceOptions | Common options for creating a cluster instance. |
ClusterInstanceProps | Common options for creating cluster instances (both serverless and provisioned). |
ClusterInstanceType | The type of Aurora Cluster Instance. |
CommonRotationUserOptions | Properties common to single-user and multi-user rotation options. |
Credentials | Username and password combination. |
CredentialsBaseOptions | Base options for creating Credentials. |
CredentialsFromUsernameOptions | Options for creating Credentials from a username. |
DatabaseCluster | Create a clustered database with a given number of instances. |
DatabaseClusterAttributes | Properties that describe an existing cluster instance. |
DatabaseClusterBase | A new or imported clustered database. |
DatabaseClusterEngine | A database cluster engine. |
DatabaseClusterFromSnapshot | A database cluster restored from a snapshot. |
DatabaseClusterFromSnapshotProps | Properties for |
DatabaseClusterProps | Properties for a new database cluster. |
DatabaseInstance | A database instance. |
DatabaseInstanceAttributes | Properties that describe an existing instance. |
DatabaseInstanceBase | A new or imported database instance. |
DatabaseInstanceEngine | A database instance engine. |
DatabaseInstanceFromSnapshot | A database instance restored from a snapshot. |
DatabaseInstanceFromSnapshotProps | Construction properties for a DatabaseInstanceFromSnapshot. |
DatabaseInstanceNewProps | Construction properties for a DatabaseInstanceNew. |
DatabaseInstanceProps | Construction properties for a DatabaseInstance. |
DatabaseInstanceReadReplica | A read replica database instance. |
DatabaseInstanceReadReplicaProps | Construction properties for a DatabaseInstanceReadReplica. |
DatabaseInstanceSourceProps | Construction properties for a DatabaseInstanceSource. |
DatabaseProxy | RDS Database Proxy. |
DatabaseProxyAttributes | Properties that describe an existing DB Proxy. |
DatabaseProxyOptions | Options for a new DatabaseProxy. |
DatabaseProxyProps | Construction properties for a DatabaseProxy. |
DatabaseSecret | A database secret. |
DatabaseSecretProps | Construction properties for a DatabaseSecret. |
DBClusterStorageType | The storage type to be associated with the DB cluster. |
Endpoint | Connection endpoint of a database cluster or instance. |
EngineVersion | A version of an engine - for either a cluster, or instance. |
InstanceEngineBindOptions | The options passed to |
InstanceEngineConfig | The type returned from the |
InstanceEngineFeatures | Represents Database Engine features. |
InstanceProps | Instance properties for database instances. |
InstanceType | |
InstanceUpdateBehaviour | The orchestration of updates of multiple instances. |
LicenseModel | The license model. |
MariaDbEngineVersion | The versions for the MariaDB instance engines (those returned by |
MariaDbInstanceEngineProps | Properties for MariaDB instance engines. |
MysqlEngineVersion | The versions for the MySQL instance engines (those returned by |
MySqlInstanceEngineProps | Properties for MySQL instance engines. |
NetworkType | The network type of the DB instance. |
OptionConfiguration | Configuration properties for an option. |
OptionGroup | An option group. |
OptionGroupProps | Construction properties for an OptionGroup. |
OracleEeCdbInstanceEngineProps | Properties for Oracle Enterprise Edition (CDB) instance engines. |
OracleEeInstanceEngineProps | Properties for Oracle Enterprise Edition instance engines. |
OracleEngineVersion | The versions for the Oracle instance engines. |
OracleSe2CdbInstanceEngineProps | Properties for Oracle Standard Edition 2 (CDB) instance engines. |
OracleSe2InstanceEngineProps | Properties for Oracle Standard Edition 2 instance engines. |
ParameterGroup | A parameter group. |
ParameterGroupClusterBindOptions | Options for |
ParameterGroupClusterConfig | The type returned from |
ParameterGroupInstanceBindOptions | Options for |
ParameterGroupInstanceConfig | The type returned from |
ParameterGroupProps | Properties for a parameter group. |
PerformanceInsightRetention | The retention period for Performance Insight data, in days. |
PostgresEngineFeatures | Features supported by the Postgres database engine. |
PostgresEngineVersion | The versions for the PostgreSQL instance engines (those returned by |
PostgresInstanceEngineProps | Properties for PostgreSQL instance engines. |
ProcessorFeatures | The processor features. |
ProvisionedClusterInstanceProps | Options for creating a provisioned instance. |
ProxyTarget | Proxy target: Instance or Cluster. |
ProxyTargetConfig | The result of binding a |
RotationMultiUserOptions | Options to add the multi user rotation. |
RotationSingleUserOptions | Options to add the multi user rotation. |
ServerlessCluster | Create an Aurora Serverless v1 Cluster. |
ServerlessClusterAttributes | Properties that describe an existing cluster instance. |
ServerlessClusterFromSnapshot | A Aurora Serverless v1 Cluster restored from a snapshot. |
ServerlessClusterFromSnapshotProps | Properties for |
ServerlessClusterProps | Properties for a new Aurora Serverless v1 Cluster. |
ServerlessScalingOptions | Options for configuring scaling on an Aurora Serverless v1 Cluster. |
ServerlessV2ClusterInstanceProps | Options for creating a serverless v2 instance. |
SessionPinningFilter | SessionPinningFilter. |
SnapshotCredentials | Credentials to update the password for a |
SnapshotCredentialsFromGeneratedPasswordOptions | Options used in the |
SqlServerEeInstanceEngineProps | Properties for SQL Server Enterprise Edition instance engines. |
SqlServerEngineVersion | The versions for the SQL Server instance engines (those returned by |
SqlServerExInstanceEngineProps | Properties for SQL Server Express Edition instance engines. |
SqlServerSeInstanceEngineProps | Properties for SQL Server Standard Edition instance engines. |
SqlServerWebInstanceEngineProps | Properties for SQL Server Web Edition instance engines. |
StorageType | The type of storage. |
SubnetGroup | Class for creating a RDS DB subnet group. |
SubnetGroupProps | Properties for creating a SubnetGroup. |
TimeoutAction | TimeoutAction defines the action to take when a timeout occurs if a scaling point is not found. |
Interfaces
CfnDBCluster.IDBClusterRoleProperty | Describes an AWS Identity and Access Management (IAM) role that is associated with a DB cluster. |
CfnDBCluster.IEndpointProperty | The |
CfnDBCluster.IMasterUserSecretProperty | The |
CfnDBCluster.IReadEndpointProperty | The |
CfnDBCluster.IScalingConfigurationProperty | The |
CfnDBCluster.IServerlessV2ScalingConfigurationProperty | The |
CfnDBInstance.ICertificateDetailsProperty | The details of the DB instance’s server certificate. |
CfnDBInstance.IDBInstanceRoleProperty | Information about an AWS Identity and Access Management (IAM) role that is associated with a DB instance. |
CfnDBInstance.IEndpointProperty | This data type represents the information you need to connect to an Amazon RDS DB instance. |
CfnDBInstance.IMasterUserSecretProperty | The |
CfnDBInstance.IProcessorFeatureProperty | The |
CfnDBProxy.IAuthFormatProperty | Specifies the details of authentication used by a proxy to log in as a specific database user. |
CfnDBProxy.ITagFormatProperty | Metadata assigned to an Amazon RDS resource consisting of a key-value pair. |
CfnDBProxyEndpoint.ITagFormatProperty | Metadata assigned to an Amazon RDS resource consisting of a key-value pair. |
CfnDBProxyTargetGroup.IConnectionPoolConfigurationInfoFormatProperty | Specifies the settings that control the size and behavior of the connection pool associated with a |
CfnDBSecurityGroup.IIngressProperty | The |
CfnOptionGroup.IOptionConfigurationProperty | The |
CfnOptionGroup.IOptionSettingProperty | The |
IAuroraClusterEngineProps | Creation properties of the plain Aurora database cluster engine. |
IAuroraClusterInstance | An Aurora Cluster Instance. |
IAuroraMysqlClusterEngineProps | Creation properties of the Aurora MySQL database cluster engine. |
IAuroraPostgresClusterEngineProps | Creation properties of the Aurora PostgreSQL database cluster engine. |
IAuroraPostgresEngineFeatures | Features supported by this version of the Aurora Postgres cluster engine. |
IBackupProps | Backup configuration for RDS databases. |
ICfnCustomDBEngineVersionProps | Properties for defining a |
ICfnDBClusterParameterGroupProps | Properties for defining a |
ICfnDBClusterProps | Properties for defining a |
ICfnDBInstanceProps | Properties for defining a |
ICfnDBParameterGroupProps | Properties for defining a |
ICfnDBProxyEndpointProps | Properties for defining a |
ICfnDBProxyProps | Properties for defining a |
ICfnDBProxyTargetGroupProps | Properties for defining a |
ICfnDBSecurityGroupIngressProps | Properties for defining a |
ICfnDBSecurityGroupProps | Properties for defining a |
ICfnDBSubnetGroupProps | Properties for defining a |
ICfnEventSubscriptionProps | Properties for defining a |
ICfnGlobalClusterProps | Properties for defining a |
ICfnIntegrationProps | Properties for defining a |
ICfnOptionGroupProps | Properties for defining a |
IClusterEngine | The interface representing a database cluster (as opposed to instance) engine. |
IClusterEngineBindOptions | The extra options passed to the |
IClusterEngineConfig | The type returned from the |
IClusterEngineFeatures | Represents Database Engine features. |
IClusterInstance | Represents an Aurora cluster instance This can be either a provisioned instance or a serverless v2 instance. |
IClusterInstanceBindOptions | Options for binding the instance to the cluster. |
IClusterInstanceOptions | Common options for creating a cluster instance. |
IClusterInstanceProps | Common options for creating cluster instances (both serverless and provisioned). |
ICommonRotationUserOptions | Properties common to single-user and multi-user rotation options. |
ICredentialsBaseOptions | Base options for creating Credentials. |
ICredentialsFromUsernameOptions | Options for creating Credentials from a username. |
IDatabaseCluster | Create a clustered database with a given number of instances. |
IDatabaseClusterAttributes | Properties that describe an existing cluster instance. |
IDatabaseClusterFromSnapshotProps | Properties for |
IDatabaseClusterProps | Properties for a new database cluster. |
IDatabaseInstance | A database instance. |
IDatabaseInstanceAttributes | Properties that describe an existing instance. |
IDatabaseInstanceFromSnapshotProps | Construction properties for a DatabaseInstanceFromSnapshot. |
IDatabaseInstanceNewProps | Construction properties for a DatabaseInstanceNew. |
IDatabaseInstanceProps | Construction properties for a DatabaseInstance. |
IDatabaseInstanceReadReplicaProps | Construction properties for a DatabaseInstanceReadReplica. |
IDatabaseInstanceSourceProps | Construction properties for a DatabaseInstanceSource. |
IDatabaseProxy | DB Proxy. |
IDatabaseProxyAttributes | Properties that describe an existing DB Proxy. |
IDatabaseProxyOptions | Options for a new DatabaseProxy. |
IDatabaseProxyProps | Construction properties for a DatabaseProxy. |
IDatabaseSecretProps | Construction properties for a DatabaseSecret. |
IEngine | A common interface for database engines. |
IEngineVersion | A version of an engine - for either a cluster, or instance. |
IInstanceEngine | Interface representing a database instance (as opposed to cluster) engine. |
IInstanceEngineBindOptions | The options passed to |
IInstanceEngineConfig | The type returned from the |
IInstanceEngineFeatures | Represents Database Engine features. |
IInstanceProps | Instance properties for database instances. |
IMariaDbInstanceEngineProps | Properties for MariaDB instance engines. |
IMySqlInstanceEngineProps | Properties for MySQL instance engines. |
IOptionConfiguration | Configuration properties for an option. |
IOptionGroup | An option group. |
IOptionGroupProps | Construction properties for an OptionGroup. |
IOracleEeCdbInstanceEngineProps | Properties for Oracle Enterprise Edition (CDB) instance engines. |
IOracleEeInstanceEngineProps | Properties for Oracle Enterprise Edition instance engines. |
IOracleSe2CdbInstanceEngineProps | Properties for Oracle Standard Edition 2 (CDB) instance engines. |
IOracleSe2InstanceEngineProps | Properties for Oracle Standard Edition 2 instance engines. |
IParameterGroup | A parameter group. |
IParameterGroupClusterBindOptions | Options for |
IParameterGroupClusterConfig | The type returned from |
IParameterGroupInstanceBindOptions | Options for |
IParameterGroupInstanceConfig | The type returned from |
IParameterGroupProps | Properties for a parameter group. |
IPostgresEngineFeatures | Features supported by the Postgres database engine. |
IPostgresInstanceEngineProps | Properties for PostgreSQL instance engines. |
IProcessorFeatures | The processor features. |
IProvisionedClusterInstanceProps | Options for creating a provisioned instance. |
IProxyTargetConfig | The result of binding a |
IRotationMultiUserOptions | Options to add the multi user rotation. |
IRotationSingleUserOptions | Options to add the multi user rotation. |
IServerlessCluster | Interface representing a serverless database cluster. |
IServerlessClusterAttributes | Properties that describe an existing cluster instance. |
IServerlessClusterFromSnapshotProps | Properties for |
IServerlessClusterProps | Properties for a new Aurora Serverless v1 Cluster. |
IServerlessScalingOptions | Options for configuring scaling on an Aurora Serverless v1 Cluster. |
IServerlessV2ClusterInstanceProps | Options for creating a serverless v2 instance. |
ISnapshotCredentialsFromGeneratedPasswordOptions | Options used in the |
ISqlServerEeInstanceEngineProps | Properties for SQL Server Enterprise Edition instance engines. |
ISqlServerExInstanceEngineProps | Properties for SQL Server Express Edition instance engines. |
ISqlServerSeInstanceEngineProps | Properties for SQL Server Standard Edition instance engines. |
ISqlServerWebInstanceEngineProps | Properties for SQL Server Web Edition instance engines. |
ISubnetGroup | Interface for a subnet group. |
ISubnetGroupProps | Properties for creating a SubnetGroup. |