Building an Echo Lambda with AWS CDK and CloudShell

2024-11-29

Introduction

AWS CloudShell comes with CDK pre-installed, making it an ideal environment for quick serverless deployments. Let's build an Echo Lambda function that randomly responds with light or dark echoes.

Project Setup

First, check CDK version and create project structure:

cdk --version  # Verify installed version
mkdir -p ~/echo-cdk-tutorial/lib && cd ~/echo-cdk-tutorial
npm init -y
npm install aws-cdk-lib@2.158.0  # Pin to CloudShell version

Create necessary files:

touch cdk.json lib/echo-stack.js lib/Dockerfile lib/echo.js

Configuration Files

cdk.json:

{
  "app": "node lib/echo-stack.js"
}

lib/echo-stack.js:

const { App, Stack } = require('aws-cdk-lib');
const { DockerImageFunction, DockerImageCode } = require('aws-cdk-lib/aws-lambda');
const path = require('path');

const app = new App();

class EchoStack extends Stack {
  constructor(scope, id, props) {
    super(scope, id, props);
    
    const dockerfileDir = path.join(__dirname);
    new DockerImageFunction(this, 'EchoFunction', {
      code: DockerImageCode.fromImageAsset(dockerfileDir),
      functionName: 'EchoFunction',
    });
  }
}

new EchoStack(app, 'EchoStack');

Create Dockerfile:

echo "FROM public.ecr.aws/lambda/nodejs:20
COPY echo.js \${LAMBDA_TASK_ROOT}
CMD [ \"echo.handler\" ]" > lib/Dockerfile

Lambda function (lib/echo.js):

exports.handler = async (event) => {
  const message = (event.body ? JSON.parse(event.body).message :
    event.message ||
    event.queryStringParameters?.message ||
    event || '').trim().toLowerCase();
    
  const response = message === 'echo'
    ? Math.random() < 0.5 ? '🌑 dark ECHO' : '💡 light ECHO'
    : `You said: ${message}. Say 'echo' to play the tunnel game!`;

  return {
    statusCode: 200,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ message: response })
  };
};

Deployment

Set region and deploy:

export AWS_DEFAULT_REGION=us-east-1
cdk synth
cdk deploy --require-approval never

Testing

Test regular message:

aws lambda invoke \
  --function-name EchoFunction \
  --cli-binary-format raw-in-base64-out \
  --payload '{"message":"hello"}' \
  response.json

cat response.json

Play the echo game:

aws lambda invoke \
  --function-name EchoFunction \
  --cli-binary-format raw-in-base64-out \
  --payload '{"message":"echo"}' \
  response.json

cat response.json

Cleanup

Remove all resources:

cdk destroy --force
cd ~ && rm -rf ~/echo-cdk-tutorial

Key Points