Source code: https://git.io/fjDYx
In a recent blog post, we discussed about the journey we go through that leads us to search for better options to deal with ever increasing and complex deployment workloads, as adoption of cloud grows in our organization.
In this blog post, we will look at how to practically use AWS CDK by deploying a working REST API backend for our books catalog Microservices.
Create a folder and sub-folder for project, as shown below
Open terminal window in books-api subfolder and run the following command to install aws-cdk
npm install -g aws-cdk
This installs aws cdk globally into this machine, so it can be used in any path.
Verify cdk is installed correctly by checking its version
This completes the installation.
Make sure you are in books-api folder and run the following command from the terminal windows
Now if you were to browse under books-api folder, you should see the many artifacts created for us by AWS CDK.
All the work we will be doing is in file books-api-stack.js present in “lib” folder.
So, let’s look at boiler plate code already present in this file.
This is the standard structure. The Stack object here corresponds to the AWS CloudFormation Stack that will be created for us when we deploy. So we extend cdk.stack class to create BooksApiStack class.
We will be writing our code in the section underlined with Red line.
Now, before we begin to write code, lets do a dry run to check how CDK works.
For that, go back to your terminal and execute the following command
you should see the following result, which is nothing but a CloudFormation template created for us.
So, the “synth” command, which means Synthesize, is responsible for converting the code we have written in “lib” folder into a CloudFormation template. This is one of the important things the CDK does for us.
In some cases, you may find that you write few lines of code and CDK will generate 10’s or even 100’s of lines of CloudFormation template code for us. So, we are essentially working at a higher level of abstraction and CDK is responsible for doing the grunt work of converting the higher-level code into template.
This is the game changer and once you are hooked to this way of deployment, you will never go back to writing CloudFormation templates yourself.
Also, as you can see, CDK will include a Metadata section into the template along with other resources that we code.
OK. Now let’s focus on task at hand, which is that we are going to implement ListBooks REST API function here and will use CDK to create required resources. The following things will need to be created
- A DynamoDB table to hold all the books present in our book catalog
- A lambda function to return list of all books present in Dynamo Db table
- A GET REST API endpoint to read the books returned.
- Additionally, we also require permissions to be set appropriately in IAM (creation of Roles)
We will start with provisioning of database first. But before we can deploy anything, we need to bootstrap the cdk.
You will see some preliminary tasks executed by CDK like creating an S3 bucket for storage of CloudFormation templates.
So now we are ready to go ahead with deployment. Let’s checkout doing an empty deployment
First deployment using CDK
You can deploy the CloudFormation template created earlier with a single command as follows
This completes our first deployment using AWS CDK. Congrats!
This is the Second important thing that CDK does. It helps us to deploy our template with a simple command and give us the real-time status of the resources being created and success/failure of the operation.
Let’s check this by opening CloudFormation home page
So, as we mentioned before, the template we built earlier using synthesize command is uploaded to a S3 bucket and executed as a CloudFormation stack.
We are done here. Now all You have to do is write some code and call Deploy command. That’s it. Isn’t this simple? [Sarcasm alert].
I know what you are thinking. Isn’t writing the right CODE an important part of this exercise you fool.?
OK. I heard that. Loud and Clear and that was Rude. But let’s proceed to write some code anyway 😊
Creating DynamoDB Table
First, we need to install a package required by CDK. Execute the following commmand in your terminal window
npm install –save @aws-cdk/aws-dynamodb
Now, paste the following code in our main file present in “lib” folder (books-api-stack.js)
Run the synthesize command again
Then run deploy command again
And you would see the table created in DynamoDB
Now we will add 2 books in it. Click on the table name, go to Items tab and click Create Item button
Click the drop-down arrow after text Tree and select Text there.
Then paste the below two JSON entries for books one-by-one and click Save.
Note: You can find this json file in following location
After this, you should be able to see the 2 books in DynamoDB Items tab
This completes work at database level. Now lets quickly write code for Lambda function as well as API Gateway provisioning together
Provision Lambda function & API Gateway
Execute the following commands.
npm install –save @aws-cdk/aws-lambda
npm install –save @aws-cdk/aws-apigateway
npm install –save @aws-cdk/aws-iam
Now that we have the required modules available, lets modify our main file (books-api-stack.js) in “lib” folder
Add the following 3 lines towards top of our main file
Then Paste the code to create Lambda AFTER DynamoDB section
Then code to create API Gateway
Then Setting Permissions on Role.
So the complete file looks like below
List-books Lambda function
Now, the last thing which remains is to define our ListBooks lambda function.
Create a folder called “lambda” under our books-api folder. Inside this folder, create a file called list.js.
Paste the following code in list.js file
This list.js file is attached to our Lambda function in main file by the two lines below.
Code asset mentions the folder where it Lambda code resides.
Handler’s first part (“list.handler”) means it is looking for list.js file. Inside this file, it will look for handler function as the starting point of lambda code execution.
Also note above that we are passing the DynamoDB table as Environment variable in environment section.
It will show you what all will be provisioned for you and will prompt you to proceed Yes/No. Answer Yes and the provisioning will complete.
Make note of the API Endpoint URL returned above
You can check the resources have been provisioned as expected.
Checking auto-generated CloudFormation template
Go to cdk.out folder and open file BooksAPIStack.template.json
This file is the actual CloudFormation template CDK created for us.
If you were to convert this 458 lines JSON file to YAML, it comes to 265 lines, as seen below
So, by writing few lines of code in the boiler-plate CDK template, we managed to get it to create a 265 lines template.
Also, there are no other hassles like copy-paste errors or syntax errors that we regularly incur while writing long templates. It just creates templates that execute flawlessly.
I am sold off on this and will now use AWS CDK as primary tool for deployment on AWS. Will you?
Final Testing (Moment of Truth)
Take the Endpoint URL above, add /books at the end and hit it in a browser.
You should see a response like the one below
Bingo!. It works.
To remove the deployment, execute the following command
This should remove all the resources created above.
Edit: Go to DynamoDB table and Delete books-catalog table manually. The default property set for the table in above code did not allow it to be cleaned by above command. So we have to clean it manually.
This completes your journey into using AWS Cloud Deployment Kit (CDK) for deployment.
Now, you can check-in this code to version control, use it multiple times, track it and more importantly, you can use the full power and features of a programming language like Modular design, Inheritance, Conditional logic etc. to create deployment code that is intelligently deploy exactly as per your requirement irrespective of the complexity
1 thought on “ – Deploying Microservices using AWS Cloud Development Kit (CDK)”
[…] next blog post, we will explore how to use AWS CDK […]