Skip to main content

CDK Constructs for AWS RDS

Project description

Amazon Relational Database Service Construct Library


Stability: Experimental

This is a developer preview (public beta) module. Releases might lack important features and might have future breaking changes.

This API is still under active development and subject to non-backward compatible changes or removal in any future version. Use of the API is not recommended in production environments. Experimental APIs are not subject to the Semantic Versioning model.


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:

const cluster = new DatabaseCluster(this, 'Database', {
    engine: DatabaseClusterEngine.Aurora,
    masterUser: {
        username: 'admin'
    },
    instanceProps: {
        instanceType: new InstanceTypePair(InstanceClass.Burstable2, InstanceSize.Small),
        vpcSubnets: {
            subnetType: ec2.SubnetType.Public,
        },
        vpc
    }
});

By default, the master password will be generated and stored in AWS Secrets Manager.

Your cluster will be empty by default. To add a default database upon construction, specify the defaultDatabaseName attribute.

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:

const instance = new DatabaseInstance(stack, 'Instance', {
    engine: rds.DatabaseInstanceEngine.OracleSE1,
    instanceClass: new ec2.InstanceTypePair(ec2.InstanceClass.Burstable2, ec2.InstanceSize.Small),
    masterUsername: 'syscdk',
    vpc
});

By default, the master password will be generated and stored in AWS Secrets Manager.

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

new DatabaseInstanceFromSnapshot(stack, 'Instance', {
    snapshotIdentifier: 'my-snapshot',
    engine: rds.DatabaseInstanceEngine.Postgres,
    instanceClass: new ec2.InstanceTypePair(ec2.InstanceClass.Burstable2, ec2.InstanceSize.Large),
    vpc
});

new DatabaseInstanceReadReplica(stack, 'ReadReplica', {
    sourceDatabaseInstance: sourceInstance,
    engine: rds.DatabaseInstanceEngine.Postgres,
    instanceClass: new ec2.InstanceTypePair(ec2.InstanceClass.Burstable2, ec2.InstanceSize.Large),
    vpc
});

Creating a "production" Oracle database instance with option and parameter groups:

    // Set open cursors with parameter group
    const parameterGroup = new rds.ParameterGroup(this, 'ParameterGroup', {
      family: 'oracle-se1-11.2',
      parameters: {
        open_cursors: '2500'
      }
    });

Add XMLDB and OEM with option group

    const optionGroup = new rds.OptionGroup(this, 'OptionGroup', {
      engine: rds.DatabaseInstanceEngine.OracleSE1,
      majorEngineVersion: '11.2',
      configurations: [
        {
          name: 'XMLDB'
        },
        {
          name: 'OEM',
          port: 1158,
          vpc
        }
      ]
    });

    // Allow connections to OEM
    optionGroup.optionConnections.OEM.connections.allowDefaultPortFromAnyIpv4();

    // Database instance with production values
    const instance = new rds.DatabaseInstance(this, 'Instance', {
      engine: rds.DatabaseInstanceEngine.OracleSE1,
      licenseModel: rds.LicenseModel.BringYourOwnLicense,
      instanceClass: new ec2.InstanceTypePair(ec2.InstanceClass.Burstable2, ec2.InstanceSize.Medium),
      multiAz: true,
      storageType: rds.StorageType.IO1,
      masterUsername: 'syscdk',
      vpc,
      databaseName: 'ORCL',
      storageEncrypted: true,
      backupRetentionPeriod: 7,
      monitoringInterval: 60,
      enablePerformanceInsights: true,
      cloudwatchLogsExports: [
        'trace',
        'audit',
        'alert',
        'listener'
      ],
      cloudwatchLogsRetention: logs.RetentionDays.OneMonth,
      autoMinorVersionUpgrade: false,
      optionGroup,
      parameterGroup
    });

    // Allow connections on default port from any IPV4
    instance.connections.allowDefaultPortFromAnyIpv4();

    // Rotate the master user password every 30 days
    instance.addRotationSingleUser('Rotation');

    // Add alarm for high CPU
    new cloudwatch.Alarm(this, 'HighCPU', {
      metric: instance.metricCPUUtilization(),
      threshold: 90,
      evaluationPeriods: 1
    });

    // Trigger Lambda function on instance availability events
    const fn = new lambda.Function(this, 'Function', {
      code: lambda.Code.inline('exports.handler = (event) => console.log(event);'),
      handler: 'index.handler',
      runtime: lambda.Runtime.Nodejs810
    });

    const availabilityRule = instance.onEvent('Availability', { target: new targets.LambdaFunction(fn) });
    availabilityRule.addEventPattern({
      detail: {
        EventCategories: [
          'availability'
        ]
      }
    });

Instance events

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

const rule = instance.onEvent('InstanceEvent', { target: new targets.LambdaFunction(fn) });

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:

cluster.connections.allowFromAnyIpv4('Open to the world');

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

const writeAddress = cluster.clusterEndpoint.socketAddress;   // "HOSTNAME:PORT"

For an instance database:

const address = instance.instanceEndpoint.socketAddress;   // "HOSTNAME:PORT"

Rotating master password

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

const cluster = new rds.DatabaseCluster(stack, 'Database', {
  engine: rds.DatabaseClusterEngine.Aurora,
  masterUser: {
    username: 'admin'
  },
  instanceProps: {
    instanceType: new ec2.InstanceTypePair(ec2.InstanceClass.Burstable2, ec2.InstanceSize.Small),
    vpc
  }
});

cluster.addRotationSingleUser('Rotation');

Rotation of the master password is also supported for an existing cluster:

new SecretRotation(stack, 'Rotation', {
    secret: importedSecret,
    application: SecretRotationApplication.OracleRotationSingleUser
    target: importedCluster, // or importedInstance
    vpc: importedVpc,
})

The importedSecret must be a JSON string with the following format:

{
  "engine": "<required: database engine>",
  "host": "<required: instance host name>",
  "username": "<required: username>",
  "password": "<required: password>",
  "dbname": "<optional: database name>",
  "port": "<optional: if not specified, default port will be used>"
}

Metrics

Database instances expose metrics (cloudwatch.Metric):

// The number of database connections in use (average over 5 minutes)
const dbConnections = instance.metricDatabaseConnections();

// The average amount of time taken per disk I/O operation (average over 1 minute)
const readLatency = instance.metric('ReadLatency', { statistic: 'Average', periodSec: 60 });

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aws-cdk.aws-rds-0.35.0.tar.gz (197.2 kB view details)

Uploaded Source

Built Distribution

aws_cdk.aws_rds-0.35.0-py3-none-any.whl (197.1 kB view details)

Uploaded Python 3

File details

Details for the file aws-cdk.aws-rds-0.35.0.tar.gz.

File metadata

  • Download URL: aws-cdk.aws-rds-0.35.0.tar.gz
  • Upload date:
  • Size: 197.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.6.5

File hashes

Hashes for aws-cdk.aws-rds-0.35.0.tar.gz
Algorithm Hash digest
SHA256 040a6c6bbfbbfed75ae5716b69cb57c85cee423cd15603203107e68b520d8452
MD5 5f39ba074ac4f0801693b301330e3c34
BLAKE2b-256 68f8fba4a5a2cd298b94c87ba0c6d337d221d8eccf6420046c77fe95adadc741

See more details on using hashes here.

File details

Details for the file aws_cdk.aws_rds-0.35.0-py3-none-any.whl.

File metadata

  • Download URL: aws_cdk.aws_rds-0.35.0-py3-none-any.whl
  • Upload date:
  • Size: 197.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.6.5

File hashes

Hashes for aws_cdk.aws_rds-0.35.0-py3-none-any.whl
Algorithm Hash digest
SHA256 81f6ae72aaf35295fe9e79e4e0623396423d403e6ca3e200537d96d4f5e62d84
MD5 dc9bc6c2b8dd23d829994bcc3f70aaa5
BLAKE2b-256 c3da8ef3dfb38d1bcd2eadefc6e6fb99fcfa489b9ea8457c3774744ae69f8682

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page