AWS CDK And TS -The Basic (Update to cdk v2)

Yanai Edri
7 min readJun 21, 2022
Image by Rainer Maiores from Pixabay

Although the AWS CDK docs for Typescript are very good — I filled that I need a basic tutorial on how to use the basic functionality of the CDK.
In this article, you can learn How to use AWS CDK (Cloud Development Kit) and how to create a basic CRUD app.

But first, What is CDK ? from AWS formal site :

The AWS Cloud Development Kit (AWS CDK) is an open-source software development framework to define your cloud application resources using familiar programming languages.
using familiar programming languages like phyton, java, C#, Typescript/JavaScript — I will use typescript in this tutorial.

In the next few sections, we will learn the basics of creating and deploying our awesome Todo app — with AWS Dynamodb, API-GW, Lambda functions, and S3 bucket.

So let’s start — first we need to install the AWS CDK from NPM and verified it:

npm install -g aws-cdk
cdk — version

Update: in CDK version 2- you need to install

npm install aws-cdk-lib 
npm install constructs

and all the sub-libs that are shown in this article are already in aws-cdk-lib
and all the code stay like v1 , for example :

// for v1
import * as lambda from “@aws-cdk/aws-lambda”;
// for v2
import {lambda} from “aws-cdk-lib/aws-lambda”;

And you’re ready to go !!! let’s create a folder and in this folder, we can initialize the CDK in this command:

cdk init {TEMPLATE} — language {LANGUAGE}

The Template by default is “app” — we have three options for the template:

app: Template for a CDK Application
lib: Template for a CDK Construct Library
sample-app: Example CDK Application with some constructs

now, we will run this command:

 cdk init sample-app — language=typescript

This will create us some files and folders to start with — we will focus at :

Bin — is the entry point for the CDK, in this file we initialize our instructions.
Lib — is Where the stack lives — there all the main functionality happens — all the instructions and the privileges are managed.

If we write the stack (the logic command for execute ) with TS — we don’t need to build and generate the JS files, only if we use lambda functions- this function will execute in the node environment at AWS therefore we need to generate the JS files — with the command:

npm run build

Else we can deploy the stack -

cdk deploy

We can create a different stack for different environments and run the specific deployment.
The entry point file in the app is located in the bin folder — in our example:
serverless.ts
In this file we create the app base on the CDK class — and create the stack :

Where we creating the stack we can create different stacks with parameters like that:

And with the deploy command, we can run

cdk deploy {prod-cdk | staging-cdk}

The parameters will be passed to the stack file located in the lib folder- serverless-stack.ts
Because we use TS — we need to extend the stack to recognize the parameters :

To simplify the flow — all our code will run inside the constructor function.
Let's do some base config -

UPDATE: in cdk v2- the scope get the interface from the packge ‘constructs’- and not from `cdk.Constructs`

First lambda function:

To start with the lambda function we need to install the
@aws-cdk/aws-lambda
package and import it-

 import * as lambda from “@aws-cdk/aws-lambda”;

And now we can our serverless function — all the lambda functions will sit in lambda folder — and will export with handler

This function will return the string “hello from lambda” when executing…
In the stack we can also pass parameters to the function — let's define the lambada function in the stack:

(*all the `this` keywords that pass as the first argument in the function’s referrer to the current stack.)

Be aware that the handler gets the file name — hello + the export handler.
In this function, we declare the run time engine, we pass parameters to the lambda function via the environment.

To create API get-way — we need to install and import :

import * as apiGw from “@aws-cdk/aws-apigateway”;
import { AuthorizationType } from ‘@aws-cdk/aws-apigateway’;

In our case, we will create an API with allows CORS

we are creating the API in three steps:

1. we are creating a new Rest API — with CORS allowed
2. we are binding the API handler with the lambda function
3. we are creating the entry point — in this case, a method is ‘GET’ in the ‘/hello’ entry

Let's create our database now…

Dynamodb

To get access to the Dynamodb database we need to install and import

import * as dynamodb from “@aws-cdk/aws-dynamodb”;

for our example, we create a TODOs database –

In this table, we created the partitionKey that is required for indexing.

the table name — we configured in the config step.

billing mode — supports two billing modes:
1- PROVISIONED — the default mode where the table and global secondary indexes have configured read and write capacity.
2-PAY_PER_REQUEST — on-demand pricing and scaling. You only pay for what you use and there is no read and write capacity for the table or its global secondary indexes.

ReadCapacity — in KB

Next step — we need a place to store our amazing app

S3 Bucket

First — import the package:

import * as s3 from “@aws-cdk/aws-s3”;

In this step we only create the bucket but to deploy our app to the bucket we need more steps:

import * as s3Deployment from “@aws-cdk/aws-s3-deployment”;
const path = require(“path”);
const appDir = path.join(__dirname, “path”, “to”, “my-project”);

The package s3Deployment gets in the second parameter the type of the bucket- in our case is a static website.

Well Done!! If You got here — you have the basic knowledge for the next — all our basic foundations are ready — let’s create the app backend — some of the CRUD actions.

Read from the database -

As we did before — we create the lambda function and then bind the function with the API-GW and the final step is to give the lambada permission to access the Dynamodb, the lambda function:

In the function we have access to AWS SDK — we are running in node env — the TABLE_NAME passing throw the function binding step (in environment props);
We are initializing the dynamo asset — and using it inside the lambda function a get all the todos data.

Finely return the HTTP request to the client.
let's see another example — to get specific todo and delete specific todo:
let’s start from the end — we are adding an entry resource under the
todosApi -this entry is dynamic and gets {id} of the todo item.

All the steps are similar to the last one we sow, let's see the delete lambada function

This code is very simple, the id we are getting from the pathParameters and delete the specific todo.
The last example we see is how to add todo — first the binding in the stack:

The function -

I expect here to the body will contain this object as a payload:

{ 
id,
task,
done
}

id is a string of timesteps, the task is a string, and done is Boolean
then with the put function, I insert the item into the Dynamodb.

summary

in this article, I tried to show the basics of the AWS CDK — and how you can start with,

in the next step, you can create a CloudFront that we are your entry for all the requests — and the s3 bucket can be private with no access, use Cognito to manage subscribers, use route 53 to enter a domain name, and a lot more.

Thanks For Reading.
Yanai.

--

--

Yanai Edri

Hi, I'm a web developer for more than 15 years, I believe in self-learning and a big fan of web technology. if something I wrote helped one person - worth it