AWS Serverless Building AWS Stack for AWS aurora

Create infrastructure using AWS CDK

Write code once and create multiple environments with single code Create infrastructure using AWS CDK

Install AWS Client

Make sure you have installed “AWS Client” on your system if not you can use the following command to install

brew install awscli

once you have installed the AWS client to verify please type the following command on the terminal

aws configure

Then you will see the following prompt then input your AWS Access Key ID

for example:
AWS Access Key ID [None]: AKIAI44QH8DHBEXAMPLE

Once you hit enter/return then you will see the following prompt then you need to input AWS Secret Access Key

for example:
Secret Access Key [None]: je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY

Once you hit enter/return then you will see the following prompt then you need to input Default region name

for example:
Default region name [None]: ap-southeast-1

Once you hit enter/return then you will see the following prompt then you need to input Default output format

for example:
Default output format [None]: json

After that, you can .aws directory under your username as shown in the following screenshot

Note: .aws is a hidden directory

AWS CDK

AWS CDK is an open source framework for creating and managing AWS resources. By using languages familiar to the developer such as TypeScript or Python, the Infrastructure as Code is described. In doing so, CDK synthesizes the code into AWS Cloudformation Templates and can optionally deploy them right away.

AWS CDK has been experiencing a steady increase in enthusiastic developers since 2019 and already has a strong and helpful community that is very active on Slack, for example. There is of course much more to say about AWS CDK and I recommend you explore it. Drop me a line if you have any questions.

Developers use the CDK framework in one of the supported programming languages to define reusable cloud components called constructs, which are composed together into stacks, forming a "CDK app".

They then use the AWS CDK CLI to interact with their CDK app. The CLI allows developers to synthesize artifacts such as AWS CloudFormation Templates, deploy stacks to development AWS accounts and "diff" against a deployed stack to understand the impact of a code change.

The AWS Construct Library includes a module for each AWS service with constructs that offer rich APIs that encapsulate the details of how to use AWS. The AWS Construct Library aims to reduce the complexity and glue-logic required when integrating various AWS services to achieve your goals on AWS.

Modules in the AWS Construct Library are designated Experimental while we build them; experimental modules may have breaking API changes in any release. After a module is designated Stable, it adheres to semantic versioning, and only major releases can have breaking changes. Each module's stability designation is available on its Overview page in the AWS CDK API Reference. For more information, see Versioning in the CDK Developer Guide.

At a glance

Install or update the AWS CDK CLI from npm (requires Node.js ≥ 14.15.0). We recommend using a version in Active LTS

$ npm i -g aws-cdk

(See Manual Installation for installing the CDK from a signed .zip file).

Initialize a project:

$ mkdir hello-cdk
$ cd hello-cdk
$ cdk init sample-app --language=typescript

This creates a sample project looking like this:

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

    const queue = new sqs.Queue(this, 'HelloCdkQueue', {
      visibilityTimeout: cdk.Duration.seconds(300)
    });

    const topic = new sns.Topic(this, 'HelloCdkTopic');

    topic.addSubscription(new subs.SqsSubscription(queue));
  }
}

Deploy this to your account:

$ cdk deploy

lets play with AWS arora serverless RDS

Arora is not same as RDS on AWS

Unlike RDS and Aurora Clusters, Aurora Serverless does not have a public endpoint. In fact, according to the documentation, there is no way to choose if the cluster should be public. This means working with the Aurora Serverless cluster can only be accomplished by:

  • using a VPN into your VPC;
  • running your application code in a VPC which you have access to;
  • launching an EC2 instance and installing the MySQL client to work with the database; or

use the Aurora Web Data API.

  • The first three options should be fairly well understood, This article is going to present the Web Data API to interface with your Aurora Cluster. Before we dive in, what is Aurora Serverless anyway?

Aurora Serverless

Aurora Serverless is built upon Amazon Aurora, which is a “built for the cloud” relational database supporting both MySQL and PostgreSQL. These two highly popular open-source databases are used by enterprises around the world. Aurora’s custom design makes it significantly faster than standard MySQL and PostgreSQL databases. Amazon Aurora is a fully managed database, available as part of the Amazon Relational Database Service.

Aurora Serverless builds on these capabilities by providing a “database in the cloud”, where the capabilities of Amazon Aurora are allocated and automatically scaled based upon your application’s demand. There are no “servers” deployed in your infrastructure and no database capacity for you to monitor and manage. This makes Aurora Serverless ideal for many types of applications, especially those with a transient workload.

Install the AWS CDK Toolkit globally using the following Node Package Manager command.

npm install -g aws-cdk

Run the following command to verify the correct installation and print the version number of the AWS CDK.

cdk --version

Create a CDK App Create a new directory aurora-cdk using the following command

mkdir aurora-cdk && cd aurora-cdk

from the above command, we have created the aurora-cdk directory and we will create the CDK App using TypeScript

You need to initialize the app using the cdk init command, specifying the desired template (“app”) and programming language.

Example:

cdk init app --language typescript
Once the app successfully created it will show you the All Done! as shown below

Now you will see there are a file aurora-cdk.ts under bin directory

Above file contain an instance of the AuroraCdkStack the implementation of that class is under the lib folder as shown below

Before creating new Instance & VPN we will do some refactoring and Renaming.

bin -> aurora-cdk.ts
We renamed from (AuroraCdkStack)
import { AuroraCdkStack } from '../lib/aurora-cdk-stack';
To (AuroraSlsStack)

import { AuroraSlsStack } from '../lib/aurora-cdk-stack';
// We refactored to the following code.
#!/usr/bin/env node
import 'source-map-support/register';
import cdk = require('@aws-cdk/core');
import { Aws, Construct } from '@aws-cdk/core';
import { AuroraSlsStack } from '../lib/aurora-cdk-stack';

const deploymentStage = 'aurora-sls-dev';

const defaultEnv: cdk.Environment = {
  account: Aws.ACCOUNT_ID,
  region: 'ap-southeast-1',
};

const app = new cdk.App();
class AuroraCdkStack extends Construct {
    constructor(scope: Construct, id: string, env: cdk.Environment) {
      super(scope, id);
      new AuroraSlsStack(this, 'AuroraSlsStack', {env}, deploymentStage);
    }
}

new AuroraCdkStack(app, deploymentStage, defaultEnv);

First, before creating Aurora instance we will create a VPC.

We need to add aws-ec2 package dependency. try to run following command

npm install @aws-cdk/aws-ec2

and for Aurora, Serverless Instance run the following command

npm install @aws-cdk/aws-rds

Here is the final version of following file aurora-cdk-stack.ts

lib -> aurora-cdk-stack.ts
import { CfnOutput, Construct, Stack, StackProps } from '@aws-cdk/core';
import { Vpc, SubnetType } from '@aws-cdk/aws-ec2';
import { CfnDBCluster, CfnDBSubnetGroup } from '@aws-cdk/aws-rds';

export class AuroraSlsStack extends Stack {
  constructor(scope: Construct, id: string, props: StackProps, deploymentStage: string) {
    super(scope, id, props);
    // create vpc
    const vpc = new Vpc(this, 'Vpc', {
      cidr: '10.0.0.0/16',
      natGateways: 0,
      subnetConfiguration: [ 
        { name: 'aurora_isolated_', subnetType: SubnetType.ISOLATED }
      ]
    });

    // get subnetids from vpc
    const subnetIds: string[] = [];
    vpc.isolatedSubnets.forEach(subnet => {
      subnetIds.push(subnet.subnetId);
    });

  // output subnet ids
    new CfnOutput(this, 'VpcSubnetIds', {
      value: JSON.stringify(subnetIds)
    });

    // output security group
    new CfnOutput(this, 'VpcDefaultSecurityGroup', {
      value: vpc.vpcDefaultSecurityGroup
    });

    // create subnetgroup
    const dbSubnetGroup: CfnDBSubnetGroup = new CfnDBSubnetGroup(this, 'AuroraSubnetGroup', {
      dbSubnetGroupDescription: 'Subnet group to access aurora',
      dbSubnetGroupName: 'aurora-sls-subnet-group',
      subnetIds
    });

    // create aurora db serverless cluster 
    const aurora = new CfnDBCluster(this, 'AuroraServerlessCdk', {
      databaseName: 'dbname',
      dbClusterIdentifier: 'aurora-sls',
      engine: 'aurora',
      engineMode: 'serverless',
      masterUsername: 'masteruser',
      masterUserPassword: 'IT_IS_SMART_TO_GENERATE_AND_OUTPUT_THIS',
      port: 3306,
      dbSubnetGroupName: dbSubnetGroup.dbSubnetGroupName,
      scalingConfiguration: {
        autoPause: true,
        maxCapacity: 2,
        minCapacity: 2,
        secondsUntilAutoPause: 3600
      }
    });

    //wait for subnet group to be created
    aurora.addDependsOn(dbSubnetGroup);

    // construct arn from available information
    const account  = props.env?.account;
    const region = props.env?.region;
  
    const auroraArn = `arn:aws:rds:${region}:${account}:cluster:${aurora.dbClusterIdentifier}`;

    new CfnOutput(this, 'AuroraClusterArn', {
      exportName: `${deploymentStage}`,
      value: auroraArn
    }); 
  }
}

Build the App Try to run the following command.

npm run build

This will create compiled Javascript files as shown in the screenshots.

Then try to run following command

cdk synth

You will see it will return you the CloudFormation Template as shown below

Now, it’s time to Deploy the CDK Stack 🚀🚀🚀🚀 Try to run following command

cdk deploy

After successful deployment, it will show you the Output as shown below

Comments