AWS CDK — Cloud Candy Quick Start with Lambda Hello World

Dre May
6 min readMay 12, 2020

Background

If you are reading this, I don’t have to tell you about the popularity of AWS. AWS is everywhere. Cloud computing has infiltrated even the most mundane of back-office corporate environments. Some of the key questions are typically where to get started however. Training is typically done by utilizing the AWS Console (GUI), or is a mixture of CloudFormation scripts that you are simply told to “run”. AWS re:Invent has great instructional content; however, many sessions say run this CloudFormation, which is not a great way to get started.

Other cloud experts may be brought into your corporation that recommend other tools such as Terraform. Terraform can be its own little world as well, and if attempting to understand AWS for the first time, may not be the best place to start. Terraform in addition to CloudFormation, are domain specific markup that doesn’t necessarily “speak” to someone with a programming background.

Hopefully in this article I will outline another alternative to diving in and understanding AWS by utilizing the AWS CDK. The CDK is a cloud development kit that allows you to use popular programming languages to create AWS constructs. In this article, I will be using typescript; however, the general concepts can be applied to any language the CDK supports.

The output of the CDK is CloudFormation, the “native” way AWS utilizes Infrastructure as Code.

Isn’t the Console Easier?

To sign up for an AWS account, you have inevitably navigated into the AWS console. You may have even gone through many tutorials that utilize the console, or perhaps you are a seasoned expert still using the console. When I first started, I had a very specific task in mind related to a personal website. I found an online tutorial how to set things up, and when I was finished I felt I had jumped through a great learning hurdle. Unfortunately visiting back years later to the same process, I had no idea what I had done. There wasn’t really a concrete history of what I had used — no audit trail to be found.

I felt oddly disconnected from the process as well. There were infrastructure tools available at the time; however, when I looked at how to utilize them, it felt like I would be learning multiple things, and really AWS.

Getting Started

As mentioned before, this article will assume typescript usage when using the CDK. Typescript and the CDK will be installed through npm.

Step 1 — Ensure you have NPM installed.

Install NPM along with NodeJS. These are typically installed together. Visit the nodeJS site here.

Step 2 — Already Have NPM / Node? Time to Update

sudo npm install -g npm

Note, I’m running on a Mac, and I needed sudo. This may be optional for you.

Step 3 — Install TypeScript

sudo npm install -g typescript

to update use:

sudo npm update -g typescript

Step 4 — Install the CDK

sudo npm install -g cdk

Similar to above, if you already have it installed, you can run the npm update command.

Creating a new CDK project

Let’s start creating a new project. First create a new empty directory, and run the cdk init command:

mkdir intro1
cd intro1
cdk init --language typescript

Note, I had some issues after updating my CDK, and I needed to clean the npm cache. This worked for me; however, is noted here as a last resort:

npm cache clean --force

After a successful run, you should see a set of commands such as:

npm run build
npm run watch
npm run test
cdk deploy
cdk diff
cdk synth

CDK Default Enhancements

The CDK has some odd choices for the template files. Hopefully there is a way in the future to easily add your own templates. For now, I am going to make the following changes:

  • Change the source code to reside in a single directory (not lib and bin).
  • Change the output directory of the typescript compiler to not litter the current directories.
  • Add a clean phase to the build to accommodate the above changes.

Notice the screenshot after initial setup, with source in both bin and lib.

Source location tweaks

Start by creating a new folder called src within your test1 directory.

Now move the files from bin and lib into the src folder. You can delete the lib folder at this point. If using VSCode, the typescript files will be updated for you — otherwise, examine the imports below, as you may need to modify the typescript files.

The intro1.js file should have an import similar to below:

import { Intro1Stack } from './intro1-stack';

Within package.json, add the following to dev dependencies:

"devDependencies": {
"rimraf": "^3.0.1",

Rimraf will help clean out the build directory in an OS independent manner.

Within package.json, change the bin attribute as follows:

"bin": {
"intro1": "bin/src/intro1.js"
},

Next, within the same package.json, change the options that will be run:

"scripts": {
"rimraf": "./node_modules/rimraf/bin.js",
"clean": "rimraf bin/",
"build": "npm run clean && tsc -p ./",

Almost there, within tsconfig.json, add the following:

"compilerOptions": {
"outDir": "bin",

The important thing to note is the outDir. With that, JS and TS files won’t get cluttered together.

One final file to tweak, which is the cdk.json. Ensure the npx command is pointing to the correct location:

{
"app": "npx ts-node src/intro1.ts",

Notice the src directory above instead of bin.

Whew, Finally Running

OK, let’s run everything to make sure we are in business. Run the following commands:

npm run build
cdk synth

Build will transpile everything into the bin directory, and cdk synth will display what CloudFormation will be executed.

Bootstrapping your Account

Getting a brand new AWS account, with a user provisioned, and access keys is beyond the scope of this article. If you aren’t sure what those are, there are a lot of resources on how to create a new AWS user with programmatic access. Once you have that set, come back here. Running aws configure will get you started on the path of what you need.

Once you are set with aws configure, bootstrap the CDK into your account with:

cdk bootstrap

Lambda Hello World

At this stage the CDK is all set to go — but we have nothing inside of it. Let’s keep things as simple as possible, and add a lambda function that returns hello world.

Let’s add lambda and api-gateway:

npm install @aws-cdk/aws-apigateway
npm install @aws-sdk/lambda

Adding the Lambda Source

Add a resources directory, with the following JavaScript code (lambdatest.js):

const AWS = require('aws-sdk');
exports.main = async function(event, context) {
try {
var method = event.httpMethod;
if (method === "GET") {
if (event.path === "/") {
return {
statusCode: 200,
headers: {},
body: "Hello World!"
};
}
}
}
catch(error) {
var body = error.stack || JSON.stringify(error, null, 2);
return {
statusCode: 400,
headers: {},
body: JSON.stringify(body)
}
}
}

The CDK Infrastructure

Now we have created our lambda code under the resources directory, let’s tell the CDK to deploy it with the API Gateway.

Add the following typescript file under the src directory. (src/LambdaTest.ts)

import core = require("@aws-cdk/core");
import apigateway = require("@aws-cdk/aws-apigateway");
import lambda = require("@aws-cdk/aws-lambda");
export class LambdaTest extends core.Construct {
constructor(scope: core.Construct, id: string) {
super(scope, id);
const handler = new lambda.Function(this,
"LambdaTestHandler", {
runtime: lambda.Runtime.NODEJS_10_X,
code: lambda.Code.asset("resources"),
handler: "lambdatest.main"
});
const api = new apigateway.RestApi(this, "test-api", {
restApiName: "Lambda Test Service"
});
const apiIntegration =
new apigateway.LambdaIntegration(handler, {
requestTemplates: { "application/json":
'{ "statusCode": "200" }' }
});
api.root.addMethod("GET", apiIntegration);
}
}

Adding The CDK Function to the Stack

Inside your Intro1Stack class, you will notice a line about “add your code here”, which is created by the cdk init.

Add the following code to the Intro1Stack.ts:

// The code that defines your stack goes herenew myservice.LambdaTest(this, 'LambdaTest');

Deploy and Enjoy!

Run the following commands to deploy to your AWS account:

npm run build
cdk synth
cdk deploy

If everything went according to plan, you will have an output of a URL. Paste this in your browser and you will see the famous “Hello World”!

Cleaning Up

Make sure your run the following command to clean up the CloudFormation stack output by your CDK project:

cdk destroy

What We Have Done — Summary

Hopefully in this article I have shown that you don’t need to touch the AWS console to have an enjoyable coding experience and deploy AWS resources while working in a popular language such as typescript. There are always enhancements to be made such as crafting the lambda itself in typescript; however, that will need to come in another article.

--

--

Dre May

I love writing about all technology including JavaScript, Java, Swift, and Kotlin.