Package: aws-cdk.aws-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 theMigrating to AWS CDK v2guide.importaws_cdk.aws_rdsasrdsStarting a clustered databaseTo set up a clustered database (like Aurora), define aDatabaseCluster. You must
always launch a database in a VPC. Use thevpcSubnetsattribute to control whether
your instances will be launched privately or publicly:# vpc: ec2.Vpccluster=rds.DatabaseCluster(self,"Database",engine=rds.DatabaseClusterEngine.aurora_mysql(version=rds.AuroraMysqlEngineVersion.VER_2_08_1),credentials=rds.Credentials.from_generated_secret("clusteradmin"),# Optional - will default to 'admin' username and generated passwordinstance_props=rds.InstanceProps(# optional , defaults to t3.mediuminstance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2,ec2.InstanceSize.SMALL),vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT),vpc=vpc))If there isn't a constant for the exact version you want to use,
all of theVersionclasses have a staticofmethod that can be used to create an arbitrary version.custom_engine_version=rds.AuroraMysqlEngineVersion.of("5.7.mysql_aurora.2.08.1")By default, the master password will be generated and stored in AWS Secrets Manager with auto-generated description.Your cluster will be empty by default. To add a default database upon construction, specify thedefaultDatabaseNameattribute.UseDatabaseClusterFromSnapshotto create a cluster from a snapshot:# vpc: ec2.Vpcrds.DatabaseClusterFromSnapshot(self,"Database",engine=rds.DatabaseClusterEngine.aurora(version=rds.AuroraEngineVersion.VER_1_22_2),instance_props=rds.InstanceProps(vpc=vpc),snapshot_identifier="mySnapshot")Starting an instance databaseTo set up a instance database, define aDatabaseInstance. You must
always launch a database in a VPC. Use thevpcSubnetsattribute to control whether
your instances will be launched privately or publicly:# vpc: ec2.Vpcinstance=rds.DatabaseInstance(self,"Instance",engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),# optional, defaults to m5.largeinstance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3,ec2.InstanceSize.SMALL),credentials=rds.Credentials.from_generated_secret("syscdk"),# Optional - will default to 'admin' username and generated passwordvpc=vpc,vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT))If there isn't a constant for the exact engine version you want to use,
all of theVersionclasses have a staticofmethod that can be used to create an arbitrary version.custom_engine_version=rds.OracleEngineVersion.of("19.0.0.0.ru-2020-04.rur-2020-04.r1","19")By default, the master password will be generated and stored in AWS Secrets Manager.To use the storage auto scaling option of RDS you can specify the maximum allocated storage.
This is the upper limit to which RDS can automatically scale the storage. More info can be foundhereExample for max storage configuration:# vpc: ec2.Vpcinstance=rds.DatabaseInstance(self,"Instance",engine=rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3),# optional, defaults to m5.largeinstance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2,ec2.InstanceSize.SMALL),vpc=vpc,max_allocated_storage=200)UseDatabaseInstanceFromSnapshotandDatabaseInstanceReadReplicato create an instance from snapshot or
a source database respectively:# vpc: ec2.Vpc# source_instance: rds.DatabaseInstancerds.DatabaseInstanceFromSnapshot(self,"Instance",snapshot_identifier="my-snapshot",engine=rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3),# optional, defaults to m5.largeinstance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2,ec2.InstanceSize.LARGE),vpc=vpc)rds.DatabaseInstanceReadReplica(self,"ReadReplica",source_database_instance=source_instance,instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2,ec2.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 (usingbackupRetention)
if also enabled on the source instance.Creating a "production" Oracle database instance with option and parameter groups:# Set open cursors with parameter groupparameter_group=rds.ParameterGroup(self,"ParameterGroup",engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),parameters={"open_cursors":"2500"})option_group=rds.OptionGroup(self,"OptionGroup",engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),configurations=[rds.OptionConfiguration(name="LOCATOR"),rds.OptionConfiguration(name="OEM",port=1158,vpc=vpc)])# Allow connections to OEMoption_group.option_connections.OEM.connections.allow_default_port_from_any_ipv4()# Database instance with production valuesinstance=rds.DatabaseInstance(self,"Instance",engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),license_model=rds.LicenseModel.BRING_YOUR_OWN_LICENSE,instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3,ec2.InstanceSize.MEDIUM),multi_az=True,storage_type=rds.StorageType.IO1,credentials=rds.Credentials.from_username("syscdk"),vpc=vpc,database_name="ORCL",storage_encrypted=True,backup_retention=cdk.Duration.days(7),monitoring_interval=cdk.Duration.seconds(60),enable_performance_insights=True,cloudwatch_logs_exports=["trace","audit","alert","listener"],cloudwatch_logs_retention=logs.RetentionDays.ONE_MONTH,auto_minor_version_upgrade=True,# required to be true if LOCATOR is used in the option groupoption_group=option_group,parameter_group=parameter_group,removal_policy=RemovalPolicy.DESTROY)# Allow connections on default port from any IPV4instance.connections.allow_default_port_from_any_ipv4()# Rotate the master user password every 30 daysinstance.add_rotation_single_user()# Add alarm for high CPUcloudwatch.Alarm(self,"HighCPU",metric=instance.metric_cPUUtilization(),threshold=90,evaluation_periods=1)# Trigger Lambda function on instance availability eventsfn=lambda_.Function(self,"Function",code=lambda_.Code.from_inline("exports.handler = (event) => console.log(event);"),handler="index.handler",runtime=lambda_.Runtime.NODEJS_14_X)availability_rule=instance.on_event("Availability",target=targets.LambdaFunction(fn))availability_rule.add_event_pattern(detail={"EventCategories":["availability"]})Add XMLDB and OEM with option group# Set open cursors with parameter groupparameter_group=rds.ParameterGroup(self,"ParameterGroup",engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),parameters={"open_cursors":"2500"})option_group=rds.OptionGroup(self,"OptionGroup",engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),configurations=[rds.OptionConfiguration(name="LOCATOR"),rds.OptionConfiguration(name="OEM",port=1158,vpc=vpc)])# Allow connections to OEMoption_group.option_connections.OEM.connections.allow_default_port_from_any_ipv4()# Database instance with production valuesinstance=rds.DatabaseInstance(self,"Instance",engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19_0_0_0_2020_04_R1),license_model=rds.LicenseModel.BRING_YOUR_OWN_LICENSE,instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3,ec2.InstanceSize.MEDIUM),multi_az=True,storage_type=rds.StorageType.IO1,credentials=rds.Credentials.from_username("syscdk"),vpc=vpc,database_name="ORCL",storage_encrypted=True,backup_retention=cdk.Duration.days(7),monitoring_interval=cdk.Duration.seconds(60),enable_performance_insights=True,cloudwatch_logs_exports=["trace","audit","alert","listener"],cloudwatch_logs_retention=logs.RetentionDays.ONE_MONTH,auto_minor_version_upgrade=True,# required to be true if LOCATOR is used in the option groupoption_group=option_group,parameter_group=parameter_group,removal_policy=RemovalPolicy.DESTROY)# Allow connections on default port from any IPV4instance.connections.allow_default_port_from_any_ipv4()# Rotate the master user password every 30 daysinstance.add_rotation_single_user()# Add alarm for high CPUcloudwatch.Alarm(self,"HighCPU",metric=instance.metric_cPUUtilization(),threshold=90,evaluation_periods=1)# Trigger Lambda function on instance availability eventsfn=lambda_.Function(self,"Function",code=lambda_.Code.from_inline("exports.handler = (event) => console.log(event);"),handler="index.handler",runtime=lambda_.Runtime.NODEJS_14_X)availability_rule=instance.on_event("Availability",target=targets.LambdaFunction(fn))availability_rule.add_event_pattern(detail={"EventCategories":["availability"]})Setting Public AccessibilityYou can set public accessibility for the database instance or cluster using thepubliclyAccessibleproperty.
If you specifytrue, it creates an instance with a publicly resolvable DNS name, which resolves to a public IP address.
If you specifyfalse, it creates an internal instance with a DNS name that resolves to a private IP address.
The default value depends onvpcSubnets.
It will betrueifvpcSubnetsissubnetType: SubnetType.PUBLIC,falseotherwise.# vpc: ec2.Vpc# Setting public accessibility for DB instancerds.DatabaseInstance(self,"Instance",engine=rds.DatabaseInstanceEngine.mysql(version=rds.MysqlEngineVersion.VER_8_0_19),vpc=vpc,vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT),publicly_accessible=True)# Setting public accessibility for DB clusterrds.DatabaseCluster(self,"DatabaseCluster",engine=rds.DatabaseClusterEngine.AURORA,instance_props=rds.InstanceProps(vpc=vpc,vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT),publicly_accessible=True))Instance eventsTo define Amazon CloudWatch event rules for database instances, use theonEventmethod:# instance: rds.DatabaseInstance# fn: lambda.Functionrule=instance.on_event("InstanceEvent",target=targets.LambdaFunction(fn))Login credentialsBy default, database instances and clusters (with the exception ofDatabaseInstanceFromSnapshotandServerlessClusterFromSnapshot) will haveadminuser 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 aDatabaseInstance, but the same usage is applicable toDatabaseCluster.# vpc: ec2.Vpcengine=rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3)rds.DatabaseInstance(self,"InstanceWithUsername",engine=engine,vpc=vpc,credentials=rds.Credentials.from_generated_secret("postgres"))rds.DatabaseInstance(self,"InstanceWithUsernameAndPassword",engine=engine,vpc=vpc,credentials=rds.Credentials.from_password("postgres",SecretValue.ssm_secure("/dbPassword","1")))my_secret=secretsmanager.Secret.from_secret_name(self,"DBSecret","myDBLoginInfo")rds.DatabaseInstance(self,"InstanceWithSecretLogin",engine=engine,vpc=vpc,credentials=rds.Credentials.from_secret(my_secret))Secrets generated byfromGeneratedSecret()can be customized:# vpc: ec2.Vpcengine=rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3)my_key=kms.Key(self,"MyKey")rds.DatabaseInstance(self,"InstanceWithCustomizedSecret",engine=engine,vpc=vpc,credentials=rds.Credentials.from_generated_secret("postgres",secret_name="my-cool-name",encryption_key=my_key,exclude_characters="!&*^#@()",replica_regions=[secretsmanager.ReplicaRegion(region="eu-west-1"),secretsmanager.ReplicaRegion(region="eu-west-2")]))Snapshot credentialsAs noted above, Databases created withDatabaseInstanceFromSnapshotorServerlessClusterFromSnapshotwill 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 withfromGeneratedSecret()orfromGeneratedPassword().# vpc: ec2.Vpcengine=rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3)my_key=kms.Key(self,"MyKey")rds.DatabaseInstanceFromSnapshot(self,"InstanceFromSnapshotWithCustomizedSecret",engine=engine,vpc=vpc,snapshot_identifier="mySnapshot",credentials=rds.SnapshotCredentials.from_generated_secret("username",encryption_key=my_key,exclude_characters="!&*^#@()",replica_regions=[secretsmanager.ReplicaRegion(region="eu-west-1"),secretsmanager.ReplicaRegion(region="eu-west-2")]))ConnectingTo control who can access the cluster or instance, use the.connectionsattribute. RDS databases have
a default port, so you don't need to specify the port:# cluster: rds.DatabaseClustercluster.connections.allow_from_any_ipv4(ec2.Port.all_traffic(),"Open to the world")The endpoints to access your database cluster will be available as the.clusterEndpointand.readerEndpointattributes:# cluster: rds.DatabaseClusterwrite_address=cluster.cluster_endpoint.socket_addressFor an instance database:# instance: rds.DatabaseInstanceaddress=instance.instance_endpoint.socket_addressRotating credentialsWhen the master password is generated and stored in AWS Secrets Manager, it can be rotated automatically:importaws_cdk.coreascdk# instance: rds.DatabaseInstanceinstance.add_rotation_single_user(automatically_after=cdk.Duration.days(7),# defaults to 30 daysexclude_characters="!@#$%^&*")cluster=rds.DatabaseCluster(stack,"Database",engine=rds.DatabaseClusterEngine.AURORA,instance_props=rds.InstanceProps(instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3,ec2.InstanceSize.SMALL),vpc=vpc))cluster.add_rotation_single_user()The multi user rotation scheme is also available:# instance: rds.DatabaseInstance# my_imported_secret: rds.DatabaseSecretinstance.add_rotation_multi_user("MyUser",secret=my_imported_secret)It's also possible to create user credentials together with the instance/cluster and add rotation:# instance: rds.DatabaseInstancemy_user_secret=rds.DatabaseSecret(self,"MyUserSecret",username="myuser",secret_name="my-user-secret",# optional, defaults to a CloudFormation-generated namemaster_secret=instance.secret,exclude_characters="{}[]()'\"/\\")my_user_secret_attached=my_user_secret.attach(instance)# Adds DB connections information in the secretinstance.add_rotation_multi_user("MyUser",# Add rotation using the multi user schemesecret=my_user_secret_attached)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 thevpcSubnetsand/orendpointoptions:# instance: rds.DatabaseInstance# my_endpoint: ec2.InterfaceVpcEndpointinstance.add_rotation_single_user(vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT),# Place rotation Lambda in private subnetsendpoint=my_endpoint)See also@aws-cdk/aws-secretsmanagerfor credentials rotation of existing clusters/instances.IAM AuthenticationYou can also authenticate to a database instance using AWS Identity and Access Management (IAM) database authentication;
Seehttps://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.htmlfor more information
and a list of supported versions and limitations.Note:grantConnect()does not currently work - seethis GitHub issue.The following example shows enabling IAM authentication for a database instance and granting connection access to an IAM role.# vpc: ec2.Vpcinstance=rds.DatabaseInstance(self,"Instance",engine=rds.DatabaseInstanceEngine.mysql(version=rds.MysqlEngineVersion.VER_8_0_19),vpc=vpc,iam_authentication=True)role=iam.Role(self,"DBRole",assumed_by=iam.AccountPrincipal(self.account))instance.grant_connect(role)The following example shows granting connection access for RDS Proxy to an IAM role.# vpc: ec2.Vpccluster=rds.DatabaseCluster(self,"Database",engine=rds.DatabaseClusterEngine.AURORA,instance_props=rds.InstanceProps(vpc=vpc))proxy=rds.DatabaseProxy(self,"Proxy",proxy_target=rds.ProxyTarget.from_cluster(cluster),secrets=[cluster.secret],vpc=vpc)role=iam.Role(self,"DBProxyRole",assumed_by=iam.AccountPrincipal(self.account))proxy.grant_connect(role,"admin")Note: In addition to the setup above, a database user will need to be created to support IAM auth.
Seehttps://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.DBAccounts.htmlfor setup instructions.Kerberos AuthenticationYou can also authenticate using Kerberos to a database instance using AWS Managed Microsoft AD for authentication;
Seehttps://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.htmlfor 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: ec2.Vpcrole=iam.Role(self,"RDSDirectoryServicesRole",assumed_by=iam.ServicePrincipal("rds.amazonaws.com"),managed_policies=[iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AmazonRDSDirectoryServiceAccess")])instance=rds.DatabaseInstance(self,"Instance",engine=rds.DatabaseInstanceEngine.mysql(version=rds.MysqlEngineVersion.VER_8_0_19),vpc=vpc,domain="d-????????",# The ID of the domain for the instance to join.domain_role=role)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, seehttps://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.htmlfor details
on configuring users for each available database engine.MetricsDatabase instances and clusters both expose metrics (cloudwatch.Metric):# The number of database connections in use (average over 5 minutes)# instance: rds.DatabaseInstance# Average CPU utilization over 5 minutes# cluster: rds.DatabaseClusterdb_connections=instance.metric_database_connections()cpu_utilization=cluster.metric_cPUUtilization()# The average amount of time taken per disk I/O operation (average over 1 minute)read_latency=instance.metric("ReadLatency",statistic="Average",period=Duration.seconds(60))Enabling S3 integrationData in S3 buckets can be imported to and exported from certain database engines using SQL queries. To enable this
functionality, set thes3ImportBucketsands3ExportBucketsproperties for import and export respectively. When
configured, the CDK automatically creates and configures IAM roles as required.
Additionally, thes3ImportRoleands3ExportRoleproperties can be used to set this role directly.You can read more about loading data to (or from) S3 here:Aurora MySQL -importandexport.Aurora PostgreSQL -importandexport.Microsoft SQL Server -import and exportPostgreSQL -importandexportOracle -import and exportThe following snippet sets up a database cluster with different S3 buckets where the data is imported and exported -importaws_cdk.aws_s3ass3# vpc: ec2.Vpcimport_bucket=s3.Bucket(self,"importbucket")export_bucket=s3.Bucket(self,"exportbucket")rds.DatabaseCluster(self,"dbcluster",engine=rds.DatabaseClusterEngine.AURORA,instance_props=rds.InstanceProps(vpc=vpc),s3_import_buckets=[import_bucket],s3_export_buckets=[export_bucket])Creating a Database ProxyAmazon 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 atAmazon RDS ProxyThe following code configures an RDS Proxy for aDatabaseInstance.# vpc: ec2.Vpc# security_group: ec2.SecurityGroup# secrets: List[secretsmanager.Secret[]]# db_instance: rds.DatabaseInstanceproxy=db_instance.add_proxy("proxy",borrow_timeout=Duration.seconds(30),max_connections_percent=50,secrets=secrets,vpc=vpc)Exporting LogsYou 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.importaws_cdk.aws_logsaslogs# my_logs_publishing_role: iam.Role# vpc: ec2.Vpc# Exporting logs from a clustercluster=rds.DatabaseCluster(self,"Database",engine=rds.DatabaseClusterEngine.aurora(version=rds.AuroraEngineVersion.VER_1_17_9),instance_props=rds.InstanceProps(vpc=vpc),cloudwatch_logs_exports=["error","general","slowquery","audit"],# Export all available MySQL-based logscloudwatch_logs_retention=logs.RetentionDays.THREE_MONTHS,# Optional - default is to never expire logscloudwatch_logs_retention_role=my_logs_publishing_role)# Exporting logs from an instanceinstance=rds.DatabaseInstance(self,"Instance",engine=rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_12_3),vpc=vpc,cloudwatch_logs_exports=["postgresql"])Option GroupsSome 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: ec2.Vpc# security_group: ec2.SecurityGrouprds.OptionGroup(self,"Options",engine=rds.DatabaseInstanceEngine.oracle_se2(version=rds.OracleEngineVersion.VER_19),configurations=[rds.OptionConfiguration(name="OEM",port=5500,vpc=vpc,security_groups=[security_group])])Parameter GroupsDatabase 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: ec2.Vpcparameter_group=rds.ParameterGroup(self,"ParameterGroup",engine=rds.DatabaseInstanceEngine.sql_server_ee(version=rds.SqlServerEngineVersion.VER_11),parameters={"locks":"100"})rds.DatabaseInstance(self,"Database",engine=rds.DatabaseInstanceEngine.SQL_SERVER_EE,vpc=vpc,parameter_group=parameter_group)Another way to specify parameters is to use the inline fieldparametersthat 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: ec2.Vpcrds.DatabaseInstance(self,"Database",engine=rds.DatabaseInstanceEngine.sql_server_ee(version=rds.SqlServerEngineVersion.VER_11),vpc=vpc,parameters={"locks":"100"})You cannot specify a parameter map and a parameter group at the same time.ServerlessAmazon Aurora Serverlessis 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: ec2.Vpccluster=rds.ServerlessCluster(self,"AnotherCluster",engine=rds.DatabaseClusterEngine.AURORA_POSTGRESQL,parameter_group=rds.ParameterGroup.from_parameter_group_name(self,"ParameterGroup","default.aurora-postgresql10"),vpc=vpc,scaling=rds.ServerlessScalingOptions(auto_pause=Duration.minutes(10),# default is to pause after 5 minutes of idle timemin_capacity=rds.AuroraCapacityUnit.ACU_8,# default is 2 Aurora capacity units (ACUs)max_capacity=rds.AuroraCapacityUnit.ACU_32))Aurora Serverless Clusters do not support the following features:Loading data from an Amazon S3 bucketSaving data to an Amazon S3 bucketInvoking an AWS Lambda function with an Aurora MySQL native functionAurora replicasBacktrackingMulti-master clustersDatabase cloningIAM database cloningIAM database authenticationRestoring a snapshot from MySQL DB instancePerformance InsightsRDS ProxyRead more about thelimitations of Aurora ServerlessLearn more about using Amazon Aurora Serverless by reading thedocumentationUseServerlessClusterFromSnapshotto create a serverless cluster from a snapshot:# vpc: ec2.Vpcrds.ServerlessClusterFromSnapshot(self,"Cluster",engine=rds.DatabaseClusterEngine.AURORA_MYSQL,vpc=vpc,snapshot_identifier="mySnapshot")Data APIYou 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: ec2.Vpc# code: lambda.Codecluster=rds.ServerlessCluster(self,"AnotherCluster",engine=rds.DatabaseClusterEngine.AURORA_MYSQL,vpc=vpc,# this parameter is optional for serverless Clustersenable_data_api=True)fn=lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_14_X,handler="index.handler",code=code,environment={"CLUSTER_ARN":cluster.cluster_arn,"SECRET_ARN":cluster.secret.secret_arn})cluster.grant_data_api_access(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 thedocumentation.Default VPCThevpcparameter 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 thevpcSubnets,subnetGrouporsecurityGroupsof the Aurora Serverless Cluster.
If you want to provide one ofvpcSubnets,subnetGrouporsecurityGroupsparameter, please provide avpc.