Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
The AWS Cloud Development Kit (AWS CDK) is an open-source software development framework to define cloud infrastructure in code and provision it through AWS CloudFormation. It provides high-level components called constructs that preconfigure cloud resources with proven defaults, so you can build cloud applications without needing to be an expert in AWS services.
Defining Infrastructure
This feature allows you to define AWS infrastructure using familiar programming languages. The code sample demonstrates how to define a new VPC using the AWS CDK.
const vpc = new ec2.Vpc(this, 'VPC');
Creating a Lambda Function
With AWS CDK, you can create serverless functions such as AWS Lambda. The code sample shows how to define a Lambda function with the Node.js 12.x runtime.
const lambdaFunction = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_12_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('lambda')
});
Hosting a Static Website
AWS CDK can be used to host static websites on Amazon S3. The code sample illustrates how to create an S3 bucket configured for website hosting and how to deploy website content to it.
const bucket = new s3.Bucket(this, 'WebsiteBucket', {
websiteIndexDocument: 'index.html'
});
new s3deploy.BucketDeployment(this, 'DeployWebsite', {
sources: [s3deploy.Source.asset('./website-dist')],
destinationBucket: bucket
});
Setting up an API Gateway
This feature enables the creation of Amazon API Gateway endpoints. The code sample shows how to set up a REST API with a GET method integrated with a Lambda function.
const api = new apigateway.RestApi(this, 'MyApi', {
restApiName: 'Service'
});
const getLambdaIntegration = new apigateway.LambdaIntegration(getLambda);
api.root.addMethod('GET', getLambdaIntegration);
The Serverless Framework is similar to AWS CDK in that it allows you to define and deploy cloud infrastructure using code. It supports multiple cloud providers and is focused on building serverless applications. It uses a configuration file approach rather than an object-oriented programming model.
Terraform by HashiCorp is an infrastructure as code tool that allows you to define both cloud and on-premises resources with a declarative configuration language. It is cloud-agnostic and supports multiple providers, whereas AWS CDK is focused on AWS services.
Pulumi is an infrastructure as code tool that allows you to define infrastructure using general-purpose programming languages. Similar to AWS CDK, Pulumi provides an object-oriented approach but supports multiple cloud providers, not just AWS.
The AWS CDK Toolkit provides the cdk
command-line interface that can be used to work with AWS CDK applications.
Command | Description |
---|---|
cdk docs | Access the online documentation |
cdk init | Start a new CDK project (app or library) |
cdk list | List stacks in an application |
cdk synth | Synthesize a CDK app to CloudFormation template(s) |
cdk diff | Diff stacks against current state |
cdk deploy | Deploy a stack into an AWS account |
cdk destroy | Deletes a stack from an AWS account |
cdk bootstrap | Deploy a toolkit stack to support deploying large stacks & artifacts |
cdk doctor | Inspect the environment and produce information useful for troubleshooting |
This module is part of the AWS Cloud Development Kit project.
cdk docs
Outputs the URL to the documentation for the current toolkit version, and attempts to open a browser to that URL.
$ # Open the documentation in the default browser (using 'open')
$ cdk docs
https://docs.aws.amazon.com/cdk/api/latest/
$ # Open the documentation in Chrome.
$ cdk docs --browser='chrome %u'
https://docs.aws.amazon.com/cdk/api/latest/
cdk init
Creates a new CDK project.
$ # List the available template types & languages
$ cdk init --list
Available templates:
* app: Template for a CDK Application
└─ cdk init app --language=[java|typescript]
* lib: Template for a CDK Construct Library
└─ cdk init lib --language=typescript
$ # Create a new library application in typescript
$ cdk init lib --language=typescript
cdk list
Lists the stacks modeled in the CDK app.
$ # List all stacks in the CDK app 'node bin/main.js'
$ cdk list --app='node bin/main.js'
Foo
Bar
Baz
$ # List all stack including all details (add --json to output JSON instead of YAML)
$ cdk list --app='node bin/main.js' --long
-
name: Foo
environment:
name: 000000000000/bermuda-triangle-1
account: '000000000000'
region: bermuda-triangle-1
-
name: Bar
environment:
name: 111111111111/bermuda-triangle-2
account: '111111111111'
region: bermuda-triangle-2
-
name: Baz
environment:
name: 333333333333/bermuda-triangle-3
account: '333333333333'
region: bermuda-triangle-3
cdk synthesize
Synthesize the CDK app and outputs CloudFormation templates. If the application contains multiple stacks and no
stack name is provided in the command-line arguments, the --output
option is mandatory and a CloudFormation template
will be generated in the output folder for each stack.
By default, templates are generated in YAML format. The --json
option can be used to switch to JSON.
$ # Generate the template for StackName and output it to STDOUT
$ cdk synthesize --app='node bin/main.js' MyStackName
$ # Generate the template for MyStackName and save it to template.yml
$ cdk synth --app='node bin/main.js' MyStackName --output=template.yml
$ # Generate templates for all the stacks and save them into templates/
$ cdk synth --app='node bin/main.js' --output=templates
cdk diff
Computes differences between the infrastructure specified in the current state of the CDK app and the currently deployed application (or a user-specified CloudFormation template). This command returns non-zero if any differences are found.
$ # Diff against the currently deployed stack
$ cdk diff --app='node bin/main.js' MyStackName
$ # Diff against a specific template document
$ cdk diff --app='node bin/main.js' MyStackName --template=path/to/template.yml
cdk deploy
Deploys a stack of your CDK app to it's environment. During the deployment, the toolkit will output progress
indications, similar to what can be observed in the AWS CloudFormation Console. If the environment was never
bootstrapped (using cdk bootstrap
), only stacks that are not using assets and synthesize to a template that is under
51,200 bytes will successfully deploy.
$ cdk deploy --app='node bin/main.js' MyStackName
Before creating a change set, cdk deploy
will compare the template and tags of the
currently deployed stack to the template and tags that are about to be deployed and
will skip deployment if they are identical. Use --force
to override this behavior
and always deploy the stack.
Pass parameters to your template during deployment by using --parameters (STACK:KEY=VALUE)
. This will apply the value VALUE
to the key KEY
for stack STACK
.
Example of providing an attribute value for an SNS Topic through a parameter in TypeScript:
Usage of parameter in CDK Stack:
new sns.Topic(this, 'TopicParameter', {
topicName: new cdk.CfnParameter(this, 'TopicNameParam').value.toString()
});
Parameter values as a part of cdk deploy
$ cdk deploy --parameters "MyStackName:TopicNameParam=parameterized"
Parameter values can be overwritten by supplying the --force
flag.
Example of overwriting the topic name from a previous deployment.
$ cdk deploy --parameters "ParametersStack:TopicNameParam=blahagain" --force
⚠️ Parameters will be applied to all stacks if a stack name is not specified or *
is provided.
Parameters provided to Stacks that do not make use of the parameter will not successfully deploy.
⚠️ Parameters do not propagate to NestedStacks. These must be sent with the constructor. See Nested Stack documentation
Write stack outputs from deployments into a file. When your stack finishes deploying, all stack outputs will be written to the output file as JSON.
Usage of output in a CDK stack
const fn = new lambda.Function(this, "fn", {
handler: "index.handler",
code: lambda.Code.fromInline(`exports.handler = \${handler.toString()}`),
runtime: lambda.Runtime.NODEJS_10_X
});
new cdk.CfnOutput(this, 'FunctionArn', {
value: fn.functionArn,
});
Specify an outputs file to write to by supplying the --outputs-file
parameter
$ cdk deploy --outputs-file outputs.json
When the stack finishes deployment, outputs.json
would look like this:
{
"MyStack": {
"FunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:MyStack-fn5FF616E3-G632ITHSP5HK"
}
}
⚠️ The key
of the outputs corresponds to the logical ID of the CfnOutput
.
Read more about identifiers in the CDK here
If multiple stacks are being deployed or the wild card *
is used to deploy all stacks, all outputs
are written to the same output file where each stack artifact ID is a key in the JSON file
$ cdk deploy '*' --outputs-file "/Users/code/myproject/outputs.json"
Example outputs.json
after deployment of multiple stacks
{
"MyStack": {
"FunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:MyStack-fn5FF616E3-G632ITHSP5HK"
},
"AnotherStack": {
"VPCId": "vpc-z0mg270fee16693f"
}
}
cdk destroy
Deletes a stack from it's environment. This will cause the resources in the stack to be destroyed (unless they were
configured with a DeletionPolicy
of Retain
). During the stack destruction, the command will output progress
information similar to what cdk deploy
provides.
$ cdk destroy --app='node bin/main.js' MyStackName
cdk bootstrap
Deploys a CDKToolkit
CloudFormation stack into the specified environment(s), that provides an S3 bucket that
cdk deploy
will use to store synthesized templates and the related assets, before triggering a CloudFormation stack
update. The name of the deployed stack can be configured using the --toolkit-stack-name
argument.
$ # Deploys to all environments
$ cdk bootstrap --app='node bin/main.js'
$ # Deploys only to environments foo and bar
$ cdk bootstrap --app='node bin/main.js' foo bar
cdk doctor
Inspect the current command-line environment and configurations, and collect information that can be useful for troubleshooting problems. It is usually a good idea to include the information provided by this command when submitting a bug report.
$ cdk doctor
ℹ️ CDK Version: 1.0.0 (build e64993a)
ℹ️ AWS environment variables:
- AWS_EC2_METADATA_DISABLED = 1
- AWS_SDK_LOAD_CONFIG = 1
On top of passing configuration through command-line arguments, it is possible to use JSON configuration files. The configuration's order of precedence is:
./cdk.json
)~/.cdk.json
)Some of the interesting keys that can be used in the JSON configuration files:
{
"app": "node bin/main.js", // Command to start the CDK app (--app='node bin/main.js')
"context": { // Context entries (--context=key=value)
"key": "value"
},
"toolkitStackName": "foo", // Customize 'bootstrap' stack name (--toolkit-stack-name=foo)
"toolkitBucketName": "fooBucket", // Customize 'bootstrap' bucket name (--toolkit-bucket-name=fooBucket)
"versionReporting": false // Opt-out of version reporting (--no-version-reporting)
}
1.32.0 (2020-04-07)
UserPoolClient
construct no longer has the property
userPoolClientClientSecret
. The functionality to retrieve the client
secret never existed in CloudFormation, so this property was not
working in the first place.userPoolClientName
property on the UserPoolClient
construct will throw an error if client name was not configured on the
UserPoolClient
during initialization. This property was previously
incorrectly configured and was returning a not-implemented message from
CloudFormation every time.sourceCodeProvider
prop to connect your app to a source
code provider. The props repository
, accessToken
and oauthToken
do not exist
anymore in AppProps
.retentionPeriodHours
is now retentionPeriod
and of type Duration
Cluster
now creates a default managed nodegroup as its default capacity. Set the new cluster property defaultCapacityType
to DefaultCapacityType.EC2
to preserve EC2
as its default capacity.add*Trigger()
methods to configure
lambda triggers has now been replaced by a single
addTrigger()
method.addTrigger()
method will fail if a trigger
was already configured for that user pool operation.{[key: string]: any}
instead of plain any
. You were always supposed to pass a map/dictionary in these locations, but the type system didn't enforce it. It now does.aws:SecureTransport
for staging bucket (#7192) (ed106ea)Size
unit representing digital information quantity (#6940) (22a560d)acm-certificatemanager: DnsValidatedCertificateHandler support for SubjectAlternativeNames
(#7050) (a711c01), closes #4659
aws-kinesis: test assume order between stacks (#7065) (17aab37)
cli: can't use credential providers for stacks with assets (#7022) (afd7045), closes #7005
cloudtrail: include s3KeyPrefix in bucket policy resource (#7053) (b49881f), closes #6741
cognito: user pool - passwordPolicy.minLength
is not optional in all cases (#6971) (49cdd8f)
dynamodb: cannot use attribute as key in a GSI, non-key in another (#7075) (a6bd34f), closes #4398
ecs: default Service throws in a VPC without private subnets (#7188) (0ef6a95), closes #7062
events: Batch target does not work (#7191) (6f00783), closes #7137
kinesis: retention period does not use Duration type (#7037) (1186227), closes #7036
rewrite-imports: incorrect main in package.json (#7021) (2bf85b3)
stepfunctions-tasks: batch job - can not use task input as array size (#7008) (923d2a1), closes #6922
stepfunctions-tasks: confusion between multiple ways to run a Lambda (#6796) (7485448), closes #4801
FAQs
CDK Toolkit, the command line tool for CDK apps
The npm package aws-cdk receives a total of 1,739,933 weekly downloads. As such, aws-cdk popularity was classified as popular.
We found that aws-cdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.