Setting Up and Tearing Down Environments with the AWS CDK

1 hour
  • 6 Learning Objectives

About this Hands-on Lab

In this lab, we’ll use the Cloud9 service in AWS to work on our CDK project using a “blue/green” deployment. Our CDK project already consists of an API Gateway, backed by a Lambda function that can scan items on a DynamoDB table. We want to update our application and add a second Lambda function that can add items to our DynamoDB table. To do this, we’ll need to create a second “green” stack with an entirely separate API Gateway, Lambda function, and DynamoDB table. Once the “green” stack has been provisioned and tested, we can promote it to the “blue” stack and then destroy our unneeded infrastructure.

Learning Objectives

Successfully complete this lab by achieving the following learning objectives:

Create A Cloud9 Development Environment
From the Cloud9 Terminal, Pull the Code from the Provided GitHub Link and Deploy the “Blue” Stack
  • git clone https://github.com/DavidBlocher/cdk-lab-1.git
  • cd cdk-lab-1
  • npm install
Create a New “Green” Stack and Copy the Constructs from Your “Blue” Stack
In Your “Green” Stack, Create a New API Gateway Endpoint That Calls a New Lambda Function to Add Items to Your DynamoDB Table
import * as AWSXRay from 'aws-xray-sdk';
import * as AWSSDK from 'aws-sdk';
import { APIGatewayProxyEvent } from "aws-lambda";

//define DocumentClient
const AWS = AWSXRay.captureAWS(AWSSDK);
const docClient = new AWS.DynamoDB.DocumentClient();

//define table by variable passed from stack
const table = process.env.DYNAMODB || "undefined"

//putItems function uses params to scan a dynamodb table
async function putItem(){
  try {
    const data = await docClient.put(params).promise()
    return data
  } catch (err) {
    return err
  }
}

//actual handler logs events and calls scanItems
//logs error on catch
exports.handler = async (event:APIGatewayProxyEvent) => {
  try {
      console.log(event)
      console.log(event.body)
      const obj = JSON.parse(event.body)

      const ID = obj.id;
      const NAME = obj.name

      //define table and item in params
      const params = {
          TableName: table,
          Item: {
               id: {S: ID},
               name: {S: NAME}
          }
      };
    const data = await putItem(params)
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}
Deploy Your “Green” Stack and Verify Deployment
Once Your “Green” Stack Is Deployed, Tear Down Your “Blue” Stack

What are Hands-on Labs

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Sign In
Welcome Back!

Psst…this one if you’ve been moved to ACG!

Get Started
Who’s going to be learning?