aws-cdk-lib.aws_rds.DatabaseInstance

class DatabaseInstance (construct)

LanguageType name
.NETAmazon.CDK.AWS.RDS.DatabaseInstance
Gogithub.com/aws/aws-cdk-go/awscdk/v2/awsrds#DatabaseInstance
Javasoftware.amazon.awscdk.services.rds.DatabaseInstance
Pythonaws_cdk.aws_rds.DatabaseInstance
TypeScript (source)aws-cdk-lib » aws_rds » DatabaseInstance

Implements IConstruct, IDependable, IResource, IDatabaseInstance, IConnectable, ISecretAttachmentTarget

A database instance.

Example

declare const vpc: ec2.IVpc;

const instance1 = new rds.DatabaseInstance(this, "PostgresInstance1", {
  engine: rds.DatabaseInstanceEngine.POSTGRES,
  // Generate the secret with admin username `postgres` and random password
  credentials: rds.Credentials.fromGeneratedSecret('postgres'),
  vpc
});
// Templated secret with username and password fields
const templatedSecret = new secretsmanager.Secret(this, 'TemplatedSecret', {
  generateSecretString: {
    secretStringTemplate: JSON.stringify({ username: 'postgres' }),
    generateStringKey: 'password',
    excludeCharacters: '/@"',
  },
});
// Using the templated secret as credentials
const instance2 = new rds.DatabaseInstance(this, "PostgresInstance2", {
  engine: rds.DatabaseInstanceEngine.POSTGRES,
  credentials: {
    username: templatedSecret.secretValueFromJson('username').toString(),
    password: templatedSecret.secretValueFromJson('password')
  },
  vpc
});

Initializer

new DatabaseInstance(scope: Construct, id: string, props: DatabaseInstanceProps)

Parameters

  • scope Construct
  • id string
  • props DatabaseInstanceProps

Construct Props

NameTypeDescription
engineIInstanceEngineThe database engine.
vpcIVpcThe VPC network where the DB subnet group should be created.
allocatedStorage?numberThe allocated storage size, specified in gibibytes (GiB).
allowMajorVersionUpgrade?booleanWhether to allow major version upgrades.
autoMinorVersionUpgrade?booleanIndicates that minor engine upgrades are applied automatically to the DB instance during the maintenance window.
availabilityZone?stringThe name of the Availability Zone where the DB instance will be located.
backupRetention?DurationThe number of days during which automatic DB snapshots are retained.
characterSetName?stringFor supported engines, specifies the character set to associate with the DB instance.
cloudwatchLogsExports?string[]The list of log types that need to be enabled for exporting to CloudWatch Logs.
cloudwatchLogsRetention?RetentionDaysThe number of days log events are kept in CloudWatch Logs.
cloudwatchLogsRetentionRole?IRoleThe IAM role for the Lambda function associated with the custom resource that sets the retention policy.
copyTagsToSnapshot?booleanIndicates whether to copy all of the user-defined tags from the DB instance to snapshots of the DB instance.
credentials?CredentialsCredentials for the administrative user.
databaseName?stringThe name of the database.
deleteAutomatedBackups?booleanIndicates whether automated backups should be deleted or retained when you delete a DB instance.
deletionProtection?booleanIndicates whether the DB instance should have deletion protection enabled.
domain?stringThe Active Directory directory ID to create the DB instance in.
domainRole?IRoleThe IAM role to be used when making API calls to the Directory Service.
enablePerformanceInsights?booleanWhether to enable Performance Insights for the DB instance.
iamAuthentication?booleanWhether to enable mapping of AWS Identity and Access Management (IAM) accounts to database accounts.
instanceIdentifier?stringA name for the DB instance.
instanceType?InstanceTypeThe name of the compute and memory capacity for the instance.
iops?numberThe number of I/O operations per second (IOPS) that the database provisions.
licenseModel?LicenseModelThe license model.
maxAllocatedStorage?numberUpper limit to which RDS can scale the storage in GiB(Gibibyte).
monitoringInterval?DurationThe interval, in seconds, between points when Amazon RDS collects enhanced monitoring metrics for the DB instance.
monitoringRole?IRoleRole that will be used to manage DB instance monitoring.
multiAz?booleanSpecifies if the database instance is a multiple Availability Zone deployment.
networkType?NetworkTypeThe network type of the DB instance.
optionGroup?IOptionGroupThe option group to associate with the instance.
parameterGroup?IParameterGroupThe DB parameter group to associate with the instance.
parameters?{ [string]: string }The parameters in the DBParameterGroup to create automatically.
performanceInsightEncryptionKey?IKeyThe AWS KMS key for encryption of Performance Insights data.
performanceInsightRetention?PerformanceInsightRetentionThe amount of time, in days, to retain Performance Insights data.
port?numberThe port for the instance.
preferredBackupWindow?stringThe daily time range during which automated backups are performed.
preferredMaintenanceWindow?stringThe weekly time range (in UTC) during which system maintenance can occur.
processorFeatures?ProcessorFeaturesThe number of CPU cores and the number of threads per core.
publiclyAccessible?booleanIndicates whether the DB instance is an internet-facing instance.
removalPolicy?RemovalPolicyThe CloudFormation policy to apply when the instance is removed from the stack or replaced during an update.
s3ExportBuckets?IBucket[]S3 buckets that you want to load data into.
s3ExportRole?IRoleRole that will be associated with this DB instance to enable S3 export.
s3ImportBuckets?IBucket[]S3 buckets that you want to load data from.
s3ImportRole?IRoleRole that will be associated with this DB instance to enable S3 import.
securityGroups?ISecurityGroup[]The security groups to assign to the DB instance.
storageEncrypted?booleanIndicates whether the DB instance is encrypted.
storageEncryptionKey?IKeyThe KMS key that's used to encrypt the DB instance.
storageThroughput?numberThe storage throughput, specified in mebibytes per second (MiBps).
storageType?StorageTypeThe storage type.
subnetGroup?ISubnetGroupExisting subnet group for the instance.
timezone?stringThe time zone of the instance.
vpcSubnets?SubnetSelectionThe type of subnets to add to the created DB subnet group.

engine

Type: IInstanceEngine

The database engine.


vpc

Type: IVpc

The VPC network where the DB subnet group should be created.


allocatedStorage?

Type: number (optional, default: 100)

The allocated storage size, specified in gibibytes (GiB).


allowMajorVersionUpgrade?

Type: boolean (optional, default: false)

Whether to allow major version upgrades.


autoMinorVersionUpgrade?

Type: boolean (optional, default: true)

Indicates that minor engine upgrades are applied automatically to the DB instance during the maintenance window.


availabilityZone?

Type: string (optional, default: no preference)

The name of the Availability Zone where the DB instance will be located.


backupRetention?

Type: Duration (optional, default: Duration.days(1) for source instances, disabled for read replicas)

The number of days during which automatic DB snapshots are retained.

Set to zero to disable backups. When creating a read replica, you must enable automatic backups on the source database instance by setting the backup retention to a value other than zero.


characterSetName?

Type: string (optional, default: RDS default character set name)

For supported engines, specifies the character set to associate with the DB instance.


cloudwatchLogsExports?

Type: string[] (optional, default: no log exports)

The list of log types that need to be enabled for exporting to CloudWatch Logs.


cloudwatchLogsRetention?

Type: RetentionDays (optional, default: logs never expire)

The number of days log events are kept in CloudWatch Logs.

When updating this property, unsetting it doesn't remove the log retention policy. To remove the retention policy, set the value to Infinity.


cloudwatchLogsRetentionRole?

Type: IRole (optional, default: a new role is created.)

The IAM role for the Lambda function associated with the custom resource that sets the retention policy.


copyTagsToSnapshot?

Type: boolean (optional, default: true)

Indicates whether to copy all of the user-defined tags from the DB instance to snapshots of the DB instance.


credentials?

Type: Credentials (optional, default: A username of 'admin' (or 'postgres' for PostgreSQL) and SecretsManager-generated password)

Credentials for the administrative user.


databaseName?

Type: string (optional, default: no name)

The name of the database.


deleteAutomatedBackups?

Type: boolean (optional, default: false)

Indicates whether automated backups should be deleted or retained when you delete a DB instance.


deletionProtection?

Type: boolean (optional, default: true if removalPolicy is RETAIN, false otherwise)

Indicates whether the DB instance should have deletion protection enabled.


domain?

Type: string (optional, default: Do not join domain)

The Active Directory directory ID to create the DB instance in.


domainRole?

Type: IRole (optional, default: The role will be created for you if DatabaseInstanceNewProps#domain is specified)

The IAM role to be used when making API calls to the Directory Service.

The role needs the AWS-managed policy AmazonRDSDirectoryServiceAccess or equivalent.


enablePerformanceInsights?

Type: boolean (optional, default: false, unless performanceInsightRentention or performanceInsightEncryptionKey is set.)

Whether to enable Performance Insights for the DB instance.


iamAuthentication?

Type: boolean (optional, default: false)

Whether to enable mapping of AWS Identity and Access Management (IAM) accounts to database accounts.


instanceIdentifier?

Type: string (optional, default: a CloudFormation generated name)

A name for the DB instance.

If you specify a name, AWS CloudFormation converts it to lowercase.


instanceType?

Type: InstanceType (optional, default: m5.large (or, more specifically, db.m5.large))

The name of the compute and memory capacity for the instance.


iops?

Type: number (optional, default: no provisioned iops if storage type is not specified. For GP3: 3,000 IOPS if allocated storage is less than 400 GiB for MariaDB, MySQL, and PostgreSQL, less than 200 GiB for Oracle and less than 20 GiB for SQL Server. 12,000 IOPS otherwise (except for SQL Server where the default is always 3,000 IOPS).)

The number of I/O operations per second (IOPS) that the database provisions.

The value must be equal to or greater than 1000.


licenseModel?

Type: LicenseModel (optional, default: RDS default license model)

The license model.


maxAllocatedStorage?

Type: number (optional, default: No autoscaling of RDS instance)

Upper limit to which RDS can scale the storage in GiB(Gibibyte).

See also: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PIOPS.StorageTypes.html#USER_PIOPS.Autoscaling


monitoringInterval?

Type: Duration (optional, default: no enhanced monitoring)

The interval, in seconds, between points when Amazon RDS collects enhanced monitoring metrics for the DB instance.


monitoringRole?

Type: IRole (optional, default: A role is automatically created for you)

Role that will be used to manage DB instance monitoring.


multiAz?

Type: boolean (optional, default: false)

Specifies if the database instance is a multiple Availability Zone deployment.


networkType?

Type: NetworkType (optional, default: IPV4)

The network type of the DB instance.


optionGroup?

Type: IOptionGroup (optional, default: no option group)

The option group to associate with the instance.


parameterGroup?

Type: IParameterGroup (optional, default: no parameter group)

The DB parameter group to associate with the instance.


parameters?

Type: { [string]: string } (optional, default: None)

The parameters in the DBParameterGroup to create automatically.

You can only specify parameterGroup or parameters but not both. You need to use a versioned engine to auto-generate a DBParameterGroup.


performanceInsightEncryptionKey?

Type: IKey (optional, default: default master key)

The AWS KMS key for encryption of Performance Insights data.


performanceInsightRetention?

Type: PerformanceInsightRetention (optional, default: 7 this is the free tier)

The amount of time, in days, to retain Performance Insights data.


port?

Type: number (optional, default: the default port for the chosen engine.)

The port for the instance.


preferredBackupWindow?

Type: string (optional, default: a 30-minute window selected at random from an 8-hour block of time for each AWS Region. To see the time blocks available, see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithAutomatedBackups.html#USER_WorkingWithAutomatedBackups.BackupWindow)

The daily time range during which automated backups are performed.

Constraints:

  • Must be in the format hh24:mi-hh24:mi.
  • Must be in Universal Coordinated Time (UTC).
  • Must not conflict with the preferred maintenance window.
  • Must be at least 30 minutes.

preferredMaintenanceWindow?

Type: string (optional, default: a 30-minute window selected at random from an 8-hour block of time for each AWS Region, occurring on a random day of the week. To see the time blocks available, see https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html#Concepts.DBMaintenance)

The weekly time range (in UTC) during which system maintenance can occur.

Format: ddd:hh24:mi-ddd:hh24:mi Constraint: Minimum 30-minute window


processorFeatures?

Type: ProcessorFeatures *(optional, default: the default number of CPU cores and threads per core for the chosen instance class.

See https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.DBInstanceClass.html#USER_ConfigureProcessor)*

The number of CPU cores and the number of threads per core.


publiclyAccessible?

Type: boolean (optional, default: true if vpcSubnets is subnetType: SubnetType.PUBLIC, false otherwise)

Indicates whether the DB instance is an internet-facing instance.


removalPolicy?

Type: RemovalPolicy (optional, default: RemovalPolicy.SNAPSHOT (remove the resource, but retain a snapshot of the data))

The CloudFormation policy to apply when the instance is removed from the stack or replaced during an update.


s3ExportBuckets?

Type: IBucket[] (optional, default: None)

S3 buckets that you want to load data into.

This property must not be used if s3ExportRole is used.

For Microsoft SQL Server:

See also: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-s3-integration.html


s3ExportRole?

Type: IRole (optional, default: New role is created if s3ExportBuckets is set, no role is defined otherwise)

Role that will be associated with this DB instance to enable S3 export.

This property must not be used if s3ExportBuckets is used.

For Microsoft SQL Server:

See also: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-s3-integration.html


s3ImportBuckets?

Type: IBucket[] (optional, default: None)

S3 buckets that you want to load data from.

This feature is only supported by the Microsoft SQL Server, Oracle, and PostgreSQL engines.

This property must not be used if s3ImportRole is used.

For Microsoft SQL Server:

See also: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/PostgreSQL.Procedural.Importing.html


s3ImportRole?

Type: IRole (optional, default: New role is created if s3ImportBuckets is set, no role is defined otherwise)

Role that will be associated with this DB instance to enable S3 import.

This feature is only supported by the Microsoft SQL Server, Oracle, and PostgreSQL engines.

This property must not be used if s3ImportBuckets is used.

For Microsoft SQL Server:

See also: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/PostgreSQL.Procedural.Importing.html


securityGroups?

Type: ISecurityGroup[] (optional, default: a new security group is created)

The security groups to assign to the DB instance.


storageEncrypted?

Type: boolean (optional, default: true if storageEncryptionKey has been provided, false otherwise)

Indicates whether the DB instance is encrypted.


storageEncryptionKey?

Type: IKey (optional, default: default master key if storageEncrypted is true, no key otherwise)

The KMS key that's used to encrypt the DB instance.


storageThroughput?

Type: number (optional, default: 125 MiBps if allocated storage is less than 400 GiB for MariaDB, MySQL, and PostgreSQL, less than 200 GiB for Oracle and less than 20 GiB for SQL Server. 500 MiBps otherwise (except for SQL Server where the default is always 125 MiBps).)

The storage throughput, specified in mebibytes per second (MiBps).

Only applicable for GP3.

See also: https://docs.aws.amazon.com//AmazonRDS/latest/UserGuide/CHAP_Storage.html#gp3-storage


storageType?

Type: StorageType (optional, default: GP2)

The storage type.

Storage types supported are gp2, io1, standard.

See also: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html#Concepts.Storage.GeneralSSD


subnetGroup?

Type: ISubnetGroup (optional, default: a new subnet group will be created.)

Existing subnet group for the instance.


timezone?

Type: string (optional, default: RDS default timezone)

The time zone of the instance.

This is currently supported only by Microsoft Sql Server.


vpcSubnets?

Type: SubnetSelection (optional, default: private subnets)

The type of subnets to add to the created DB subnet group.

Properties

NameTypeDescription
connectionsConnectionsAccess to network connections.
dbInstanceEndpointAddressstringThe instance endpoint address.
dbInstanceEndpointPortstringThe instance endpoint port.
envResourceEnvironmentThe environment this resource belongs to.
instanceArnstringThe instance arn.
instanceEndpointEndpointThe instance endpoint.
instanceIdentifierstringThe instance identifier.
instanceTypeInstanceType
newCfnPropsCfnDBInstanceProps
nodeNodeThe tree node.
sourceCfnPropsCfnDBInstanceProps
stackStackThe stack in which this resource is defined.
vpcIVpcThe VPC where this database instance is deployed.
enableIamAuthentication?boolean
engine?IInstanceEngineThe engine of this database Instance.
instanceResourceId?stringThe AWS Region-unique, immutable identifier for the DB instance.
secret?ISecretThe AWS Secrets Manager secret attached to the instance.
vpcPlacement?SubnetSelection

connections

Type: Connections

Access to network connections.


dbInstanceEndpointAddress

Type: string

The instance endpoint address.


dbInstanceEndpointPort

Type: string

The instance endpoint port.


env

Type: ResourceEnvironment

The environment this resource belongs to.

For resources that are created and managed by the CDK (generally, those created by creating new class instances like Role, Bucket, etc.), this is always the same as the environment of the stack they belong to; however, for imported resources (those obtained from static methods like fromRoleArn, fromBucketName, etc.), that might be different than the stack they were imported into.


instanceArn

Type: string

The instance arn.


instanceEndpoint

Type: Endpoint

The instance endpoint.


instanceIdentifier

Type: string

The instance identifier.


instanceType

Type: InstanceType


newCfnProps

Type: CfnDBInstanceProps


node

Type: Node

The tree node.


sourceCfnProps

Type: CfnDBInstanceProps


stack

Type: Stack

The stack in which this resource is defined.


vpc

Type: IVpc

The VPC where this database instance is deployed.


enableIamAuthentication?

Type: boolean (optional)


engine?

Type: IInstanceEngine (optional)

The engine of this database Instance.

May be not known for imported Instances if it wasn't provided explicitly, or for read replicas.


instanceResourceId?

Type: string (optional)

The AWS Region-unique, immutable identifier for the DB instance.

This identifier is found in AWS CloudTrail log entries whenever the AWS KMS key for the DB instance is accessed.


secret?

Type: ISecret (optional)

The AWS Secrets Manager secret attached to the instance.


vpcPlacement?

Type: SubnetSelection (optional)

Methods

NameDescription
addProxy(id, options)Add a new db proxy to this instance.
addRotationMultiUser(id, options)Adds the multi user rotation to this instance.
addRotationSingleUser(options?)Adds the single user rotation of the master password to this instance.
applyRemovalPolicy(policy)Apply the given removal policy to this resource.
asSecretAttachmentTarget()Renders the secret attachment target specifications.
grantConnect(grantee, dbUser?)Grant the given identity connection access to the database.
metric(metricName, props?)Return the given named metric for this DBInstance.
metricCPUUtilization(props?)The percentage of CPU utilization.
metricDatabaseConnections(props?)The number of database connections in use.
metricFreeStorageSpace(props?)The amount of available storage space.
metricFreeableMemory(props?)The amount of available random access memory.
metricReadIOPS(props?)The average number of disk write I/O operations per second.
metricWriteIOPS(props?)The average number of disk read I/O operations per second.
onEvent(id, options?)Defines a CloudWatch event rule which triggers for instance events.
toString()Returns a string representation of this construct.
protected setLogRetention()

addProxy(id, options)

public addProxy(id: string, options: DatabaseProxyOptions): DatabaseProxy

Parameters

  • id string
  • options DatabaseProxyOptions

Returns

  • DatabaseProxy

Add a new db proxy to this instance.


addRotationMultiUser(id, options)

public addRotationMultiUser(id: string, options: RotationMultiUserOptions): SecretRotation

Parameters

  • id string
  • options RotationMultiUserOptions

Returns

  • SecretRotation

Adds the multi user rotation to this instance.


addRotationSingleUser(options?)

public addRotationSingleUser(options?: RotationSingleUserOptions): SecretRotation

Parameters

  • options RotationSingleUserOptions — the options for the rotation, if you want to override the defaults.

Returns

  • SecretRotation

Adds the single user rotation of the master password to this instance.


applyRemovalPolicy(policy)

public applyRemovalPolicy(policy: RemovalPolicy): void

Parameters

  • policy RemovalPolicy

Apply the given removal policy to this resource.

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).


asSecretAttachmentTarget()

public asSecretAttachmentTarget(): SecretAttachmentTargetProps

Returns

  • SecretAttachmentTargetProps

Renders the secret attachment target specifications.


grantConnect(grantee, dbUser?)

public grantConnect(grantee: IGrantable, dbUser?: string): Grant

Parameters

  • grantee IGrantable — the Principal to grant the permissions to.
  • dbUser string — the name of the database user to allow connecting as to the db instance.

Returns

  • Grant

Grant the given identity connection access to the database.


metric(metricName, props?)

public metric(metricName: string, props?: MetricOptions): Metric

Parameters

  • metricName string
  • props MetricOptions

Returns

  • Metric

Return the given named metric for this DBInstance.


metricCPUUtilization(props?)

public metricCPUUtilization(props?: MetricOptions): Metric

Parameters

  • props MetricOptions

Returns

  • Metric

The percentage of CPU utilization.

Average over 5 minutes


metricDatabaseConnections(props?)

public metricDatabaseConnections(props?: MetricOptions): Metric

Parameters

  • props MetricOptions

Returns

  • Metric

The number of database connections in use.

Average over 5 minutes


metricFreeStorageSpace(props?)

public metricFreeStorageSpace(props?: MetricOptions): Metric

Parameters

  • props MetricOptions

Returns

  • Metric

The amount of available storage space.

Average over 5 minutes


metricFreeableMemory(props?)

public metricFreeableMemory(props?: MetricOptions): Metric

Parameters

  • props MetricOptions

Returns

  • Metric

The amount of available random access memory.

Average over 5 minutes


metricReadIOPS(props?)

public metricReadIOPS(props?: MetricOptions): Metric

Parameters

  • props MetricOptions

Returns

  • Metric

The average number of disk write I/O operations per second.

Average over 5 minutes


metricWriteIOPS(props?)

public metricWriteIOPS(props?: MetricOptions): Metric

Parameters

  • props MetricOptions

Returns

  • Metric

The average number of disk read I/O operations per second.

Average over 5 minutes


onEvent(id, options?)

public onEvent(id: string, options?: OnEventOptions): Rule

Parameters

  • id string
  • options OnEventOptions

Returns

  • Rule

Defines a CloudWatch event rule which triggers for instance events.

Use rule.addEventPattern(pattern) to specify a filter.


toString()

public toString(): string

Returns

  • string

Returns a string representation of this construct.


protected setLogRetention()

protected setLogRetention(): void