All classes with the
Cfn
prefix in this module (CFN Resources) are always stable and safe to use.
The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.
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:
const cluster = new DatabaseCluster(this, 'Database', {
engine: DatabaseClusterEngine.AURORA,
masterUser: {
username: 'clusteradmin'
},
instanceProps: {
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.SMALL),
vpcSubnets: {
subnetType: ec2.SubnetType.PRIVATE,
},
vpc
}
});
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 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:
const instance = new DatabaseInstance(stack, 'Instance', {
engine: rds.DatabaseInstanceEngine.ORACLE_SE1,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.SMALL),
masterUsername: 'syscdk',
vpc
});
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:
const instance = new DatabaseInstance(stack, 'Instance', {
engine: rds.DatabaseInstanceEngine.ORACLE_SE1,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.SMALL),
masterUsername: 'syscdk',
vpc,
maxAllocatedStorage: 200
});
Use DatabaseInstanceFromSnapshot
and DatabaseInstanceReadReplica
to create an instance from snapshot or
a source database respectively:
new DatabaseInstanceFromSnapshot(stack, 'Instance', {
snapshotIdentifier: 'my-snapshot',
engine: rds.DatabaseInstanceEngine.POSTGRES,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.LARGE),
vpc
});
new DatabaseInstanceReadReplica(stack, 'ReadReplica', {
sourceDatabaseInstance: sourceInstance,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.LARGE),
vpc
});
Creating a "production" Oracle database instance with option and parameter groups:
example of setting up a production oracle instance
To define Amazon CloudWatch event rules for database instances, use the onEvent
method:
const rule = instance.onEvent('InstanceEvent', { target: new targets.LambdaFunction(fn) });
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:
cluster.connections.allowFromAnyIpv4('Open to the world');
The endpoints to access your database cluster will be available as the .clusterEndpoint
and .readerEndpoint
attributes:
const writeAddress = cluster.clusterEndpoint.socketAddress; // "HOSTNAME:PORT"
For an instance database:
const address = instance.instanceEndpoint.socketAddress; // "HOSTNAME:PORT"
When the master password is generated and stored in AWS Secrets Manager, it can be rotated automatically:
instance.addRotationSingleUser(); // Will rotate automatically after 30 days
example of setting up master password rotation for a cluster
The multi user rotation scheme is also available:
instance.addRotationMultiUser('MyUser', {
secret: myImportedSecret // This secret must have the `masterarn` key
});
It's also possible to create user credentials together with the instance/cluster and add rotation:
const myUserSecret = new rds.DatabaseSecret(this, 'MyUserSecret', {
username: 'myuser'
masterSecret: instance.secret
});
const myUserSecretAttached = myUserSecret.attach(instance); // Adds DB connections information in the secret
instance.addRotationMultiUser('MyUser', { // Add rotation using the multi user scheme
secret: myUserSecretAttached
});
Note: This user must be created manually in the database using the master credentials. The rotation will start as soon as this user exists.
See also @aws-cdk/aws-secretsmanager for credentials rotation of existing clusters/instances.
Database instances expose metrics (cloudwatch.Metric
):
// The number of database connections in use (average over 5 minutes)
const dbConnections = instance.metricDatabaseConnections();
// The average amount of time taken per disk I/O operation (average over 1 minute)
const readLatency = instance.metric('ReadLatency', { statistic: 'Average', periodSec: 60 });
Data in S3 buckets can be imported to and exported from Aurora databases 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.
For Aurora MySQL, read more about loading data from S3 and saving data into S3.
For Aurora PostgreSQL, read more about loading data from S3 and saving data into S3.
The following snippet sets up a database cluster with different S3 buckets where the data is imported and exported -
const importBucket = new s3.Bucket(this, 'importbucket');
const exportBucket = new s3.Bucket(this, 'exportbucket');
new DatabaseCluster(this, 'dbcluster', {
// ...
s3ImportBuckets: [ importBucket ],
s3ExportBuckets: [ exportBucket ]
});
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
.
import * as cdk from '@aws-cdk/core';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as rds from '@aws-cdk/aws-rds';
import * as secrets from '@aws-cdk/aws-secretsmanager';
const vpc: ec2.IVpc = ...;
const securityGroup: ec2.ISecurityGroup = ...;
const secret: secrets.ISecret = ...;
const dbInstance: rds.IDatabaseInstance = ...;
const proxy = dbInstance.addProxy('proxy', {
connectionBorrowTimeout: cdk.Duration.seconds(30),
maxConnectionsPercent: 50,
secret,
vpc,
});