You've already forked devops-exercises
2.7 KiB
2.7 KiB
Set up a CDK Project - Solution
Exercise
Initialize a CDK project and set up files required to build a CDK project.
Solution
Initialize a CDK project
- Install CDK on your machine by running
npm install -g aws-cdk. - Create a new directory named
samplefor your project and runcdk init app --language typescriptto initialize a CDK project. You can choose language as csharp, fsharp, go, java, javascript, python or typescript. - You would see the following files created in your directory:
cdk.json,tsconfig.json,package.json- These are configuration files that are used to define some global settings for your CDK project.bin/sample.ts- This is the entry point for your CDK project. This file is used to define the stack that you want to create.lib/sample-stack.ts- This is the main file that will contain the code for your CDK project.
Create a Sample lambda function
- In
lib/sample-stack.tsfile, add the following code to create a lambda function:
import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { Construct } from 'constructs';
export class SampleStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const hello = new lambda.Function(this, 'SampleLambda', {
runtime: lambda.Runtime.NODEJS_14_X,
code: lambda.Code.fromInline('exports.handler = async () => "hello world";'),
handler: 'index.handler'
});
}
}
This will create a sample lambda function that returns "hello world" when invoked.
Bootstrap the CDK project
Before you deploy your project. You need to bootstrap your project. This will create a CloudFormation stack that will be used to deploy your project. You can bootstrap your project by running cdk bootstrap.
Learn more about bootstrapping here.
Deploy the Project
- Run
npm installto install all the dependencies for your project whenever you make changes. - Run
cdk synthto synthesize the CloudFormation template for your project. You will see a new file calledcdk.out/CDKToolkit.template.jsonthat contains the CloudFormation template for your project. - Run
cdk diffto see the changes that will be made to your AWS account. You will see a new stack calledSampleStackthat will create a lambda function and all the changes associated with it. - Run
cdk deployto deploy your project. You should see a new stack called created in your AWS account under CloudFormation. - Go to Lambda console and you will see a new lambda function called
SampleLambdacreated in your account.