Get started with the AWS Cloud Development Kit (CDK) (2023)

How to Deploy a Simple Lambda and S3 Application Using the CDK

Get started with the AWS Cloud Development Kit (CDK) (1)

The more I use the AWS CDK, the more I like it. I've always found the raw CloudFormation to be tedious and long-winded, and the CDK seems like a faster and easier way to set up and manage your infrastructure.

In this story, I'll explain how to get started with the CDK and how to use it to deploy a small application to your AWS account.

AWS Cloud Development Kit (CDK)is a framework that allows engineers to define their infrastructure as code (IaC) in a familiar programming language, rather than having to manually manage their infrastructure or write raw CloudFormation.

While I generally prefer to write in Python, I've been writing my CDK in Typescript. I don't have very strong reasons for this; it was the language in which I was first introduced to the CDK. It's also the native language of the CDK, and between its strong typing and VSCode's autocompletion, it makes writing CDKs a breeze.

For this example, we'll create a simple application consisting of two S3 buckets (one source and one destination) and a Lambda that will read the source file, modify it, and write it to the destination bucket.

Obviously, this is a simple and contrived example, but we'll need to have the CDK written to:

  • Set of S3 cubes
  • Define our Lambda function
  • Manage Permissions
  • Give us an endpoint to invoke our Lambda

This guide assumes you have the AWS CLI and Node.js installed. If not, seeAWS official documentationto configure your environment.

Otherwise, we will create a new directory (this command must be executed in an empty directory, otherwise you will get an error)mkdir CDKDemo,cdthey are executed:

cdk init app --typescript

This will create a lot of files and also initialize a new git repository in your directory.

We have a few files to create that are unrelated to the CDK.

the text file

We're going to upload a file to S3, so let's define that file. It's just a simple txt file calledola.txt, and we will create a new directoryactive/to save it to:

Hello World!

the python function

This is the python file that will run in Lambda to move our file between repositories. In this example, we are going to create this file asola.pynolambda/directory:

import date and time
Careful

import boto3

FILE_NAME = "hola.txt"
s3 = boto3. recurso("s3")

def copy_file_to_destination():
new_file_name = f"{FILE_NAME.split('.')[0]}_updated.txt"
s3.Bucket(os.environ["DESTINATION_BUCKET"]).upload_file(
f"/tmp/{FILE_NAME}", new_file_name
)

def find_file_from_source():
s3.Bucket(os.environ["SOURCE_BUCKET"]).download_file(FILE_NAME, f"/tmp/{FILE_NAME}")

def update_file():
com open(f"/tmp/{FILE_NAME}", "a") como f:
my_str = f"\nI read this file on {datetime.datetime.now()}!"
f.write(my_string)

definition handler(event, context):
find_source_file()
Update file()
copy_file_to_destination()

Note that this function performs 3 simple tasks:

  1. Using the boto3 library, get the file from ourSOURCE_BUCKETand store it in/tmpdirectory.
  2. It then adds a newline to the file that announces when it reads the file.
  3. Again using boto3, upload the updated file toDESTINATION_BUCKETwith "_updated" appended to the name.

After executing the above command, you should open thetfile insidereleaseaddress The name of this file will depend on what your working directory is called and there will be some boilerplate code in place. This is where we can start defining our stack!

S3

We need a source cube and a target cube for this demo. We don't need to have any public access to these buckets, so let's lock them down and let s3 handle the server-side encryption.

For this example, we also want to defineremoval policyaDESTROY, and having the items in our buckets automatically removed when we destroy the stack. keep in mind thatyou probably don't want this behavior in a real world application, but otherwise we'd be left with these orphaned buckets that we'd need to manually clean up when we're done.

import * as s3 from "aws-cdk-lib/aws-s3";

// S3 containers
const sourceBucket = new s3.Bucket(this, "sourceBucket", {
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
cifrado: s3.BucketEncryption.S3_MANAGED,
removal policy: cdk.RemovalPolicy.DESTROY,
autoDeleteObjects: true,
});

const destinoCubo = new s3.Cubo(this, "destinoCubo", {
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
cifrado: s3.BucketEncryption.S3_MANAGED,
removal policy: cdk.RemovalPolicy.DESTROY,
autoDeleteObjects: true,
});

Upload our text file

Since our example is using a predefined patternola.txtLet's go ahead and upload it to the source repository as part of our deployment. Remember that our text file is located at./active:

import * as s3deploy from "aws-cdk-lib/aws-s3-deployment";

// Subir hello.txt a sourceBucket
const deployment = new s3deploy.BucketDeployment(this, "DeployHello", {
fontes: [s3deploy.Source.asset("./assets")],
target repository: source repository,
});

lambda

The Lambda definition is probably the most complicated. Note that since I'm creating a lambda that uses python, I'm going to import and install theaws-lambda-python-alfapackage too. While not strictly necessary in this example, it makes packaging dependencies easier, so I got used to using it.
As this is not included inaws-cdk-lib, you will probably need to install it separately, using the command:

npm instala "@aws-cdk/aws-lambda-python-alpha"

We also need to tell this lambda to use Python 3.9, where to find ourola.pyfile and how to run it:manipulative. If you look back at the python file above, you'll also notice that we need to set two environment variables: the names of our buckets. We can access the name using thefontCubeytarget cubevariables that we assign to our S3 buckets.

Finally, we add an unauthenticated function URL that will allow us to invoke our lambda.

import * as lambda from "aws-cdk-lib/aws-lambda";
importar * como pyLambda de "@aws-cdk/aws-lambda-python-alpha";

//Lambda
const fileTransferLambda = new pyLambda.PythonFunction(
That's it,
"transferirarquivoLambda",
{
runtime: lambda.Runtime.PYTHON_3_9,
input: "./lambda",
index: "hello.py",
negotiations: "exchanges",
environment: {
SOURCE_BUCKET: sourceBucket.bucketName,
DESTINATION_BUCKET: destinoBucket.bucketName,
},
}
);

// URL lambda
const fileTransferLambdaUrl = fileTransferLambda.addFunctionUrl({
authentication type: lambda.FunctionUrlAuthType.NONE,
});

Police I.A.M.

Although we have defined our lambda and our buckets, they are currently not allowed to interact with each other. For that, we need to define some IAM policies.

we just needGETof the original warehouse andTO PLACEto the destination bucket, so we add only the minimum necessary permissions.

After defining these policies, we need to attach them to our lambda's security role.

import * as iam from "aws-cdk-lib/aws-iam";

//MILITARY
const getFromSourcePolicy = new iam.Policy(this, "getFromSourcePolicy", {
document: new now.PolicyDocument({
statements: [
nueva iam.PolicyStatement({
actions: ["s3:Get*"],
recursos: [sourceBucket.arnForObjects("*")],
}),
],
}),
});

const putInDestinationPolicy = new iam.Policy(
That's it,
"put in target policy",
{
document: new now.PolicyDocument({
statements: [
nueva iam.PolicyStatement({
actions: ["s3:Put*"],
recursos: [destinationBucket.arnForObjects("*")],
}),
],
}),
}
);

// Attach IAM policies to Lambda
const fileTransferLambdaRole = fileTransferLambda.role;
fileTransferLambdaRole?.attachInlinePolicy(getFromSourcePolicy);
fileTransferLambdaRole?.attachInlinePolicy(putInDestinationPolicy);

Note that setting policies this way is really overkill for this simple application! We could have just usedgrantReadygrant writein S3 cubes,but this gives an example of what a custom IAM policy might look like.

Production

Finally, we want the CDK to tell us the URL value of our lambda for ease of use, so we set it to aOutput Cfnfinal:

// Production
novo cdk.CfnOutput(this, "fileTransferLambdaUrl", {
valor: fileTransferLambdaUrl.url,
});

the whole file

That is all!
For easy reference, the full file is below. Note that we were able to define our entire infrastructure in less than 90 lines of code.

import * as cdk from "aws-cdk-lib";
import * as s3 from "aws-cdk-lib/aws-s3";
import * as s3deploy from "aws-cdk-lib/aws-s3-deployment";
import * as iam from "aws-cdk-lib/aws-iam";
import * as lambda from "aws-cdk-lib/aws-lambda";
importar * como pyLambda de "@aws-cdk/aws-lambda-python-alpha";
import {Building} from "buildings";

export class CdkDemoStack extends cdk.Stack {
constructor(scope: Build, id: string, props?: cdk.StackProps) {
super(range, id, props);

// S3 containers
const sourceBucket = new s3.Bucket(this, "sourceBucket", {
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
cifrado: s3.BucketEncryption.S3_MANAGED,
});

const destinoCubo = new s3.Cubo(this, "destinoCubo", {
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
cifrado: s3.BucketEncryption.S3_MANAGED,
});

// Subir hello.txt a sourceBucket
const deployment = new s3deploy.BucketDeployment(this, "DeployHello", {
fontes: [s3deploy.Source.asset("./assets")],
target repository: source repository,
});

//Lambda
const fileTransferLambda = new pyLambda.PythonFunction(
That's it,
"transferirarquivoLambda",
{
runtime: lambda.Runtime.PYTHON_3_9,
input: "./lambda",
index: "hello.py",
negotiations: "exchanges",
environment: {
SOURCE_BUCKET: sourceBucket.bucketName,
DESTINATION_BUCKET: destinoBucket.bucketName,
},
}
);

// URL lambda
const fileTransferLambdaUrl = fileTransferLambda.addFunctionUrl({
authentication type: lambda.FunctionUrlAuthType.NONE,
});

//MILITARY
const getFromSourcePolicy = new iam.Policy(this, "getFromSourcePolicy", {
document: new now.PolicyDocument({
statements: [
nueva iam.PolicyStatement({
actions: ["s3:Get*"],
recursos: [sourceBucket.arnForObjects("*")],
}),
],
}),
});

const putInDestinationPolicy = new iam.Policy(
That's it,
"put in target policy",
{
document: new now.PolicyDocument({
statements: [
nueva iam.PolicyStatement({
actions: ["s3:Put*"],
recursos: [destinationBucket.arnForObjects("*")],
}),
],
}),
}
);

// Attach IAM policies to Lambda
const fileTransferLambdaRole = fileTransferLambda.role;
fileTransferLambdaRole?.attachInlinePolicy(getFromSourcePolicy);
fileTransferLambdaRole?.attachInlinePolicy(putInDestinationPolicy);

// Production
novo cdk.CfnOutput(this, "fileTransferLambdaUrl", {
valor: fileTransferLambdaUrl.url,
});
}
}

Now that we have our files in order, it's time to test our app!

synthesizer

The first thing I tend to do when I create a new CDK stack (or make big changes) is runcdk synthesizer. This command generates the CloudFormation template that will run in the background and is a good way to ensure you don't have a bug in your CDK that prevents it from being synthesized.

Implantation

Finally, it's time to deploy our code to AWS! This is as simple ascdk deployment, although depending on your AWS configuration you may also need to specify which profile to use (e.g.--personal profile).

Since everything on the stack is new to start with, it will take a few minutes to run the first time, but it will usually take less (< 1 min) for future updates. However, do not exit after pressing Enter; You may need to approve some of the changes being implemented, especially changes related to security and permissions.

Get started with the AWS Cloud Development Kit (CDK) (2)

After accepting these changes, the rest of the stack will be deployed. If everything is implemented correctly, you will get the requested result in the end:

Get started with the AWS Cloud Development Kit (CDK) (3)

Evidence

Now, before you click that link and run your lambda, you can go ahead and log into the AWS console to investigate how everything looks now that it's deployed.

If you navigate to CloudFormation, you'll see its stack and its status:

Get started with the AWS Cloud Development Kit (CDK) (4)

You can also check the buckets that were created in S3:

Get started with the AWS Cloud Development Kit (CDK) (5)

And make sure ourola.txtis in the source bucket as it should be:

Get started with the AWS Cloud Development Kit (CDK) (6)

Finally, let's visit thefileTransferLambdaUrl- when clicked it will open a page that saysnull, since we didn't tell Lambda to generate anything, but now we can check our destination bucket. We should have a new updated text file!

Get started with the AWS Cloud Development Kit (CDK) (7)

if you open the newhello_updated.txt, you'll see that it's been updated with the line we added in our lambda function:

Get started with the AWS Cloud Development Kit (CDK) (8)

difference

Note that if you ever need to make changes to your stack and redeploy your application, thecdk differencecommand is also worth a quick call here. It will show the changes that the implementation will introduce.

To clean

Now that we have successfully tested our application,Don't forget to tip your stack!

Taking it all down is as easy as runningcdk destroy.

Get started with the AWS Cloud Development Kit (CDK) (9)

As I mentioned above, this is obviously a contrived example (and not a fully relevant use case likeS3 Embraced by Lambdaexists), but I hope it gives you an idea of ​​how quick and easy it is to get started writing IaC on the AWS CDK.

other resources

Here are some other resources that you might find useful when working with the AWS CDK:

I hope you found this guide helpful and would be happy to hear any suggestions or comments you may have. Happy programming!

Thank you for being part of our community! Before you go:

🚀👉Join the Level Up Talent Collective and find amazing work

FAQs

Is AWS CDK worth it? ›

Overall I think if you have a fairly small team that is owning the application, the infrastructure code of an application, and the production deployment of that application, then CDK is worth strongly considering (I'd use it myself).

How does the AWS cloud Development Kit AWS CDK aid developers who know only a few programming languages? ›

The AWS CDK Toolkit is a command line tool for interacting with CDK apps. Developers can use the AWS CDK Toolkit to synthesize artifacts such as AWS CloudFormation templates and to deploy stacks to development AWS accounts. You can also diff against a deployed stack to understand the impact of a code change.

Is CDK better than CloudFormation? ›

Additionally, the CDK provides a more structured reuse format than CloudFormation. The three-tiered reuse level of components, intents, and patterns means you can build up a library of reusable components and patterns your entire organization can use to build infrastructure and ship applications more quickly.

Does CDK generate CloudFormation? ›

The cdk synth generates a perfectly valid AWS CloudFormation template. You could take it and deploy it using the AWS CloudFormation console or another tool. But the AWS CDK Toolkit can also do that.

What are the downsides of AWS CDK? ›

Downsides of AWS CDK

AWS CDK lacks cross-account deployment support. However, you can write your own logic code using their toolset or use the CDK credential plugin. It doesn't have a console GUI to deploy your app the way CloudFormation does, so you must use the CLI.

Which language is best for AWS CDK? ›

TypeScript was the first language supported for developing AWS CDK applications. Therefore, a substantial amount of example CDK code is written in TypeScript.

What is the difference between AWS SDK and CDK? ›

What is the difference between AWS SDK and AWS CDK? The AWS Software Development Kit (SDK) is a set of libraries that allow you to integrate your application with AWS Services. The AWS Cloud Development Kit (CDK) is a framework that allows you to provision Cloud infrastructure using code.

What is the difference between CDK and CloudFormation? ›

Because the AWS CDK expands the number of resources that developers can manipulate through a code base, it offers more functionality than limited tools such as CloudFormation and Hashicorp TerraForm. The AWS CDK not only streamlines the provisioning process, it also simplifies verification and review.

How does CDK activate? ›

As their name suggests, CDKs require the presence of cyclins to become active. Cyclins are a family of proteins that have no enzymatic activity of their own but activate CDKs by binding to them.

Does CDK replace CloudFormation? ›

Using familiar programming languages and provided libraries in TypeScript, Python, Java, and . NET, developers can write with the same code as the rest of their stack to manage their infrastructure. CDK, however, is not devoid of AWS CloudFormation. In fact, CDK synthesizes to CloudFormation.

Should I use CDK or Terraform? ›

For multi-cloud operations, Terraform is an obvious choice; however, if you are looking to use AWS as your cloud provider, AWS CDK is an excellent alternative.

What is the difference between AWS CDK and Terraform? ›

Both Terraform and AWS CDK are excellent IaC tools to create and maintain cloud infrastructures. Terraform is more purely declarative, and with AWS CDK, you can use your favorite programming language with imperative style.

What is CloudFormation CDK? ›

The AWS Cloud Development Kit (AWS CDK) is an open-source software development framework for defining cloud infrastructure as code with modern programming languages and deploying it through AWS CloudFormation.

How do I create a CDK stack? ›

How to create an AWS CDK Stack
  1. Install packages.
  2. Import the Stack Class.
  3. Instantiate a new stack.
May 3, 2022

Is AWS CDK a framework? ›

The AWS Cloud Development Kit (AWS CDK) is a framework for defining cloud infrastructure in code (IaC) and provisioning it through AWS CloudFormation.

Does Google have a CDK? ›

The Go Cloud Development Kit (Go CDK) allows Go application developers to seamlessly deploy cloud applications on any combination of cloud providers. It does this by providing stable, idiomatic interfaces for common uses like storage and databases.

Does CDK use Docker? ›

AWS CDK will build your new Lambda function using Docker and then push it for you to the ECR repository that was originally created for you by running cdk bootstrap during the CDK setup. How convenient. After the image is built and pushed, CDK will deploy the necessary infrastructure.

Why is CDK so slow? ›

CloudFormation deployments are usually fairly slow, mainly because of the complicated lifecycle of resources involved in each deployment (their updates might cause replacements, failures might result in rollbacks of previously created or updated resources, etc.).

Is AWS CCP hard? ›

The AWS cloud practitioner exam is considered moderately challenging to crack for beginners. It is considered less complicated to clear if you know how to play with billing tools and AWS services. But if you are a beginner and new to AWS, the situation may be a little different for you.

How much does AWS CCP certification cost? ›

How much does an AWS Certification exam cost? The Cloud Practitioner exam is 100 USD. Associate-level exams are 150 USD. Professional-level and Specialty exams are 300 USD.

Which AWS certification is most in demand? ›

Final Verdict. The Solutions Architect – Associate certification is our choice for the best AWS cloud certification overall. It is the most popular certification offered by AWS and provides a solid foundation in AWS cloud computing.

Why should I use AWS CDK? ›

AWS CDK enables you to define your infrastructure with code and provision it through AWS CloudFormation. You get all the benefits of CloudFormation, including repeatable deployment, easy rollback, and drift detection.

Can you use AWS SDK with CDK? ›

Mixing in AWS SDK functionality in your CDK code gives additional options to add in dynamic data to your solutions. Of course there are alternatives like CDK Custom Constructs, but these are semi-static.

Is SDK better than API? ›

While an API is purpose-built to perform a specific function of allowing communication between applications, an SDK is an integrated platform that boasts a set of tools to create these applications. APIs facilitate and allow interaction between applications, but they alone are not enough to create a brand new app.

Is Terraform a CDK? ›

Built on top of the open source JSII library, CDK for Terraform allows you to write Terraform configurations in your choice of C#, Python, TypeScript, Java, or Go and still benefit from the full ecosystem of Terraform providers and modules.

Does Azure have a CDK? ›

Learn a quick method for getting started with the Cloud Development Kit (CDK) for Terraform using TypeScript as infrastructure code and provisioning on Microsoft Azure. The CDK for Terraform is a tool used to define infrastructure using programming languages including TypeScript, Python, Java, and C#.

Is CDK infrastructure as code? ›

AWS CDK, which is powered by AWS CloudFormation, enables you to specify your infrastructure in code and deploy it using AWS CloudFormation. You receive all of CloudFormation's advantages, such as repeatable deployment, simple rollback, and drift detection. Use well-known programming languages, tools, and workflows.

How many steps are required for CDK activation? ›

The two steps in Cdk1 activation are thus mutually dependent in vivo and must occur in concert. (Intrinsic instability of Cdk1/cyclin complexes, relative to Cdk2/cyclin complexes, might also explain why only the latter show activity independent of T-loop phosphorylation 11, 27, 29.)

What happens when CDKs are activated? ›

The Cdk is now active and phosphorylates various targets specific to the G1/S transition. The phosphorylated targets cause the activation of DNA replication enzymes, and S phase begins.

What is the point of CDK? ›

AWS Cloud Development Kit (AWS CDK) accelerates cloud development using common programming languages to model your applications.

Is AWS CDK serverless? ›

Amazon Web Service (AWS) CDK is an open source serverless application development framework that enables you to define cloud resources for your serverless applications using programming languages like TypeScript, Python, and Java then deploy it on AWS Lambda.

What is a stack in AWS CDK? ›

The unit of deployment in the AWS CDK is called a stack. All AWS resources defined within the scope of a stack, either directly or indirectly, are provisioned as a single unit. Because AWS CDK stacks are implemented through AWS CloudFormation stacks, they have the same limitations as in AWS CloudFormation.

Is Terraform CDK ready for production? ›

Today, we are pleased to announce that CDKTF is now generally available and ready for production usage.

Should I learn Terraform or Kubernetes first? ›

The platform you learn first depends on the DevOps function you'll be performing. If you want to deploy operational infrastructure, learn Terraform first. Developers who work with containers should learn Kubernetes first.

Is AWS CDK production ready? ›

So yes AWS CDK is production ready! In this course you are learning about the basics of AWS CDK which is an open source framework to generate Cloudformation templates out of code written in languages like Java, JavaScript, TypeScript or Python. CDK uses Constructs to describe one or more Cloudformation resources.

Is Terraform still relevant? ›

Terraform is still a useful tool in the tech space because it offers some specific advantages over its competitors as an infrastructure tool. One reason why you should continue to use Terraform is the declarative style that it offers you as a user.

How tough is Terraform certification? ›

How Difficult is this exam? This exam is easy to pass if you have the knowledge on Terraform basic understanding, the purpose why we are using it, workflow, function modules, and workspace concepts.

Can AWS CDK output Terraform? ›

Using these components, the AWS CDK generates CloudFormation configuration from code written in TypeScript, JavaScript, Python, Java, or C#. Similarly, the CDK for Terraform generates Terraform configuration to enable provisioning with the Terraform platform.

Is Terraform easier than CloudFormation? ›

In CloudFormation, it is possible to manage so-called “custom resources” by using an AWS Lambda function of your own creation as a back end. For Terraform, extensions are much easier to write and form part of the code. So there is an advantage for Terraform in this case. Terraform can handle many cloud vendors.

How to install AWS CDK? ›

To install AWS CDK, run the following command in your terminal: npm install -g aws-cdk . This will install the AWS CDK package globally on your system which then allows you to initialize your first project and start building and deploying code in your AWS account using AWS CDK.

What is CDK in Devops? ›

The AWS Cloud Development Kit (AWS CDK) is an open source software development framework to model and provision your cloud application resources using familiar programming languages. AWS CDK enables you to model application infrastructure using TypeScript, Python, Java, and .

Why should I use CloudFormation? ›

In simple terms, it allows you to create and model your infrastructure and applications without having to perform actions manually. AWS CloudFormation enables you to manage your complete infrastructure or AWS resources in a text file, or template. A collection of AWS resources is called a stack.

Is Cdk better than TerraForm? ›

As powerful and mature the CDK may be, it is limited only to AWS Cloud. When considering the scope of the IAC tools, Terraform is the obvious winner of the two. It makes a lot of sense to have your developers use a single tool for all the cloud platforms.

Is AWS CCP worth it? ›

Although, is AWS cloud practitioner worth it in the long run? Yes, AWS Certified Cloud Practitioner is a beneficial certification for cloud professionals irrespective for their technical skills and job roles to deal with clooud operations and make price-related decisions.

Is AWS CDK stable? ›

APIs in the main AWS CDK library, aws-cdk-lib , are stable, and the library is fully semantically versioned. This package includes AWS CloudFormation (L1) constructs for all AWS services and all stable higher-level (L2 and L3) modules.

References

Top Articles
Latest Posts
Article information

Author: Catherine Tremblay

Last Updated: 04/11/2023

Views: 6328

Rating: 4.7 / 5 (47 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Catherine Tremblay

Birthday: 1999-09-23

Address: Suite 461 73643 Sherril Loaf, Dickinsonland, AZ 47941-2379

Phone: +2678139151039

Job: International Administration Supervisor

Hobby: Dowsing, Snowboarding, Rowing, Beekeeping, Calligraphy, Shooting, Air sports

Introduction: My name is Catherine Tremblay, I am a precious, perfect, tasty, enthusiastic, inexpensive, vast, kind person who loves writing and wants to share my knowledge and understanding with you.