Package software.amazon.awscdk.services.docdb


package software.amazon.awscdk.services.docdb

Amazon DocumentDB Construct Library

Starting a Clustered Database

To set up a clustered DocumentDB database, define a DatabaseCluster. You must always launch a database in a VPC. Use the vpcSubnets attribute to control whether your instances will be launched privately or publicly:

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .masterUser(Login.builder()
                 .username("myuser") // NOTE: 'admin' is reserved by DocumentDB
                 .excludeCharacters("\"@/:") // optional, defaults to the set "\"@/" and is also used for eventually created rotations
                 .secretName("/myapp/mydocdb/masteruser")
                 .build())
         .instanceType(InstanceType.of(InstanceClass.MEMORY5, InstanceSize.LARGE))
         .vpcSubnets(SubnetSelection.builder()
                 .subnetType(SubnetType.PUBLIC)
                 .build())
         .vpc(vpc)
         .copyTagsToSnapshot(true)
         .build();
 

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.

Serverless Clusters

DocumentDB supports serverless clusters that automatically scale capacity based on your application's needs. To create a serverless cluster, specify the serverlessV2ScalingConfiguration instead of instanceType:

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .masterUser(Login.builder()
                 .username("myuser")
                 .build())
         .vpc(vpc)
         .serverlessV2ScalingConfiguration(ServerlessV2ScalingConfiguration.builder()
                 .minCapacity(0.5)
                 .maxCapacity(2)
                 .build())
         .engineVersion("5.0.0")
         .build();
 

Note: DocumentDB serverless requires engine version 5.0.0 or higher and is not compatible with all features. See the AWS documentation for limitations.

Connecting

To control who can access the cluster, use the .connections attribute. DocumentDB databases have a default port, so you don't need to specify the port:

 DatabaseCluster cluster;
 
 cluster.connections.allowDefaultPortFromAnyIpv4("Open to the world");
 

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

 DatabaseCluster cluster;
 
 String writeAddress = cluster.getClusterEndpoint().getSocketAddress();
 

If you have existing security groups you would like to add to the cluster, use the addSecurityGroups method. Security groups added in this way will not be managed by the Connections object of the cluster.

 Vpc vpc;
 DatabaseCluster cluster;
 
 
 SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SecurityGroup")
         .vpc(vpc)
         .build();
 cluster.addSecurityGroups(securityGroup);
 

Deletion protection

Deletion protection can be enabled on an Amazon DocumentDB cluster to prevent accidental deletion of the cluster:

 Vpc vpc;
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .masterUser(Login.builder()
                 .username("myuser")
                 .build())
         .instanceType(InstanceType.of(InstanceClass.MEMORY5, InstanceSize.LARGE))
         .vpcSubnets(SubnetSelection.builder()
                 .subnetType(SubnetType.PUBLIC)
                 .build())
         .vpc(vpc)
         .deletionProtection(true)
         .build();
 

AWS Secrets Manager Integration

DocumentDB clusters can integrate with AWS Secrets Manager to automatically manage master user passwords. This provides enhanced security through automatic password generation and rotation capabilities.

Managed Master User Password

To enable AWS Secrets Manager to manage the master user password, set manageMasterUserPassword to true:

 Vpc vpc;
 
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .manageMasterUserPassword(true)
         .masterUser(Login.builder()
                 .username("myuser")
                 .build())
         .instanceType(InstanceType.of(InstanceClass.MEMORY5, InstanceSize.LARGE))
         .vpc(vpc)
         .build();
 

When manageMasterUserPassword is enabled:

  • Amazon DocumentDB automatically generates a secure password
  • The password is stored in AWS Secrets Manager
  • You cannot specify masterUser.password (it will be auto-generated)
  • The secret is automatically rotated every 7 days by default

By default (without manageMasterUserPassword), the construct creates and manages a Secrets Manager secret for the master password, and rotation must be configured explicitly with addRotationSingleUser(), which deploys a rotation Lambda function. The manageMasterUserPassword option delegates password management entirely to the DocumentDB service, which includes built-in automatic rotation every 7 days without requiring Lambda functions.

Custom KMS Key for Secret Encryption

You can specify a custom KMS key to encrypt the managed secret:

 Vpc vpc;
 Key myKmsKey;
 
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .manageMasterUserPassword(true)
         .masterUser(Login.builder()
                 .username("myuser")
                 .build())
         .masterUserSecretKmsKey(myKmsKey) // KMS Key for secret encryption
         .instanceType(InstanceType.of(InstanceClass.MEMORY5, InstanceSize.LARGE))
         .vpc(vpc)
         .build();
 

Accessing the Managed Secret

The ARN of the secret created by manageMasterUserPassword is not provided by CloudFormation currently (unlike AWS::RDS::DBCluster, the AWS::DocDB::DBCluster resource has no MasterUserSecret.SecretArn attribute), so the secret property of the cluster remains undefined and cannot be used to grant access to the managed secret.

You can retrieve the secret ARN dynamically using a custom resource:

 import software.amazon.awscdk.customresources.*;
 import software.amazon.awscdk.services.iam.*;
 import software.amazon.awscdk.services.secretsmanager.*;
 
 DatabaseCluster cluster;
 Role role;
 
 
 // Call rds:DescribeDBClusters to retrieve the managed secret ARN at deploy time
 AwsCustomResource getSecretArn = AwsCustomResource.Builder.create(this, "GetManagedSecretArn")
         .onUpdate(AwsSdkCall.builder()
                 .service("DocDB")
                 .action("describeDBClusters")
                 .parameters(Map.of(
                         "DBClusterIdentifier", cluster.getClusterIdentifier()))
                 .physicalResourceId(PhysicalResourceId.of("GetManagedSecretArn"))
                 .build())
         .policy(AwsCustomResourcePolicy.fromSdkCalls(SdkCallsPolicyOptions.builder()
                 .resources(AwsCustomResourcePolicy.ANY_RESOURCE)
                 .build()))
         .build();
 
 ISecret managedSecret = Secret.fromSecretAttributes(this, "ManagedSecret", SecretAttributes.builder()
         .secretCompleteArn(getSecretArn.getResponseField("DBClusters.0.MasterUserSecret.SecretArn"))
         .build());
 managedSecret.grantRead(role);
 

If the secret is encrypted with a customer managed KMS key (masterUserSecretKmsKey), also pass encryptionKey to Secret.fromSecretAttributes() so that grantRead() grants kms:Decrypt on the key as well.

Rotating credentials

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

 DatabaseCluster cluster;
 
 cluster.addRotationSingleUser();
 

 DatabaseCluster cluster = DatabaseCluster.Builder.create(stack, "Database")
         .masterUser(Login.builder()
                 .username("docdb")
                 .build())
         .instanceType(InstanceType.of(InstanceClass.R5, InstanceSize.LARGE))
         .vpc(vpc)
         .removalPolicy(RemovalPolicy.DESTROY)
         .build();
 
 cluster.addRotationSingleUser();
 

The multi user rotation scheme is also available:

 import software.amazon.awscdk.services.secretsmanager.*;
 
 Secret myImportedSecret;
 DatabaseCluster cluster;
 
 
 cluster.addRotationMultiUser("MyUser", RotationMultiUserOptions.builder()
         .secret(myImportedSecret)
         .build());
 

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

 DatabaseCluster cluster;
 
 DatabaseSecret myUserSecret = DatabaseSecret.Builder.create(this, "MyUserSecret")
         .username("myuser")
         .masterSecret(cluster.getSecret())
         .build();
 ISecret myUserSecretAttached = myUserSecret.attach(cluster); // Adds DB connections information in the secret
 
 cluster.addRotationMultiUser("MyUser", RotationMultiUserOptions.builder() // Add rotation using the multi user scheme
         .secret(myUserSecretAttached).build());
 

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

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

Audit and profiler Logs

Sending audit or profiler needs to be configured in two places:

  1. Check / create the needed options in your ParameterGroup for audit and profiler logs.
  2. Enable the corresponding option(s) when creating the DatabaseCluster:

 import software.amazon.awscdk.services.iam.*;
 import software.amazon.awscdk.services.logs.*;
 
 Role myLogsPublishingRole;
 Vpc vpc;
 
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .masterUser(Login.builder()
                 .username("myuser")
                 .build())
         .instanceType(InstanceType.of(InstanceClass.MEMORY5, InstanceSize.LARGE))
         .vpcSubnets(SubnetSelection.builder()
                 .subnetType(SubnetType.PUBLIC)
                 .build())
         .vpc(vpc)
         .exportProfilerLogsToCloudWatch(true) // Enable sending profiler logs
         .exportAuditLogsToCloudWatch(true) // Enable sending audit logs
         .cloudWatchLogsRetention(RetentionDays.THREE_MONTHS) // Optional - default is to never expire logs
         .cloudWatchLogsRetentionRole(myLogsPublishingRole)
         .build();
 

Enable Performance Insights

By enabling this feature it will be cascaded and enabled in all instances inside the cluster:

 Vpc vpc;
 
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .masterUser(Login.builder()
                 .username("myuser")
                 .build())
         .instanceType(InstanceType.of(InstanceClass.MEMORY5, InstanceSize.LARGE))
         .vpcSubnets(SubnetSelection.builder()
                 .subnetType(SubnetType.PUBLIC)
                 .build())
         .vpc(vpc)
         .enablePerformanceInsights(true)
         .build();
 

## Removal Policy

This resource supports the snapshot removal policy. To specify it use the removalPolicy property:

 Vpc vpc;
 
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .masterUser(Login.builder()
                 .username("myuser")
                 .build())
         .instanceType(InstanceType.of(InstanceClass.MEMORY5, InstanceSize.LARGE))
         .vpcSubnets(SubnetSelection.builder()
                 .subnetType(SubnetType.PUBLIC)
                 .build())
         .vpc(vpc)
         .removalPolicy(RemovalPolicy.SNAPSHOT)
         .build();
 

Note: A RemovalPolicy.DESTROY removal policy will be applied to the cluster's instances and security group by default as they don't support the snapshot removal policy.

Visit DeletionPolicy for more details.

To specify a custom removal policy for the cluster's instances, use the instanceRemovalPolicy property:

 Vpc vpc;
 
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .masterUser(Login.builder()
                 .username("myuser")
                 .build())
         .instanceType(InstanceType.of(InstanceClass.MEMORY5, InstanceSize.LARGE))
         .vpcSubnets(SubnetSelection.builder()
                 .subnetType(SubnetType.PUBLIC)
                 .build())
         .vpc(vpc)
         .removalPolicy(RemovalPolicy.SNAPSHOT)
         .instanceRemovalPolicy(RemovalPolicy.RETAIN)
         .build();
 

To specify a custom removal policy for the cluster's security group, use the securityGroupRemovalPolicy property:

 Vpc vpc;
 
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .masterUser(Login.builder()
                 .username("myuser")
                 .build())
         .instanceType(InstanceType.of(InstanceClass.MEMORY5, InstanceSize.LARGE))
         .vpcSubnets(SubnetSelection.builder()
                 .subnetType(SubnetType.PUBLIC)
                 .build())
         .vpc(vpc)
         .removalPolicy(RemovalPolicy.SNAPSHOT)
         .securityGroupRemovalPolicy(RemovalPolicy.RETAIN)
         .build();
 

CA certificate

Use the caCertificate property to specify the CA certificate to use for all instances inside the cluster:

 Vpc vpc;
 
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .masterUser(Login.builder()
                 .username("myuser")
                 .build())
         .instanceType(InstanceType.of(InstanceClass.MEMORY5, InstanceSize.LARGE))
         .vpcSubnets(SubnetSelection.builder()
                 .subnetType(SubnetType.PUBLIC)
                 .build())
         .vpc(vpc)
         .caCertificate(CaCertificate.RDS_CA_RSA4096_G1)
         .build();
 

Storage Type

You can specify storage type for the cluster.

 Vpc vpc;
 
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .masterUser(Login.builder()
                 .username("myuser")
                 .build())
         .instanceType(InstanceType.of(InstanceClass.MEMORY5, InstanceSize.LARGE))
         .vpc(vpc)
         .storageType(StorageType.IOPT1)
         .build();
 

Note: StorageType.IOPT1 is supported starting with engine version 5.0.0.

Note: For serverless clusters, storage type is managed automatically and cannot be specified.

Maintenance Windows

DocumentDB has two independent maintenance windows: one for cluster-wide events (engine upgrades, etc.) and one per instance (reboots, patches). Use preferredMaintenanceWindow to control the cluster window and instanceMaintenanceWindow to control the window applied to every auto-created instance.

Note: instanceMaintenanceWindow only applies to provisioned clusters. It has no effect on serverless clusters because they don't create instances.

 Vpc vpc;
 
 
 DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Database")
         .masterUser(Login.builder()
                 .username("myuser")
                 .build())
         .instanceType(InstanceType.of(InstanceClass.MEMORY5, InstanceSize.LARGE))
         .vpc(vpc)
         .preferredMaintenanceWindow("tue:04:17-tue:04:47") // cluster-wide events
         .instanceMaintenanceWindow("sat:09:00-sat:09:30")
         .build();
 

If you want both the cluster and its instances to share the same window, set both props to the same value. When instanceMaintenanceWindow is not provided, a random 30-minute window is picked for each instance, which can cause maintenance events outside the cluster window.