package
1.204.0-devpreview
Repository: https://github.com/aws/aws-cdk-go.git
Documentation: pkg.go.dev

# README

Amazon Relational Database Service Construct Library

import rds "github.com/aws/aws-cdk-go/awscdk"

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:

var vpc vpc

cluster := rds.NewDatabaseCluster(this, jsii.String("Database"), &DatabaseClusterProps{
	Engine: rds.DatabaseClusterEngine_AuroraMysql(&AuroraMysqlClusterEngineProps{
		Version: rds.AuroraMysqlEngineVersion_VER_2_08_1(),
	}),
	Credentials: rds.Credentials_FromGeneratedSecret(jsii.String("clusteradmin")),
	 // Optional - will default to 'admin' username and generated password
	InstanceProps: &InstanceProps{
		// optional , defaults to t3.medium
		InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE2, ec2.InstanceSize_SMALL),
		VpcSubnets: &SubnetSelection{
			SubnetType: ec2.SubnetType_PRIVATE_WITH_NAT,
		},
		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.

customEngineVersion := rds.AuroraMysqlEngineVersion_Of(jsii.String("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.

Use DatabaseClusterFromSnapshot to create a cluster from a snapshot:

var vpc vpc

rds.NewDatabaseClusterFromSnapshot(this, jsii.String("Database"), &DatabaseClusterFromSnapshotProps{
	Engine: rds.DatabaseClusterEngine_Aurora(&AuroraClusterEngineProps{
		Version: rds.AuroraEngineVersion_VER_1_22_2(),
	}),
	InstanceProps: &InstanceProps{
		Vpc: *Vpc,
	},
	SnapshotIdentifier: jsii.String("mySnapshot"),
})

Starting an instance database

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:

var vpc vpc

instance := rds.NewDatabaseInstance(this, jsii.String("Instance"), &DatabaseInstanceProps{
	Engine: rds.DatabaseInstanceEngine_OracleSe2(&OracleSe2InstanceEngineProps{
		Version: rds.OracleEngineVersion_VER_19_0_0_0_2020_04_R1(),
	}),
	// optional, defaults to m5.large
	InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE3, ec2.InstanceSize_SMALL),
	Credentials: rds.Credentials_FromGeneratedSecret(jsii.String("syscdk")),
	 // Optional - will default to 'admin' username and generated password
	Vpc: Vpc,
	VpcSubnets: &SubnetSelection{
		SubnetType: ec2.SubnetType_PRIVATE_WITH_NAT,
	},
})

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.

customEngineVersion := rds.OracleEngineVersion_Of(jsii.String("19.0.0.0.ru-2020-04.rur-2020-04.r1"), jsii.String("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:

var vpc vpc

instance := rds.NewDatabaseInstance(this, jsii.String("Instance"), &DatabaseInstanceProps{
	Engine: rds.DatabaseInstanceEngine_Postgres(&PostgresInstanceEngineProps{
		Version: rds.PostgresEngineVersion_VER_12_3(),
	}),
	// optional, defaults to m5.large
	InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE2, ec2.InstanceSize_SMALL),
	Vpc: Vpc,
	MaxAllocatedStorage: jsii.Number(200),
})

Use DatabaseInstanceFromSnapshot and DatabaseInstanceReadReplica to create an instance from snapshot or a source database respectively:

var vpc vpc

var sourceInstance databaseInstance

rds.NewDatabaseInstanceFromSnapshot(this, jsii.String("Instance"), &DatabaseInstanceFromSnapshotProps{
	SnapshotIdentifier: jsii.String("my-snapshot"),
	Engine: rds.DatabaseInstanceEngine_Postgres(&PostgresInstanceEngineProps{
		Version: rds.PostgresEngineVersion_VER_12_3(),
	}),
	// optional, defaults to m5.large
	InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE2, ec2.InstanceSize_LARGE),
	Vpc: Vpc,
})
rds.NewDatabaseInstanceReadReplica(this, jsii.String("ReadReplica"), &DatabaseInstanceReadReplicaProps{
	SourceDatabaseInstance: sourceInstance,
	InstanceType: 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 (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
parameterGroup := rds.NewParameterGroup(this, jsii.String("ParameterGroup"), &ParameterGroupProps{
	Engine: rds.DatabaseInstanceEngine_OracleSe2(&OracleSe2InstanceEngineProps{
		Version: rds.OracleEngineVersion_VER_19_0_0_0_2020_04_R1(),
	}),
	Parameters: map[string]*string{
		"open_cursors": jsii.String("2500"),
	},
})

optionGroup := rds.NewOptionGroup(this, jsii.String("OptionGroup"), &OptionGroupProps{
	Engine: rds.DatabaseInstanceEngine_*OracleSe2(&OracleSe2InstanceEngineProps{
		Version: rds.OracleEngineVersion_VER_19_0_0_0_2020_04_R1(),
	}),
	Configurations: []optionConfiguration{
		&optionConfiguration{
			Name: jsii.String("LOCATOR"),
		},
		&optionConfiguration{
			Name: jsii.String("OEM"),
			Port: jsii.Number(1158),
			Vpc: *Vpc,
		},
	},
})

// Allow connections to OEM
optionGroup.OptionConnections.oEM.Connections.AllowDefaultPortFromAnyIpv4()

// Database instance with production values
instance := rds.NewDatabaseInstance(this, jsii.String("Instance"), &DatabaseInstanceProps{
	Engine: rds.DatabaseInstanceEngine_*OracleSe2(&OracleSe2InstanceEngineProps{
		Version: rds.OracleEngineVersion_VER_19_0_0_0_2020_04_R1(),
	}),
	LicenseModel: rds.LicenseModel_BRING_YOUR_OWN_LICENSE,
	InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE3, ec2.InstanceSize_MEDIUM),
	MultiAz: jsii.Boolean(true),
	StorageType: rds.StorageType_IO1,
	Credentials: rds.Credentials_FromUsername(jsii.String("syscdk")),
	Vpc: Vpc,
	DatabaseName: jsii.String("ORCL"),
	StorageEncrypted: jsii.Boolean(true),
	BackupRetention: cdk.Duration_Days(jsii.Number(7)),
	MonitoringInterval: cdk.Duration_Seconds(jsii.Number(60)),
	EnablePerformanceInsights: jsii.Boolean(true),
	CloudwatchLogsExports: []*string{
		jsii.String("trace"),
		jsii.String("audit"),
		jsii.String("alert"),
		jsii.String("listener"),
	},
	CloudwatchLogsRetention: logs.RetentionDays_ONE_MONTH,
	AutoMinorVersionUpgrade: jsii.Boolean(true),
	 // required to be true if LOCATOR is used in the option group
	OptionGroup: OptionGroup,
	ParameterGroup: ParameterGroup,
	RemovalPolicy: awscdk.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
cloudwatch.NewAlarm(this, jsii.String("HighCPU"), &AlarmProps{
	Metric: instance.metricCPUUtilization(),
	Threshold: jsii.Number(90),
	EvaluationPeriods: jsii.Number(1),
})

// Trigger Lambda function on instance availability events
fn := lambda.NewFunction(this, jsii.String("Function"), &FunctionProps{
	Code: lambda.Code_FromInline(jsii.String("exports.handler = (event) => console.log(event);")),
	Handler: jsii.String("index.handler"),
	Runtime: lambda.Runtime_NODEJS_14_X(),
})

availabilityRule := instance.OnEvent(jsii.String("Availability"), &OnEventOptions{
	Target: targets.NewLambdaFunction(fn),
})
availabilityRule.AddEventPattern(&EventPattern{
	Detail: map[string]interface{}{
		"EventCategories": []interface{}{
			jsii.String("availability"),
		},
	},
})

Add XMLDB and OEM with option group

// Set open cursors with parameter group
parameterGroup := rds.NewParameterGroup(this, jsii.String("ParameterGroup"), &ParameterGroupProps{
	Engine: rds.DatabaseInstanceEngine_OracleSe2(&OracleSe2InstanceEngineProps{
		Version: rds.OracleEngineVersion_VER_19_0_0_0_2020_04_R1(),
	}),
	Parameters: map[string]*string{
		"open_cursors": jsii.String("2500"),
	},
})

optionGroup := rds.NewOptionGroup(this, jsii.String("OptionGroup"), &OptionGroupProps{
	Engine: rds.DatabaseInstanceEngine_*OracleSe2(&OracleSe2InstanceEngineProps{
		Version: rds.OracleEngineVersion_VER_19_0_0_0_2020_04_R1(),
	}),
	Configurations: []optionConfiguration{
		&optionConfiguration{
			Name: jsii.String("LOCATOR"),
		},
		&optionConfiguration{
			Name: jsii.String("OEM"),
			Port: jsii.Number(1158),
			Vpc: *Vpc,
		},
	},
})

// Allow connections to OEM
optionGroup.OptionConnections.oEM.Connections.AllowDefaultPortFromAnyIpv4()

// Database instance with production values
instance := rds.NewDatabaseInstance(this, jsii.String("Instance"), &DatabaseInstanceProps{
	Engine: rds.DatabaseInstanceEngine_*OracleSe2(&OracleSe2InstanceEngineProps{
		Version: rds.OracleEngineVersion_VER_19_0_0_0_2020_04_R1(),
	}),
	LicenseModel: rds.LicenseModel_BRING_YOUR_OWN_LICENSE,
	InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE3, ec2.InstanceSize_MEDIUM),
	MultiAz: jsii.Boolean(true),
	StorageType: rds.StorageType_IO1,
	Credentials: rds.Credentials_FromUsername(jsii.String("syscdk")),
	Vpc: Vpc,
	DatabaseName: jsii.String("ORCL"),
	StorageEncrypted: jsii.Boolean(true),
	BackupRetention: cdk.Duration_Days(jsii.Number(7)),
	MonitoringInterval: cdk.Duration_Seconds(jsii.Number(60)),
	EnablePerformanceInsights: jsii.Boolean(true),
	CloudwatchLogsExports: []*string{
		jsii.String("trace"),
		jsii.String("audit"),
		jsii.String("alert"),
		jsii.String("listener"),
	},
	CloudwatchLogsRetention: logs.RetentionDays_ONE_MONTH,
	AutoMinorVersionUpgrade: jsii.Boolean(true),
	 // required to be true if LOCATOR is used in the option group
	OptionGroup: OptionGroup,
	ParameterGroup: ParameterGroup,
	RemovalPolicy: awscdk.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
cloudwatch.NewAlarm(this, jsii.String("HighCPU"), &AlarmProps{
	Metric: instance.metricCPUUtilization(),
	Threshold: jsii.Number(90),
	EvaluationPeriods: jsii.Number(1),
})

// Trigger Lambda function on instance availability events
fn := lambda.NewFunction(this, jsii.String("Function"), &FunctionProps{
	Code: lambda.Code_FromInline(jsii.String("exports.handler = (event) => console.log(event);")),
	Handler: jsii.String("index.handler"),
	Runtime: lambda.Runtime_NODEJS_14_X(),
})

availabilityRule := instance.OnEvent(jsii.String("Availability"), &OnEventOptions{
	Target: targets.NewLambdaFunction(fn),
})
availabilityRule.AddEventPattern(&EventPattern{
	Detail: map[string]interface{}{
		"EventCategories": []interface{}{
			jsii.String("availability"),
		},
	},
})

Setting Public Accessibility

You can set public accessibility for the database instance or cluster 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 depends on vpcSubnets. It will be true if vpcSubnets is subnetType: SubnetType.PUBLIC, false otherwise.

var vpc vpc

// Setting public accessibility for DB instance
// Setting public accessibility for DB instance
rds.NewDatabaseInstance(this, jsii.String("Instance"), &DatabaseInstanceProps{
	Engine: rds.DatabaseInstanceEngine_Mysql(&MySqlInstanceEngineProps{
		Version: rds.MysqlEngineVersion_VER_8_0_19(),
	}),
	Vpc: Vpc,
	VpcSubnets: &SubnetSelection{
		SubnetType: ec2.SubnetType_PRIVATE_WITH_NAT,
	},
	PubliclyAccessible: jsii.Boolean(true),
})

// Setting public accessibility for DB cluster
// Setting public accessibility for DB cluster
rds.NewDatabaseCluster(this, jsii.String("DatabaseCluster"), &DatabaseClusterProps{
	Engine: rds.DatabaseClusterEngine_AURORA(),
	InstanceProps: &InstanceProps{
		Vpc: *Vpc,
		VpcSubnets: &SubnetSelection{
			SubnetType: ec2.SubnetType_PRIVATE_WITH_NAT,
		},
		PubliclyAccessible: jsii.Boolean(true),
	},
})

Instance events

To define Amazon CloudWatch event rules for database instances, use the onEvent method:

var instance databaseInstance
var fn function

rule := instance.OnEvent(jsii.String("InstanceEvent"), &OnEventOptions{
	Target: targets.NewLambdaFunction(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.

var vpc vpc

engine := rds.DatabaseInstanceEngine_Postgres(&PostgresInstanceEngineProps{
	Version: rds.PostgresEngineVersion_VER_12_3(),
})
rds.NewDatabaseInstance(this, jsii.String("InstanceWithUsername"), &DatabaseInstanceProps{
	Engine: Engine,
	Vpc: Vpc,
	Credentials: rds.Credentials_FromGeneratedSecret(jsii.String("postgres")),
})

rds.NewDatabaseInstance(this, jsii.String("InstanceWithUsernameAndPassword"), &DatabaseInstanceProps{
	Engine: Engine,
	Vpc: Vpc,
	Credentials: rds.Credentials_FromPassword(jsii.String("postgres"), awscdk.SecretValue_SsmSecure(jsii.String("/dbPassword"), jsii.String("1"))),
})

mySecret := secretsmanager.Secret_FromSecretName(this, jsii.String("DBSecret"), jsii.String("myDBLoginInfo"))
rds.NewDatabaseInstance(this, jsii.String("InstanceWithSecretLogin"), &DatabaseInstanceProps{
	Engine: Engine,
	Vpc: Vpc,
	Credentials: rds.Credentials_FromSecret(mySecret),
})

Secrets generated by fromGeneratedSecret() can be customized:

var vpc vpc

engine := rds.DatabaseInstanceEngine_Postgres(&PostgresInstanceEngineProps{
	Version: rds.PostgresEngineVersion_VER_12_3(),
})
myKey := kms.NewKey(this, jsii.String("MyKey"))

rds.NewDatabaseInstance(this, jsii.String("InstanceWithCustomizedSecret"), &DatabaseInstanceProps{
	Engine: Engine,
	Vpc: Vpc,
	Credentials: rds.Credentials_FromGeneratedSecret(jsii.String("postgres"), &CredentialsBaseOptions{
		SecretName: jsii.String("my-cool-name"),
		EncryptionKey: myKey,
		ExcludeCharacters: jsii.String("!&*^#@()"),
		ReplicaRegions: []replicaRegion{
			&replicaRegion{
				Region: jsii.String("eu-west-1"),
			},
			&replicaRegion{
				Region: jsii.String("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().

var vpc vpc

engine := rds.DatabaseInstanceEngine_Postgres(&PostgresInstanceEngineProps{
	Version: rds.PostgresEngineVersion_VER_12_3(),
})
myKey := kms.NewKey(this, jsii.String("MyKey"))

rds.NewDatabaseInstanceFromSnapshot(this, jsii.String("InstanceFromSnapshotWithCustomizedSecret"), &DatabaseInstanceFromSnapshotProps{
	Engine: Engine,
	Vpc: Vpc,
	SnapshotIdentifier: jsii.String("mySnapshot"),
	Credentials: rds.SnapshotCredentials_FromGeneratedSecret(jsii.String("username"), &SnapshotCredentialsFromGeneratedPasswordOptions{
		EncryptionKey: myKey,
		ExcludeCharacters: jsii.String("!&*^#@()"),
		ReplicaRegions: []replicaRegion{
			&replicaRegion{
				Region: jsii.String("eu-west-1"),
			},
			&replicaRegion{
				Region: jsii.String("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:

var cluster databaseCluster

cluster.Connections.AllowFromAnyIpv4(ec2.Port_AllTraffic(), jsii.String("Open to the world"))

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

var cluster databaseCluster

writeAddress := cluster.ClusterEndpoint.SocketAddress

For an instance database:

var instance databaseInstance

address := instance.InstanceEndpoint.SocketAddress

Rotating credentials

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

import cdk "github.com/aws/aws-cdk-go/awscdk"

var instance databaseInstance

instance.addRotationSingleUser(&RotationSingleUserOptions{
	AutomaticallyAfter: cdk.Duration_Days(jsii.Number(7)),
	 // defaults to 30 days
	ExcludeCharacters: jsii.String("!@#$%^&*"),
})
cluster := rds.NewDatabaseCluster(stack, jsii.String("Database"), &DatabaseClusterProps{
	Engine: rds.DatabaseClusterEngine_AURORA(),
	InstanceProps: &InstanceProps{
		InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE3, ec2.InstanceSize_SMALL),
		Vpc: *Vpc,
	},
})

cluster.addRotationSingleUser()

The multi user rotation scheme is also available:

var instance databaseInstance
var myImportedSecret databaseSecret

instance.addRotationMultiUser(jsii.String("MyUser"), &RotationMultiUserOptions{
	Secret: myImportedSecret,
})

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

var instance databaseInstance

myUserSecret := rds.NewDatabaseSecret(this, jsii.String("MyUserSecret"), &DatabaseSecretProps{
	Username: jsii.String("myuser"),
	SecretName: jsii.String("my-user-secret"),
	 // optional, defaults to a CloudFormation-generated name
	MasterSecret: instance.Secret,
	ExcludeCharacters: jsii.String("{}[]()'\"/\\"),
})
myUserSecretAttached := myUserSecret.attach(instance) // Adds DB connections information in the secret

instance.addRotationMultiUser(jsii.String("MyUser"), &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:

var instance databaseInstance
var myEndpoint interfaceVpcEndpoint


instance.addRotationSingleUser(&RotationSingleUserOptions{
	VpcSubnets: &SubnetSelection{
		SubnetType: ec2.SubnetType_PRIVATE_WITH_NAT,
	},
	 // Place rotation Lambda in private subnets
	Endpoint: myEndpoint,
})

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

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.

Note: grantConnect() does not currently work - see this GitHub issue.

The following example shows enabling IAM authentication for a database instance and granting connection access to an IAM role.

var vpc vpc

instance := rds.NewDatabaseInstance(this, jsii.String("Instance"), &DatabaseInstanceProps{
	Engine: rds.DatabaseInstanceEngine_Mysql(&MySqlInstanceEngineProps{
		Version: rds.MysqlEngineVersion_VER_8_0_19(),
	}),
	Vpc: Vpc,
	IamAuthentication: jsii.Boolean(true),
})
role := iam.NewRole(this, jsii.String("DBRole"), &RoleProps{
	AssumedBy: iam.NewAccountPrincipal(this.Account),
})
instance.GrantConnect(role)

The following example shows granting connection access for RDS Proxy to an IAM role.

var vpc vpc

cluster := rds.NewDatabaseCluster(this, jsii.String("Database"), &DatabaseClusterProps{
	Engine: rds.DatabaseClusterEngine_AURORA(),
	InstanceProps: &InstanceProps{
		Vpc: *Vpc,
	},
})

proxy := rds.NewDatabaseProxy(this, jsii.String("Proxy"), &DatabaseProxyProps{
	ProxyTarget: rds.ProxyTarget_FromCluster(cluster),
	Secrets: []iSecret{
		cluster.Secret,
	},
	Vpc: Vpc,
})

role := iam.NewRole(this, jsii.String("DBProxyRole"), &RoleProps{
	AssumedBy: iam.NewAccountPrincipal(this.Account),
})
proxy.GrantConnect(role, jsii.String("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.

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.

var vpc vpc

role := iam.NewRole(this, jsii.String("RDSDirectoryServicesRole"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("rds.amazonaws.com")),
	ManagedPolicies: []iManagedPolicy{
		iam.ManagedPolicy_FromAwsManagedPolicyName(jsii.String("service-role/AmazonRDSDirectoryServiceAccess")),
	},
})
instance := rds.NewDatabaseInstance(this, jsii.String("Instance"), &DatabaseInstanceProps{
	Engine: rds.DatabaseInstanceEngine_Mysql(&MySqlInstanceEngineProps{
		Version: rds.MysqlEngineVersion_VER_8_0_19(),
	}),
	Vpc: Vpc,
	Domain: jsii.String("d-????????"),
	 // The ID of the domain for the instance to join.
	DomainRole: 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, 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)
var instance databaseInstance

// Average CPU utilization over 5 minutes
var cluster databaseCluster

dbConnections := instance.metricDatabaseConnections()
cpuUtilization := cluster.metricCPUUtilization()

// The average amount of time taken per disk I/O operation (average over 1 minute)
readLatency := instance.metric(jsii.String("ReadLatency"), &MetricOptions{
	Statistic: jsii.String("Average"),
	Period: awscdk.Duration_Seconds(jsii.Number(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.

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 -

import "github.com/aws/aws-cdk-go/awscdk"

var vpc vpc

importBucket := s3.NewBucket(this, jsii.String("importbucket"))
exportBucket := s3.NewBucket(this, jsii.String("exportbucket"))
rds.NewDatabaseCluster(this, jsii.String("dbcluster"), &DatabaseClusterProps{
	Engine: rds.DatabaseClusterEngine_AURORA(),
	InstanceProps: &InstanceProps{
		Vpc: *Vpc,
	},
	S3ImportBuckets: []iBucket{
		importBucket,
	},
	S3ExportBuckets: []*iBucket{
		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

The following code configures an RDS Proxy for a DatabaseInstance.

var vpc vpc
var securityGroup securityGroup
var secrets []secret
var dbInstance databaseInstance


proxy := dbInstance.AddProxy(jsii.String("proxy"), &DatabaseProxyOptions{
	BorrowTimeout: awscdk.Duration_Seconds(jsii.Number(30)),
	MaxConnectionsPercent: jsii.Number(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.

import logs "github.com/aws/aws-cdk-go/awscdk"
var myLogsPublishingRole role
var vpc vpc


// Exporting logs from a cluster
cluster := rds.NewDatabaseCluster(this, jsii.String("Database"), &DatabaseClusterProps{
	Engine: rds.DatabaseClusterEngine_Aurora(&AuroraClusterEngineProps{
		Version: rds.AuroraEngineVersion_VER_1_17_9(),
	}),
	InstanceProps: &InstanceProps{
		Vpc: *Vpc,
	},
	CloudwatchLogsExports: []*string{
		jsii.String("error"),
		jsii.String("general"),
		jsii.String("slowquery"),
		jsii.String("audit"),
	},
	 // Export all available MySQL-based logs
	CloudwatchLogsRetention: logs.RetentionDays_THREE_MONTHS,
	 // Optional - default is to never expire logs
	CloudwatchLogsRetentionRole: myLogsPublishingRole,
})

// Exporting logs from an instance
instance := rds.NewDatabaseInstance(this, jsii.String("Instance"), &DatabaseInstanceProps{
	Engine: rds.DatabaseInstanceEngine_Postgres(&PostgresInstanceEngineProps{
		Version: rds.PostgresEngineVersion_VER_12_3(),
	}),
	Vpc: Vpc,
	CloudwatchLogsExports: []*string{
		jsii.String("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.

var vpc vpc
var securityGroup securityGroup


rds.NewOptionGroup(this, jsii.String("Options"), &OptionGroupProps{
	Engine: rds.DatabaseInstanceEngine_OracleSe2(&OracleSe2InstanceEngineProps{
		Version: rds.OracleEngineVersion_VER_19(),
	}),
	Configurations: []optionConfiguration{
		&optionConfiguration{
			Name: jsii.String("OEM"),
			Port: jsii.Number(5500),
			Vpc: *Vpc,
			SecurityGroups: []iSecurityGroup{
				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:

var vpc vpc


parameterGroup := rds.NewParameterGroup(this, jsii.String("ParameterGroup"), &ParameterGroupProps{
	Engine: rds.DatabaseInstanceEngine_SqlServerEe(&SqlServerEeInstanceEngineProps{
		Version: rds.SqlServerEngineVersion_VER_11(),
	}),
	Parameters: map[string]*string{
		"locks": jsii.String("100"),
	},
})

rds.NewDatabaseInstance(this, jsii.String("Database"), &DatabaseInstanceProps{
	Engine: rds.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:

var vpc vpc


rds.NewDatabaseInstance(this, jsii.String("Database"), &DatabaseInstanceProps{
	Engine: rds.DatabaseInstanceEngine_SqlServerEe(&SqlServerEeInstanceEngineProps{
		Version: rds.SqlServerEngineVersion_VER_11(),
	}),
	Vpc: Vpc,
	Parameters: map[string]*string{
		"locks": jsii.String("100"),
	},
})

You cannot specify a parameter map and a parameter group at the same time.

Serverless

Amazon Aurora Serverless 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 PostgreSql cluster. Aurora Serverless clusters can specify scaling properties which will be used to automatically scale the database cluster seamlessly based on the workload.

var vpc vpc


cluster := rds.NewServerlessCluster(this, jsii.String("AnotherCluster"), &ServerlessClusterProps{
	Engine: rds.DatabaseClusterEngine_AURORA_POSTGRESQL(),
	ParameterGroup: rds.ParameterGroup_FromParameterGroupName(this, jsii.String("ParameterGroup"), jsii.String("default.aurora-postgresql10")),
	Vpc: Vpc,
	Scaling: &ServerlessScalingOptions{
		AutoPause: awscdk.Duration_Minutes(jsii.Number(10)),
		 // default is to pause after 5 minutes of idle time
		MinCapacity: rds.AuroraCapacityUnit_ACU_8,
		 // default is 2 Aurora capacity units (ACUs)
		MaxCapacity: rds.AuroraCapacityUnit_ACU_32,
	},
})

Aurora Serverless Clusters do not support the following features:

  • Loading data from an Amazon S3 bucket
  • Saving data to an Amazon S3 bucket
  • Invoking an AWS Lambda function with an Aurora MySQL native function
  • Aurora replicas
  • Backtracking
  • Multi-master clusters
  • Database cloning
  • IAM database cloning
  • IAM database authentication
  • Restoring a snapshot from MySQL DB instance
  • Performance Insights
  • RDS Proxy

Read more about the limitations of Aurora Serverless

Learn more about using Amazon Aurora Serverless by reading the documentation

Use ServerlessClusterFromSnapshot to create a serverless cluster from a snapshot:

var vpc vpc

rds.NewServerlessClusterFromSnapshot(this, jsii.String("Cluster"), &ServerlessClusterFromSnapshotProps{
	Engine: rds.DatabaseClusterEngine_AURORA_MYSQL(),
	Vpc: Vpc,
	SnapshotIdentifier: jsii.String("mySnapshot"),
})

Data API

You 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.

var vpc vpc

var code code


cluster := rds.NewServerlessCluster(this, jsii.String("AnotherCluster"), &ServerlessClusterProps{
	Engine: rds.DatabaseClusterEngine_AURORA_MYSQL(),
	Vpc: Vpc,
	 // this parameter is optional for serverless Clusters
	EnableDataApi: jsii.Boolean(true),
})
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_14_X(),
	Handler: jsii.String("index.handler"),
	Code: Code,
	Environment: map[string]*string{
		"CLUSTER_ARN": cluster.clusterArn,
		"SECRET_ARN": cluster.secret.secretArn,
	},
})
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.