log
Swift Code Chronicles

Create an Aurora PostgreSQL Database Cluster Using AWS CDK

Published on January 19, 2025
Updated on January 19, 2025
18 min read
AWS

In this article, we will demonstrate how to set up a highly scalable Aurora PostgreSQL database cluster using AWS CDK. This implementation incorporates modern best practices such as Serverless v2 instances and Secrets Manager to enhance security and efficiency.


Prerequisites

Before you begin, ensure the following:

  1. A VPC has been created.
  2. Isolated subnets and an isolated security group have been created.

CDK Code

Below is the example code for the CDK stack.

import * as cdk from 'aws-cdk-lib';
import { SecurityGroup } from 'aws-cdk-lib/aws-ec2';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import {
  AuroraPostgresEngineVersion,
  ClusterInstance,
  Credentials,
  DatabaseCluster,
  DatabaseClusterEngine,
  SubnetGroup,
} from 'aws-cdk-lib/aws-rds';
import { Secret } from 'aws-cdk-lib/aws-secretsmanager';
import { Construct } from 'constructs';

export class RDSStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // VPC ID
    const vpcId = 'xxx';

    // Isolated Security Group ID
    const isolatedSecurityGroupId = 'xxx';

    // -------------------------------------------

    // Retrieve VPC
    const vpc = ec2.Vpc.fromLookup(this, 'VPC', { vpcId: vpcId });

    const rdsSubnetGroup = new SubnetGroup(this, `rds-subnet-group`, {
      vpc: vpc,
      vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED },
      description: 'Subnet group for RDS',
    });

    // Retrieve RDS security group
    const rdsSecurityGroup = SecurityGroup.fromLookupById(this, `rds-sg`, isolatedSecurityGroupId);

    // Create a secret for RDS
    const dbSecret = new Secret(this, `rds-secret`, {
      secretName: `<SECRET_NAME>`,
      generateSecretString: {
        secretStringTemplate: JSON.stringify({ username: 'postgres' }),
        generateStringKey: 'password',
        passwordLength: 10, // Length of the generated password
        excludeCharacters: '"@/$&:{}()[]+*=^-|', // Special characters to exclude
      },
    });

    // Create RDS cluster
    new DatabaseCluster(this, `db-cluster`, {
      engine: DatabaseClusterEngine.auroraPostgres({ version: AuroraPostgresEngineVersion.VER_17_2 }), // Aurora PostgreSQL 17.2
      clusterIdentifier: `db-cluster`,
      defaultDatabaseName: '<DATABASE_NAME>',
      vpc: vpc,
      vpcSubnets: vpc.selectSubnets({ subnetType: ec2.SubnetType.PRIVATE_ISOLATED }),
      serverlessV2MinCapacity: 0.5,
      serverlessV2MaxCapacity: 64,
      backup: { retention: cdk.Duration.days(7) }, // Retain backups for 7 days
      credentials: Credentials.fromSecret(dbSecret),
      subnetGroup: rdsSubnetGroup,
      securityGroups: [rdsSecurityGroup],
      storageEncrypted: true, // Enable encryption
      writer: ClusterInstance.serverlessV2(`db-instance-1`, {
        autoMinorVersionUpgrade: false,
        instanceIdentifier: `db-instance-1`,
        enablePerformanceInsights: false,
        publiclyAccessible: false,
      }),
      readers: [
        ClusterInstance.serverlessV2(`db-instance-2`, {
          autoMinorVersionUpgrade: false,
          instanceIdentifier: `db-instance-2`,
          enablePerformanceInsights: false,
          publiclyAccessible: false,
        }),
      ],
    });
  }
}

まとめ

This article explained how to configure an Aurora PostgreSQL database cluster using AWS CDK. By leveraging Serverless v2, you can achieve an efficient, scalable, and secure database solution. For further customization options, refer to the AWS CDK RDS Documentation.

About

A personal blog sharing technical insights, experiences and thoughts

Quick Links

Contact

  • Email: hushukang_blog@proton.me
  • GitHub

© 2025 Swift Code Chronicles. All rights reserved