Knowledge transfer
DevOps with AWS CDK
And the future of Infrastructure as a Code
Overview
In this article, I want to share my experience with a distinctive technology that, I believe, sets the future for the Infrastructure as a Code in general, namely AWS CDK.
In addition to this textual report of mine, you will also have a sample project that you can use as a bootstrap for the work of your own.
Essentially AWS CDK allows you to code your infrastructure in a general-purpose programming language of your choice. The currently supported languages are C#, F#, Go, Java, Python, JavaScript, and TypeScript.
TLDR: the sample itself with the instructions to run it can be found here: https://github.com/NicklausBrain/aws-snake
Introduction
Our encounter with AWS CDK was quite accidental. We’ve been requested for a relatively simple project, MVP rather. The project needed to be delivered in a season with a small team (4–6 people). We could not afford to have a dedicated DevOps role while maintaining configuration for several environments appeared to be a pressing need early on. And yes, it had to be built upon AWS, while my previous experience was mostly about Azure, so using more-less familiar ARM templates or Azure CLI was not an option, while no one among teammates had any experience with Terraform or CloudFormation at all.
AWS CDK appeared to be a lucky finding. About two days appeared to be enough for me to get into it and create a proof of concept for the project.
The original project itself and its functions are indifferent to the topic therefore as a sample we will use a very simple web version of the well-familiar Snake game.
Sample architecture
The architecture depicted hereinbelow quite accurately represents what we used for our application (Image 1):
Essential highlights:
- It is a serverless architecture, without reserved computation power and minimized upfront costs;
- Amazon API Gateway serves as a single-entry point for the application;
- S3 storage is used to host the static website and media content;
- AWS Lambda function is used as a hosting/runtime environment for API;
- Dynamo DB preserves application state;
- For the sake of sample simplicity, I have to omit integration with Cognito which in the real-world application would be used to cover identity management.
In correspondence with the scheme above, we have three projects in the sample app:
/aws-snake
/snake-API # express API
/snake-client # snake game in plain JS
/snake-iac # AWS CDK projectThe original commercial project was built on .NET Core while I decided to implement the sample project in TypeScript for three reasons:
- TypeScript lies somewhat in between Java/C# and JavaScript;
- JavaScript-like syntax is almost universally apprehensible;
- To prove myself that this CDK thing works indifferently to the language of choice.
Getting started with the CDK
Starting with AWS CKD is straightforward, you can either follow the official Getting Started instructions or steps herein below:
- Create AWS account
- Create AWS access key
- Install AWS CLI
curl “https://awscli.amazonaws.com/AWSCLIV2.pkg" -o “AWSCLIV2.pkg” sudo installer -pkg AWSCLIV2.pkg -target / - Configure AWS CLI using the created access key
aws configure - Install Node LTS
brew install node # mac
sudo apt-get install nodejs # debian - Install AWS CDK toolkit
npm install -g aws-cdk - Install the target SDK/Runtime (in our case TypeScript)
npm install -g typescript - Create an empty project
mkdir snake-iac
cd snake-iac
cdk init app — language typescript - 9. Test the CDK commands:
cdk list # Lists all stacks in the appcdk synthesize # Synthesizes and prints the CloudFormation template for this stackcdk bootstrap # Deploys the CDK toolkit stack into an AWS environmentcdk diff # Compares the specified stack with the deployed stack or a local template file, and returns with status 1 if any difference is foundcdk deploy # Deploys the stack(s) into your AWS accountcdk destroy # Destroy the stack(s)
That’s it! Now you know all the necessary CDK commands! Most of the time though you will be using cdk diff and cdk deploy though.
Configuring the stack
Cloud Formation Stack is a collection of AWS resources manageable as a single unit and natively configurable as a JSON or YAML template (see how it works).
Get Nicklaus Brain’s stories in your inbox
Join Medium for free to get updates from this writer.
In essence, AWS CDK provides a wrapper over Cloud Formation Stack allowing configuring it in a general-purpose language.
cdk init app creates an empty stack with the respective file dependent on the target language: lib/snake-iac-stack.ts in our case (see commit 37d8d7d)
import * as cdk from ‘@aws-cdk/core’;export class SnakeIacStack extends cdk.Stack {
constructor(
scope: cdk.Construct,
id: string,
props?: cdk.StackProps) {
super(scope, id, props);
// The code that defines your stack goes here
}
}
Adding a new resource into the stack is simply adding a new instance of a respective object, for instance, to create an S3 bucket to host our JavaScript game, we simply add the lines below (see commit 93ceebe):
// The code that defines your stack goes here
// Snake Web Clientconst snakeClient = new s3.Bucket(this, nameIt(“website-s3”), {
bucketName: nameIt(“website-s3”),
versioned: false,
publicReadAccess: true,
websiteIndexDocument: “index.html”,
// remove on stack destruction
removalPolicy: cdk.RemovalPolicy.DESTROY
});
Note that it is quite important to establish a common naming convention for every resource created, for instance: <environment>-<project>-<resource>. We utilize the following helper function to achieve that:
const envName = ‘test’;
const nameIt = (name: string) =>
`${envName}-snake-${name}`.toLowerCase();Connecting resources
The very essential feature of the CDK is the ability to logically bind resources together, using them as dependencies. For instance, we can set our s3 hosted web site to be a default route (entry point) for our application (see commit 59b58dc):
// API Gateway
const snakeClientIntegration =
new integration.HttpProxyIntegration({
method: gate.HttpMethod.GET,
url: snakeClientBucket.bucketWebsiteUrl,
});const httpApi = new gate.HttpApi(this, nameIt(“Api-GateWay”), {
apiName: nameIt(“Api-GateWay”),
defaultIntegration: snakeClientIntegration,
});
Then we can similarly set API routes (see commit 8f6e9e1):
const apiGateway = new gate.HttpApi(this, nameIt(“Api-GateWay”), {
// … //
});// Snake API
const apiLambda = new lambda.Function(this, nameIt(“api-lambda”), {
// … //
});const snakeApiIntegration = new integration.LambdaProxyIntegration({
handler: apiLambda, // api integration
});apiGateway.addRoutes({ // api route
path: “/api/{proxy+}”,
methods: [gate.HttpMethod.ANY],
integration: snakeApiIntegration
});apiGateway.addRoutes({ // swagger route
path: “/swagger/{proxy+}”,
methods: [gate.HttpMethod.GET],
integration: snakeApiIntegration
});
The same comes for managing access control, giving API access to the database (see commit b20df0a):
// Persistence layer
const table = new dynamodb.Table(this, nameIt(‘DynamoDb-Table’), {
// … //
});// give api access to dynamo DB table
table.grantReadWriteData(apiLambda);
For a complete stack configuration sample please refer to the project source code.
Observing the stack
Firstly, you can refer to the CloudFormation Stacks in the AWS web console (Image 2):
Secondly, the same list of stacks can be retrieved by running a terminal command:aws cloudformation list-stacks
Handling a configuration drift
This is a rather weak spot of the AWS CDK since detecting and handling of the configuration drift is not available out of the box yet (see an open issue).
It is achievable but not trivial (see official article).
Therefore, I would suggest to start with preventing a possibility of a drift (see official manual).
Ideally, all the infrastructure changes should be applied programmatically, on behalf of a dedicated account exclusively used by the CDK application.
This option can also be automated (see an open issue).
CI/CD
AWS CDK can be easily integrated into CI/CD procedure. For this sample, GitHub Actions are being used, while for an original project we’ve been using Azure DevOps without significant differences.
The sample CI/CD configuration consists of two essential parts:
- A script for building the packages to be deployed (./build.sh);
- GitHub workflow config in YAML, describing delivery to multiple (test, prod) environments and deployment approvals (./.github/workflows/ci-cd.yml);
The resulting delivery workflow run is displayed on the image below (Image 3):
See CI/CD configuration steps in the Readme.MD for configuring it by yourself.
Conclusion
I believe AWS CDK settled the precedent for the future of DevOps practice. The ongoing development of the Terraform CDK is proving the general interest of having the Infrastructure as a Code implemented in common programming languages. This evolution will not just lower the entrance gap to the Continuous Delivery discipline but will allow any developer to be included in infrastructure maintenance and utilize all the modern quality control tools including static analysis and unit tests.
Lastly, I do assume that some of the readers would object to the idea of using a general-purpose language for the infrastructure. Since this question is out of the scope of this article I would just leave some links (one, two) to relevant discussions in Reddit that I consider insightful.
Tags: #DevOps #IaC #AWS #CDK #CICD









