• 沒有找到結果。

AWS Cloud Development Kit (CDK) v2 Developer Guide Version 2

N/A
N/A
Protected

Academic year: 2022

Share "AWS Cloud Development Kit (CDK) v2 Developer Guide Version 2"

Copied!
341
0
0

加載中.... (立即查看全文)

全文

(1)

AWS Cloud Development Kit (CDK) v2

Developer Guide

Version 2

(2)

AWS Cloud Development Kit (CDK) v2: Developer Guide

Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.

Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon.

(3)

Table of Contents

What is the AWS CDK? ... 1

Why use the AWS CDK? ... 2

Developing with the AWS CDK ... 6

The Construct Programming Model ... 6

Additional documentation and resources ... 6

Resources for serverless apps with CDK ... 7

Contributing to the AWS CDK ... 7

About Amazon Web Services ... 7

Getting started ... 8

Your background ... 8

Key concepts ... 8

Supported programming languages ... 10

Prerequisites ... 11

Install the AWS CDK ... 13

Bootstrapping ... 13

AWS CDK tools ... 13

Next steps ... 14

Your first AWS CDK app ... 14

Create the app ... 15

Build the app ... 16

List the stacks in the app ... 16

Add an Amazon S3 bucket ... 17

Synthesize an AWS CloudFormation template ... 19

Deploying the stack ... 19

Modifying the app ... 20

Destroying the app's resources ... 24

Next steps ... 24

Working with the AWS CDK ... 25

AWS CDK prerequisites ... 25

Language-specific prerequisites ... 25

AWS Construct Library ... 26

Interfaces vs. construct classes ... 27

In TypeScript ... 28

Prerequisites ... 28

Creating a project ... 28

Using local tsc and cdk ... 28

Managing AWS Construct Library modules ... 29

AWS CDK idioms in TypeScript ... 30

Building, synthesizing, and deploying ... 31

In JavaScript ... 31

Prerequisites ... 32

Creating a project ... 32

Using local cdk ... 28

Managing AWS Construct Library modules ... 33

AWS CDK idioms in JavaScript ... 34

Synthesizing and deploying ... 35

Using TypeScript examples with JavaScript ... 35

Migrating to TypeScript ... 37

In Python ... 38

Prerequisites ... 38

Creating a project ... 38

Managing AWS Construct Library modules ... 39

AWS CDK idioms in Python ... 40

Synthesizing and deploying ... 42

(4)

In Java ... 43

Prerequisites ... 43

Creating a project ... 43

Managing AWS Construct Library modules ... 44

AWS CDK idioms in Java ... 44

Building, synthesizing, and deploying ... 46

In C# ... 46

Prerequisites ... 46

Creating a project ... 47

Managing AWS Construct Library modules ... 47

AWS CDK idioms in C# ... 49

Building, synthesizing, and deploying ... 50

In Go ... 51

Prerequisites ... 51

Creating a project ... 51

Managing AWS Construct Library modules ... 52

AWS CDK idioms in Go ... 52

Building, synthesizing, and deploying ... 54

Migrating to AWS CDK v2 ... 55

New prerequisites ... 56

Upgrading from AWS CDK v2 Developer Preview ... 56

Migrating from AWS CDK v1 to CDK v2 ... 57

Updating feature flags ... 57

CDK Toolkit compatibility ... 57

Updating dependencies and imports ... 58

Troubleshooting ... 61

Translating from TypeScript ... 63

Importing a module ... 63

Instantiating a construct ... 65

Accessing members ... 66

Enum constants ... 67

Object interfaces ... 67

Concepts ... 69

Constructs ... 69

AWS Construct library ... 69

Composition ... 70

Initialization ... 70

Apps and stacks ... 70

Using L1 constructs ... 73

Using L2 constructs ... 75

Configuration ... 76

Interacting with constructs ... 77

Writing your own constructs ... 79

The construct tree ... 84

Apps ... 85

The app construct ... 86

App lifecycle ... 88

Cloud assemblies ... 89

Stacks ... 90

Stack API ... 96

Nested stacks ... 96

Environments ... 97

Resources ... 103

Resource attributes ... 104

Referencing resources ... 105

Accessing resources in a different stack ... 106

Physical names ... 108

(5)

Passing unique identifiers ... 109

Importing existing external resources ... 111

Permission grants ... 114

Metrics and alarms ... 115

Network traffic ... 117

Event handling ... 119

Removal policies ... 120

Identifiers ... 123

Construct IDs ... 123

Paths ... 125

Unique IDs ... 126

Logical IDs ... 127

Tokens ... 127

Tokens and token encodings ... 129

String-encoded tokens ... 130

List-encoded tokens ... 131

Number-encoded tokens ... 131

Lazy values ... 131

Converting to JSON ... 133

Parameters ... 134

Defining parameters ... 134

Using parameters ... 135

Deploying with parameters ... 137

Tagging ... 138

Tag priorities ... 139

Optional properties ... 140

Example ... 142

Assets ... 143

Assets in detail ... 144

Asset types ... 144

AWS CloudFormation resource metadata ... 157

Permissions ... 157

Principals ... 157

Grants ... 157

Roles ... 159

Resource policies ... 163

Context ... 164

Construct context ... 165

Context methods ... 165

Viewing and managing context ... 166

AWS CDK Toolkit --context flag ... 167

Example ... 167

Feature flags ... 170

Aspects ... 171

Aspects in detail ... 171

Example ... 172

Escape hatches ... 174

Using AWS CloudFormation constructs directly ... 174

Modifying the AWS CloudFormation resource behind AWS constructs ... 177

Raw overrides ... 179

Custom resources ... 180

Bootstrapping ... 181

How to bootstrap ... 181

Bootstrapping template ... 183

Customizing bootstrapping ... 184

Stack synthesizers ... 185

Customizing synthesis ... 186

(6)

The bootstrapping template contract ... 190

Best practices ... 193

Organization best practices ... 195

Coding best practices ... 195

Start simple and add complexity only when you need it ... 196

Align with the AWS Well-Architected framework ... 196

Every application starts with a single package in a single repository ... 196

Move code into repositories based on code lifecycle or team ownership ... 197

Infrastructure and runtime code live in the same package ... 197

Construct best practices ... 197

Model with constructs, deploy with stacks ... 197

Configure with properties and methods, not environment variables ... 198

Unit test your infrastructure ... 198

Don't change the logical ID of stateful resources ... 198

Constructs aren't enough for compliance ... 198

Application best practices ... 199

Make decisions at synthesis time ... 199

Use generated resource names, not physical names ... 199

Define removal policies and log retention ... 200

Separate your application into multiple stacks as dictated by deployment requirements ... 200

Commit cdk.context.json to avoid non-deterministic behavior ... 200

Let the AWS CDK manage roles and security groups ... 201

Model all production stages in code ... 201

Measure everything ... 202

API reference ... 203

Versioning ... 203

AWS CDK Toolkit (CLI) compatibility ... 203

AWS Construct Library versioning ... 203

Language binding stability ... 204

Examples ... 205

Serverless ... 205

Create an AWS CDK app ... 205

Create a Lambda function to list all widgets ... 207

Creating a widget service ... 208

Add the service to the app ... 212

Deploy and test the app ... 213

Add the individual widget functions ... 214

Clean up ... 217

ECS ... 218

Creating the directory and initializing the AWS CDK ... 219

Create a Fargate service ... 219

Clean up ... 222

AWS CDK examples ... 223

How tos ... 224

Get environment value ... 224

Get CloudFormation value ... 225

Import or migrate CloudFormation template ... 225

Importing a template ... 225

Accessing imported resources ... 229

Replacing parameters ... 230

Other template elements ... 231

Nested stacks ... 232

Use resources from the CloudFormation Public Registry ... 234

Activating a third-party resource in your account and region ... 235

Adding a resource from the AWS CloudFormation Public Registry to your CDK app ... 236

Get SSM value ... 237

Reading Systems Manager values at deployment time ... 237

(7)

Reading Systems Manager values at synthesis time ... 239

Writing values to Systems Manager ... 240

Get Secrets Manager value ... 240

Create an app with multiple stacks ... 242

Before you begin ... 242

Add optional parameter ... 243

Define the stack class ... 245

Create two stack instances ... 248

Synthesize and deploy the stack ... 250

Clean up ... 250

Set CloudWatch alarm ... 250

Using an existing metric ... 251

Creating your own metric ... 251

Creating the alarm ... 252

Get context value ... 254

Create CDK Pipeline ... 255

Bootstrap your AWS environments ... 255

Initialize project ... 257

Define a pipeline ... 258

Application stages ... 262

Testing deployments ... 270

Security notes ... 276

Troubleshooting ... 277

Tools ... 278

AWS CDK Toolkit ... 278

Toolkit commands ... 278

Specifying options and their values ... 279

Built-in help ... 279

Version reporting ... 280

Specifying credentials and region ... 281

Specifying the app command ... 282

Specifying stacks ... 283

Bootstrapping your AWS environment ... 283

Creating a new app ... 284

Listing stacks ... 285

Synthesizing stacks ... 285

Deploying stacks ... 286

Comparing stacks ... 288

Toolkit reference ... 290

AWS Toolkit for VS Code ... 296

SAM CLI ... 296

Testing constructs ... 298

Getting started ... 298

The example stack ... 300

Running tests ... 305

Fine-grained assertions ... 306

Matchers ... 310

Capturing ... 314

Snapshot tests ... 317

Tips for tests ... 321

Security ... 322

Identity and access management ... 322

Compliance validation ... 323

Resilience ... 323

Infrastructure security ... 324

Troubleshooting ... 325

OpenPGP keys ... 331

(8)

AWS CDK OpenPGP key ... 331 JSII OpenPGP key ... 332 Document history ... 333

(9)

What is the AWS CDK?

Welcome to the AWS Cloud Development Kit (CDK) Developer Guide. This document provides information about the AWS CDK, a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation.

NoteThe CDK has been released in two major versions, v1 and v2. This is the Developer Guide for AWS CDK v2.

The AWS CDK lets you build reliable, scalable, cost-effective applications in the cloud with the considerable expressive power of a programming language. This approach yields many benefits, including:

• Build with high-level constructs that automatically provide sensible, secure defaults for your AWS resources, defining more infrastructure with less code.

• Use programming idioms like parameters, conditionals, loops, composition, and inheritance to model your system design from building blocks provided by AWS and others.

• Put your infrastructure, application code, and configuration all in one place, ensuring that at every milestone you have a complete, cloud-deployable system.

• Employ software engineering practices such as code reviews, unit tests, and source control to make your infrastructure more robust.

• Connect your AWS resources together (even across stacks) and grant permissions using simple, intent- oriented APIs.

• Import existing AWS CloudFormation templates to give your resources a CDK API.

• Use the power of AWS CloudFormation to perform infrastructure deployments predictably and repeatedly, with rollback on error.

• Easily share infrastructure design patterns among teams within your organization or even with the public.

The AWS CDK supports TypeScript, JavaScript, Python, Java, C#/.Net, and (in developer preview) Go. Developers can use one of these supported programming languages to define reusable cloud components known as Constructs (p. 69). You compose these together into Stacks (p. 90) and Apps (p. 85).

(10)

Why use the AWS CDK?

Why use the AWS CDK?

It's easier to show than to explain! Here's some CDK code that creates an Amazon ECS service with AWS Fargate launch type (this is the code we use in the the section called “ECS” (p. 218)).

TypeScript

export class MyEcsConstructStack extends Stack {

constructor(scope: App, id: string, props?: StackProps) { super(scope, id, props);

const vpc = new ec2.Vpc(this, "MyVpc", { maxAzs: 3 // Default is all AZs in region });

const cluster = new ecs.Cluster(this, "MyCluster", { vpc: vpc

});

// Create a load-balanced Fargate service and make it public

new ecs_patterns.ApplicationLoadBalancedFargateService(this, "MyFargateService", { cluster: cluster, // Required

cpu: 512, // Default is 256 desiredCount: 6, // Default is 1

taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs- sample") },

memoryLimitMiB: 2048, // Default is 512

(11)

Why use the AWS CDK?

publicLoadBalancer: true // Default is false });

}}

JavaScript

class MyEcsConstructStack extends Stack { constructor(scope, id, props) {

super(scope, id, props);

const vpc = new ec2.Vpc(this, "MyVpc", { maxAzs: 3 // Default is all AZs in region });

const cluster = new ecs.Cluster(this, "MyCluster", { vpc: vpc

});

// Create a load-balanced Fargate service and make it public

new ecs_patterns.ApplicationLoadBalancedFargateService(this, "MyFargateService", { cluster: cluster, // Required

cpu: 512, // Default is 256 desiredCount: 6, // Default is 1

taskImageOptions: { image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs- sample") },

memoryLimitMiB: 2048, // Default is 512 publicLoadBalancer: true // Default is false });

} }

module.exports = { MyEcsConstructStack } Python

class MyEcsConstructStack(Stack):

def __init__(self, scope: Construct, id: str, **kwargs) -> None:

super().__init__(scope, id, **kwargs)

vpc = ec2.Vpc(self, "MyVpc", max_azs=3) # default is all AZs in region cluster = ecs.Cluster(self, "MyCluster", vpc=vpc)

ecs_patterns.ApplicationLoadBalancedFargateService(self, "MyFargateService", cluster=cluster, # Required

cpu=512, # Default is 256 desired_count=6, # Default is 1

task_image_options=ecs_patterns.ApplicationLoadBalancedTaskImageOptions(

image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")), memory_limit_mib=2048, # Default is 512

public_load_balancer=True) # Default is False Java

public class MyEcsConstructStack extends Stack {

public MyEcsConstructStack(final Construct scope, final String id) { this(scope, id, null);

}

public MyEcsConstructStack(final Construct scope, final String id,

(12)

Why use the AWS CDK?

StackProps props) { super(scope, id, props);

Vpc vpc = Vpc.Builder.create(this, "MyVpc").maxAzs(3).build();

Cluster cluster = Cluster.Builder.create(this, "MyCluster") .vpc(vpc).build();

ApplicationLoadBalancedFargateService.Builder.create(this, "MyFargateService") .cluster(cluster)

.cpu(512) .desiredCount(6) .taskImageOptions(

ApplicationLoadBalancedTaskImageOptions.builder() .image(ContainerImage

.fromRegistry("amazon/amazon-ecs-sample")) .build()).memoryLimitMiB(2048)

.publicLoadBalancer(true).build();

} }

C#

public class MyEcsConstructStack : Stack {

public MyEcsConstructStack(Construct scope, string id, IStackProps props=null) : base(scope, id, props)

{

var vpc = new Vpc(this, "MyVpc", new VpcProps {

MaxAzs = 3 });

var cluster = new Cluster(this, "MyCluster", new ClusterProps {

Vpc = vpc });

new ApplicationLoadBalancedFargateService(this, "MyFargateService", new ApplicationLoadBalancedFargateServiceProps

{

Cluster = cluster, Cpu = 512,

DesiredCount = 6,

TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {

Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample") },

MemoryLimitMiB = 2048, PublicLoadBalancer = true, });

} }

This class produces an AWS CloudFormation template of more than 500 lines; deploying the AWS CDK app produces more than 50 resources of the following types.

• AWS::EC2::EIP

• AWS::EC2::InternetGateway

• AWS::EC2::NatGateway

• AWS::EC2::Route

(13)

Why use the AWS CDK?

• AWS::EC2::RouteTable

• AWS::EC2::SecurityGroup

• AWS::EC2::Subnet

• AWS::EC2::SubnetRouteTableAssociation

• AWS::EC2::VPCGatewayAttachment

• AWS::EC2::VPC

• AWS::ECS::Cluster

• AWS::ECS::Service

• AWS::ECS::TaskDefinition

• AWS::ElasticLoadBalancingV2::Listener

• AWS::ElasticLoadBalancingV2::LoadBalancer

• AWS::ElasticLoadBalancingV2::TargetGroup

• AWS::IAM::Policy

• AWS::IAM::Role

• AWS::Logs::LogGroup

And let's not forget... code completion within your IDE or editor!

(14)

Developing with the AWS CDK

Developing with the AWS CDK

It's easy to get set up (p. 8) and write your first CDK app (p. 14). Short code examples are available throughout this Guide in the AWS CDK's supported programming languages: TypeScript, JavaScript, Python, Java, and C#. Longer examples are available in our GitHub repository.

The AWS CDK Toolkit (p. 278) is a command line tool for interacting with CDK apps. It enables

developers to synthesize artifacts such as AWS CloudFormation templates, deploy stacks to development AWS accounts, and diff against a deployed stack to understand the impact of a code change.

The AWS Construct Library (p. 69) offers constructs for each AWS service, many with "rich" APIs that provide high-level abstractions. The aim of the AWS Construct Library is to reduce the complexity and glue logic required when integrating various AWS services to achieve your goals on AWS.

NoteThere is no charge for using the AWS CDK, but you might incur AWS charges for creating or using AWS chargeable resources, such as running Amazon EC2 instances or using Amazon S3 storage. Use the AWS Pricing Calculator to estimate charges for the use of various AWS resources.

The Construct Programming Model

The Construct Programming Model (CPM) extends the concepts behind the AWS CDK into additional domains. Other tools using the CPM include:

• CDK for Terraform (CDKtf)

• CDK for Kubernetes (CDK8s)

• Projen, for building project configurations

Construct Hub is an online registry where you can find and publish construct libraries for CDKs like the AWS CDK.

Additional documentation and resources

In addition to this guide, the following other resources are available to AWS CDK users:

• API Reference

• AWS CDK Workshop

• cdk.dev community hub, including a Slack channel

• AWS CDK Examples

• CDK Patterns

• Awesome CDK

• AWS Solutions Constructs

• AWS Developer Blog CDK category

• Stack Overflow

• GitHub Repository

• Issues

• Examples

• Documentation Source

(15)

Resources for serverless apps with CDK

• License

• Releases

• AWS CDK OpenPGP key (p. 331)

• JSII OpenPGP key (p. 332)

• AWS CDK Sample for Cloud9

• AWS CloudFormation Concepts

• AWS Glossary

Resources for serverless apps with CDK

These tools can work with the AWS CDK to simplify serverless application development and deployment.

• AWS Serverless Application Model

• AWS Chalice, a Python serverless microframework

Contributing to the AWS CDK

Because the AWS CDK is open source, the team encourages you to contribute to make it an even better tool. For details, see Contributing.

About Amazon Web Services

Amazon Web Services (AWS) is a collection of digital infrastructure services that developers can use when developing their applications. The services include computing, storage, database, and application synchronization (messaging and queueing).

AWS uses a pay-as-you-go service model. You are charged only for the services that you — or your applications — use. Also, to make AWS useful as a platform for prototyping and experimentation, AWS offers a free usage tier, in which services are free below a certain level of usage. For more information about AWS costs and the free usage tier, see Test-Driving AWS in the Free Usage Tier.

To obtain an AWS account, go to aws.amazon.com, and then choose Create an AWS Account.

(16)

Your background

Getting started with the AWS CDK

This topic introduces you to important AWS CDK concepts and describes how to install and configure the AWS CDK. When you're done, you'll be ready to create your first AWS CDK app (p. 14).

Your background

The AWS Cloud Development Kit (CDK) lets you define your cloud infrastructure as code in one of its supported programming languages. It is intended for moderately to highly experienced AWS users.

Ideally, you already have experience with popular AWS services, particularly AWS Identity and Access Management (IAM). You might already have AWS credentials on your workstation for use with an AWS SDK or the AWS CLI and experience working with AWS resources programmatically.

Familiarity with AWS CloudFormation is also useful, as the output of an AWS CDK program is an AWS CloudFormation template.

Finally, you should be proficient in the programming language you intend to use with the AWS CDK.

Key concepts

The AWS CDK is designed around a handful of important concepts. We will introduce a few of these here briefly. Follow the links to learn more, or see the Concepts topics in this guide's Table of Contents.

An AWS CDK app (p. 85) is an application written in TypeScript, JavaScript, Python, Java, or C# that uses the AWS CDK to define AWS infrastructure. An app defines one or more stacks (p. 90). Stacks (equivalent to AWS CloudFormation stacks) contain constructs (p. 69), each of which defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, Amazon DynamoDB tables, and so on.

NoteThe AWS CDK also supports Go in a developer preview. This Guide does not include instructions or code examples for Go aside from the section called “In Go” (p. 51).

Constructs (as well as stacks and apps) are represented as classes (types) in your programming language of choice. You instantiate constructs within a stack to declare them to AWS, and connect them to each other using well-defined interfaces.

The AWS CDK includes the CDK Toolkit (also called the CLI), a command-line tool for working with your AWS CDK apps and stacks. Among other functions, the Toolkit provides the ability to convert one or more AWS CDK stacks to AWS CloudFormation templates and related assets (a process called synthesis) and to deploy your stacks to an AWS account.

The AWS CDK includes a library of AWS constructs called the AWS Construct Library, organized into various modules. The library contains constructs for each AWS service. The main CDK package is called aws-cdk-lib, and it contains the majority of the AWS Construct Library, along with base classes like Stack and App used in most CDK applications.

The actual package name of the main CDK package varies by language.

TypeScript

Install npm install aws-cdk-lib

(17)

Key concepts

Import const cdk = require('aws-cdk-lib');

JavaScript

Install npm install aws-cdk-lib

Import const cdk = require('aws-cdk-lib');

Python

Install python -m pip install aws-cdk-lib

Import import aws_cdk as cdk

Java

Add to pom.xml Group software.amazon.awscdk; artifact

aws-cdk-lib

Import import software.amazon.awscdk.App;

(for example)

C#

Install dotnet add package Amazon.CDK.Lib

Import using Amazon.CDK;

Constructs come in three fundamental flavors:

AWS CloudFormation-only or L1 (short for "layer 1"). These constructs correspond directly to resource types defined by AWS CloudFormation. In fact, these constructs are automatically generated from the AWS CloudFormation specification, so when a new AWS service is launched, the AWS CDK supports it a short time after AWS CloudFormation does.

AWS CloudFormation resources always have names that begin with Cfn. For example, for the Amazon S3 service, CfnBucket is the L1 construct for an Amazon S3 bucket.

All L1 resources are in aws-cdk-lib.

Curated or L2. These constructs are carefully developed by the AWS CDK team to address specific use cases and simplify infrastructure development. For the most part, they encapsulate L1 resources, providing sensible defaults and best-practice security policies. For example, Bucket is the L2 construct for an Amazon S3 bucket.

Libraries may also define supporting resources needed by the primary L2 resource. Some services have more than one L2 namespace in the Construct Library for organizational purposes.

aws-cdk-lib contains L2 constructs that are designated stable, i.e., ready for production use. If a service's L2 support is still under development, its constructs are designated experimental and provided in a separate module.

(18)

Supported programming languages

Patterns or L3. Patterns declare multiple resources to create entire AWS architectures for particular use cases. All the plumbing is already hooked up, and configuration is boiled down to a few important parameters.

As with L2 constructs, L3 constructs that are ready for production use (stable) are included in aws- cdk-lib, while those still under development are in separate modules.

Finally, the constructs package contains the Construct base class. It's in its own package because it is used not only by the AWS CDK but also by other construct-based tools, including CDK for Terraform and CDK for Kubernetes.

Numerous third parties have also published constructs compatible with the AWS CDK. Visit Construct Hub to explore the AWS CDK construct ecosystem.

Supported programming languages

The AWS CDK has first-class support for TypeScript, JavaScript, Python, Java, and C#. (Other JVM

and .NET CLR languages may also be used, at least in theory, but we are unable to offer support for them at this time.) Go support is available as a Developer Preview.

To facilitate supporting so many languages, the AWS CDK is developed in one language (TypeScript) and language bindings are generated for the other languages through the use of a tool called JSII.

We have taken pains to make AWS CDK app development in each language follow that language's usual conventions, so writing AWS CDK apps feels natural, not like writing TypeScript in Python (for example).

Take a look:

TypeScript

const bucket = new s3.Bucket(this, 'MyBucket', { bucketName: 'my-bucket',

versioned: true,

websiteRedirect: {hostName: 'aws.amazon.com'}});

JavaScript

const bucket = new s3.Bucket(this, 'MyBucket', { bucketName: 'my-bucket',

versioned: true,

websiteRedirect: {hostName: 'aws.amazon.com'}});

Python

bucket = s3.Bucket(self, "MyBucket", bucket_name="my-bucket", versioned=True, website_redirect=s3.RedirectTarget(host_name="aws.amazon.com"))

Java

Bucket bucket = Bucket.Builder.create(self, "MyBucket") .bucketName("my-bucket")

.versioned(true)

.websiteRedirect(new RedirectTarget.Builder() .hostName("aws.amazon.com").build()) .build();

(19)

Prerequisites

C#

var bucket = new Bucket(this, "MyBucket", new BucketProps { BucketName = "my-bucket",

Versioned = true,

WebsiteRedirect = new RedirectTarget { HostName = "aws.amazon.com"

}});

NoteThese code snippets are intended for illustration only. They are incomplete and won't run as they are.

The AWS Construct Library is distributed using each language's standard package management tools, including NPM, PyPi, Maven, and NuGet. There's even a version of the AWS CDK API Reference for each language.

To help you use the AWS CDK in your favorite language, this Guide includes topics that explain how to use the AWS CDK in all supported languages.

• the section called “In TypeScript” (p. 28)

• the section called “In JavaScript” (p. 31)

• the section called “In Python” (p. 38)

• the section called “In Java” (p. 43)

• the section called “In C#” (p. 46)

TypeScript was the first language supported by the AWS CDK, and much AWS CDK example code is written in TypeScript. This Guide includes a topic specifically to show how to adapt TypeScript AWS CDK code for use with the other supported languages. See Translating from TypeScript (p. 63).

Prerequisites

Here's what you need to install to use the AWS CDK.

All AWS CDK developers, even those working in Python, Java, or C#, need Node.js 10.13.0 or later.

All supported languages use the same back end, which runs on Node.js. We recommend a version in active long-term support, which, at this writing, is the latest 16.x release. Your organization may have a different recommendation.

Important

Node.js versions 13.0.0 through 13.6.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies.

You must configure your workstation with your credentials and an AWS region, if you have not already done so. If you have the AWS CLI installed, the easiest way to satisfy this requirement is issue the following command:

aws configure

Provide your AWS access key ID, secret access key, and default region when prompted.

You may also manually create or edit the ~/.aws/config and ~/.aws/credentials (macOS/Linux) or %USERPROFILE%\.aws\config and %USERPROFILE%\.aws\credentials (Windows) files to contain credentials and a default region, in the following format.

(20)

Prerequisites

• In ~/.aws/config or %USERPROFILE%\.aws\config [default]

region=us-west-2

• In ~/.aws/credentials or %USERPROFILE%\.aws\credentials [default]

aws_access_key_id=AKIAI44QH8DHBEXAMPLE

aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY

NoteAlthough the AWS CDK uses credentials from the same configuration files as other AWS tools and SDKs, including the AWS Command Line Interface, it may behave slightly differently from these tools. In particular, if you use a named profile from the credentials file, the config must have a profile of the same name specifying the region. The AWS CDK does not fall back to reading the region from the [default] section in config. Also, do not use a profile named

"default" (e.g. [profile default]). See Setting credentials for complete details on setting up credentials for the AWS SDK for JavaScript, which the AWS CDK uses under the hood.

AWS CDK does not natively support single sign-on (SSO). To use SSO with the CDK, use a tool such as yawsso.

Alternatively, you can set the environment variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_DEFAULT_REGION to appropriate values.

Important

We strongly recommend against using your AWS root account for day-to-day tasks. Instead, create a user in IAM and use its credentials with the CDK. Best practices are to change this account's access key regularly and to use a least-privileges role (specifying --role-arn) when deploying.

Other prerequisites depend on the language in which you develop AWS CDK applications and are as follows.

TypeScript

• TypeScript 2.7 or later (npm -g install typescript)

JavaScript

No additional requirements Python

• Python 3.6 or later including pip and virtualenv

Java

• Java Development Kit (JDK) 8 (a.k.a. 1.8) or later

• Apache Maven 3.5 or later

Java IDE recommended (we use Eclipse in some examples in this Developer Guide). IDE must be able to import Maven projects. Check to make sure your project is set to use Java 1.8. Set the JAVA_HOME environment variable to the path where you have installed the JDK.

C#

.NET Core 3.1 or later.

(21)

Install the AWS CDK

Visual Studio 2019 (any edition) or Visual Studio Code recommended.

Install the AWS CDK

Install the AWS CDK Toolkit globally using the following Node Package Manager command.

npm install -g aws-cdk

Run the following command to verify correct installation and print the version number of the AWS CDK.

cdk --version

NoteCDK Toolkit; v2 works with your existing CDK v1 projects. However, it can't initialize new CDK; v1 projects. See the section called “New prerequisites” (p. 56) if you need to be able to do that.

Bootstrapping

Many AWS CDK stacks that you write will include assets (p. 143): external files that are deployed with the stack, such as AWS Lambda functions or Docker images. The AWS CDK uploads these to an Amazon S3 bucket or other container so they are available to AWS CloudFormation during deployment.

Deployment requires that these containers already exist in the account and region you are deploying into. Creating them is called bootstrapping (p. 181). To bootstrap, issue:

cdk bootstrap aws://ACCOUNT-NUMBER/REGION

Tip

If you don't have your AWS account number handy, you can get it from the AWS Management Console. Or, if you have the AWS CLI installed, the following command displays your default account information, including the account number.

aws sts get-caller-identity

If you have created named profiles in your local AWS configuration, you can use the --profile option to display the account information for a specific profile's account, such as the prod profile as shown here.

aws sts get-caller-identity --profile prod

To display the default region, use aws configure get.

aws configure get region

aws configure get region --profile prod

AWS CDK tools

The AWS CDK Toolkit, also known as the Command Line Interface (CLI), is the main tool you use to interact with your AWS CDK app. It executes your code and produces and deploys the AWS CloudFormation templates it generates. It also has deployment, diff, deletion, and troubleshooting capabilities. For more information, see cdk --help or the section called “AWS CDK Toolkit” (p. 278).

(22)

Next steps

The AWS Toolkit for Visual Studio Code is an open-source plug-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application. Install the plug-in and learn more about using the AWS CDK Explorer.

Next steps

Where do you go now that you've dipped your toes in the AWS CDK?

• Come on in; the water's fine! Build your first AWS CDK app (p. 14).

• Try the CDK Workshop for a more in-depth tour involving a more complex project.

• See the API reference to begin exploring the provided constructs available for your favorite AWS services.

• Visit the Construct Hub to find constructs from the CDK community as well as from AWS.

• Dig deeper into concepts like the section called “Environments” (p. 97), the section called “Assets” (p. 143), the section called “Bootstrapping” (p. 181), the section called “Permissions” (p. 157), the section called “Context” (p. 164), the section called

“Parameters” (p. 134), and the section called “Escape hatches” (p. 174).

• Explore Examples of using the AWS CDK.

The AWS CDK is an open-source project. Want to contribute?

Your first AWS CDK app

You've read Getting started (p. 8) and set up your development environment for writing AWS CDK apps? Great! Now let's see how it feels to work with the AWS CDK by building the simplest possible AWS CDK app.

NoteThe AWS CDK supports Go in a developer preview. This tutorial does not include instructions or code examples for Go.

In this tutorial, you'll learn about the structure of a AWS CDK project, how to use the AWS Construct Library to define AWS resources using code, and how to synthesize, diff, and deploy collections of resources using the AWS CDK Toolkit command-line tool.

The standard AWS CDK development workflow is similar to the workflow you're already familiar with as a developer, just with a few extra steps.

1. Create the app from a template provided by the AWS CDK 2. Add code to the app to create resources within stacks

3. Build the app (optional; the AWS CDK Toolkit will do it for you if you forget)

4. Synthesize one or more stacks in the app to create an AWS CloudFormation template 5. Deploy one or more stacks to your AWS account

The build step catches syntax and type errors. The synthesis step catches logical errors in defining your AWS resources. The deployment may find permission issues. As always, you go back to the code, find the problem, fix it, then build, synthesize and deploy again.

TipDon't forget to keep your AWS CDK code under version control!

(23)

Create the app

This tutorial walks you through creating and deploying a simple AWS CDK app, from initializing the project to deploying the resulting AWS CloudFormation template. The app contains one stack, which contains one resource: an Amazon S3 bucket.

We'll also show what happens when you make a change and re-deploy, and how to clean up when you're done.

Create the app

Each AWS CDK app should be in its own directory, with its own local module dependencies. Create a new directory for your app. Starting in your home directory, or another directory if you prefer, issue the following commands.

Important

Be sure to name your project directory hello-cdk, exactly as shown here. The AWS CDK project template uses the directory name to name things in the generated code, so if you use a different name, the code in this tutorial won't work.

mkdir hello-cdk cd hello-cdk

Now initialize the app using the cdk init command, specifying the desired template ("app") and programming language. That is:

TypeScript

cdk init app --language typescript

JavaScript

cdk init app --language javascript

Python

cdk init app --language python

After the app has been created, also enter the following two commands to activate the app's Python virtual environment and install the AWS CDK core dependencies.

source .venv/bin/activate

python -m pip install -r requirements.txt

Java

cdk init app --language java

If you are using an IDE, you can now open or import the project. In Eclipse, for example, choose File

> Import > Maven > Existing Maven Projects. Make sure that the project settings are set to use Java 8 (1.8).

C#

cdk init app --language csharp

If you are using Visual Studio, open the solution file in the src directory.

(24)

Build the app

TipIf you don't specify a template, the default is "app," which is the one we wanted anyway, so technically you can leave it out and save four keystrokes.

The cdk init command creates a number of files and folders inside the hello-cdk directory to help you organize the source code for your AWS CDK app. Take a moment to explore. The structure of a basic app is all there; you'll fill in the details in this tutorial.

If you have Git installed, each project you create using cdk init is also initialized as a Git repository. We'll ignore that for now, but it's there when you need it.

Build the app

In most programming environments, after making changes to your code, you'd build (compile) it. This isn't strictly necessary with the AWS CDK—the Toolkit does it for you so you can't forget. But you can still build manually whenever you want to catch syntax and type errors. For reference, here's how.

TypeScript

npm run build

JavaScript

No build step is necessary.

Python

No build step is necessary.

Java

mvn compile -q

Or press Control-B in Eclipse (other Java IDEs may vary) C#

dotnet build src

Or press F6 in Visual Studio

NoteIf your project was created with an older version of the AWS CDK Toolkit, it may not

automatically build when you run it. If changes you make in your code fail to be reflected in the synthesized template, try a manual build. Make sure you are using the latest available version of the AWS CDK for this tutorial.

List the stacks in the app

Just to verify everything is working correctly, list the stacks in your app.

cdk ls

If you don't see HelloCdkStack, make sure you named your app's directory hello-cdk. If you didn't, go back to the section called “Create the app” (p. 15) and try again.

(25)

Add an Amazon S3 bucket

Add an Amazon S3 bucket

At this point, your app doesn't do anything because the stack it contains doesn't define any resources.

Let's add an Amazon S3 bucket.

The CDK's Amazon S3 support is part of its main library, aws-cdk-lib, so we don't need to install another library. We can just define an Amazon S3 bucket in the stack using the Bucket construct.

TypeScript

In lib/hello-cdk-stack.ts:

import * as cdk from 'aws-cdk-lib';

import { aws_s3 as s3 } from 'aws-cdk-lib';

export class HelloCdkStack extends cdk.Stack {

constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props);

new s3.Bucket(this, 'MyFirstBucket', { versioned: true

});

}}

JavaScript

In lib/hello-cdk-stack.js:

const cdk = require('aws-cdk-lib');

const s3 = require('aws-cdk-lib/aws-s3');

class HelloCdkStack extends cdk.Stack { constructor(scope, id, props) { super(scope, id, props);

new s3.Bucket(this, 'MyFirstBucket', { versioned: true

});

} }

module.exports = { HelloCdkStack }

Python

In hello_cdk/hello_cdk_stack.py:

import aws_cdk as cdk import aws_cdk.aws_s3 as s3

class HelloCdkStack(cdk.Stack):

def __init__(self, scope: cdk.App, construct_id: str, **kwargs) -> None:

super().__init__(scope, construct_id, **kwargs)

bucket = s3.Bucket(self, "MyFirstBucket", versioned=True)

Java

In src/main/java/com/myorg/HelloCdkStack.java:

(26)

Add an Amazon S3 bucket

package com.myorg;

import software.amazon.awscdk.*;

import software.amazon.awscdk.services.s3.Bucket;

public class HelloCdkStack extends Stack {

public HelloCdkStack(final App scope, final String id) { this(scope, id, null);

}

public HelloCdkStack(final App scope, final String id, final StackProps props) { super(scope, id, props);

Bucket.Builder.create(this, "MyFirstBucket") .versioned(true).build();

} }

C#

In src/HelloCdk/HelloCdkStack.cs:

using Amazon.CDK;

using Amazon.CDK.AWS.S3;

namespace HelloCdk

{ public class HelloCdkStack : Stack {

public HelloCdkStack(App scope, string id, IStackProps props=null) : base(scope, id, props)

{

new Bucket(this, "MyFirstBucket", new BucketProps {

Versioned = true });

} } }

Bucket is the first construct we've seen, so let's take a closer look. Like all constructs, the Bucket class takes three parameters.

scope: Tells the bucket that the stack is its parent: it is defined within the scope of the stack. You can define constructs inside of constructs, creating a hierarchy (tree). Here, and in most cases, the scope is this (self in Python), meaning the construct that contains the bucket: the stack.

Id: The logical ID of the Bucket within your AWS CDK app. This (plus a hash based on the bucket's location within the stack) uniquely identifies the bucket across deployments so the AWS CDK can update it if you change how it's defined in your app. Here it is "MyFirstBucket." Buckets can also have a name, which is separate from this ID (it's the bucketName property).

props: A bundle of values that define properties of the bucket. Here we've defined only one property:

versioned, which enables versioning for the files in the bucket.

All constructs take these same three arguments, so it's easy to stay oriented as you learn about new ones.

And as you might expect, you can subclass any construct to extend it to suit your needs, or just to change its defaults.

TipIf a construct's props are all optional, you can omit the props parameter entirely.

(27)

Synthesize an AWS CloudFormation template

Props are represented differently in the languages supported by the AWS CDK.

• In TypeScript and JavaScript, props is a single argument and you pass in an object containing the desired properties.

• In Python, props are passed as keyword arguments.

• In Java, a Builder is provided to pass the props. Two, actually; one for BucketProps, and a second for Bucket to let you build the construct and its props object in one step. This code uses the latter.

• In C#, you instantiate a BucketProps object using an object initializer and pass it as the third parameter.

Synthesize an AWS CloudFormation template

Synthesize an AWS CloudFormation template for the app, as follows.

cdk synth

If your app contained more than one stack, you'd need to specify which stack(s) to synthesize. But since it only contains one, the CDK Toolkit knows you must mean that one.

TipIf you received an error like --app is required..., it's probably because you are running the command from a subdirectory. Navigate to the main app directory and try again.

The cdk synth command executes your app, which causes the resources defined in it to be translated into an AWS CloudFormation template. The displayed output of cdk synth is a YAML-format template;

the beginning of our app's output is shown below. The template is also saved in the cdk.out directory in JSON format.

Resources:

MyFirstBucketB8884501:

Type: AWS::S3::Bucket Properties:

VersioningConfiguration:

Status: Enabled

UpdateReplacePolicy: Retain DeletionPolicy: Retain Metadata:...

Even if you aren't very familiar with AWS CloudFormation, you should be able to find the definition for the bucket and see how the versioned property was translated.

NoteEvery generated template contains a AWS::CDK::Metadata resource by default. (We haven't shown it here.) The AWS CDK team uses this metadata to gain insight into how the AWS CDK is used, so we can continue to improve it. For details, including how to opt out of version reporting, see Version reporting (p. 280).

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.

Deploying the stack

To deploy the stack using AWS CloudFormation, issue:

cdk deploy

(28)

Modifying the app

As with cdk synth, you don't need to specify the name of the stack since there's only one in the app.

It is optional (though good practice) to synthesize before deploying. The AWS CDK synthesizes your stack before each deployment.

If your code has security implications, you'll see a summary of these and need to confirm them before deployment proceeds. This isn't the case in our stack.

cdk deploy displays progress information as your stack is deployed. When it's done, the command prompt reappears. You can go to the AWS CloudFormation console and see that it now lists

HelloCdkStack. You'll also find MyFirstBucket in the Amazon S3 console.

You've deployed your first stack using the AWS CDK—congratulations! But that's not all there is to the AWS CDK.

Modifying the app

The AWS CDK can update your deployed resources after you modify your app. Let's change our bucket so it can be automatically deleted when we delete the stack, which involves changing its

RemovalPolicy. Also, because AWS CloudFormation won't delete Amazon S3 buckets that contain any objects, we'll ask the AWS CDK to delete the objects from our bucket before destroying the bucket, via the autoDeleteObjects property.

TypeScript

Update lib/hello-cdk-stack.ts.

new s3.Bucket(this, 'MyFirstBucket', { versioned: true,

removalPolicy: cdk.RemovalPolicy.DESTROY, autoDeleteObjects: true

});

JavaScript

Update lib/hello-cdk-stack.js.

new s3.Bucket(this, 'MyFirstBucket', { versioned: true,

removalPolicy: cdk.RemovalPolicy.DESTROY, autoDeleteObjects: true

});

Python

Update hello_cdk/hello_cdk_stack.py.

bucket = s3.Bucket(self, "MyFirstBucket", versioned=True,

removal_policy=cdk.RemovalPolicy.DESTROY, auto_delete_objects=True)

Java

Update src/main/java/com/myorg/HelloCdkStack.java.

Bucket.Builder.create(this, "MyFirstBucket")

(29)

Modifying the app

.versioned(true)

.removalPolicy(RemovalPolicy.DESTROY) .autoDeleteObjects(true)

.build();

C#

Update src/HelloCdk/HelloCdkStack.cs.

new Bucket(this, "MyFirstBucket", new BucketProps {

Versioned = true,

RemovalPolicy = RemovalPolicy.DESTROY, AutoDeleteObjects = true

});

Here, we haven't written any code that, in itself, changes our Amazon S3 bucket. Instead, our code defines the desired state of the bucket. The AWS CDK synthesizes that state to a new AWS

CloudFormation template and deploys a changeset that makes only the changes necessary to reach that state.

To see these changes, we'll use the cdk diff command .

cdk diff

The AWS CDK Toolkit queries your AWS account for the last-deployed AWS CloudFormation template for the HelloCdkStack and compares it with the template it just synthesized from your app. The output should look like the following.

Stack HelloCdkStack IAM Statement Changes

#######################################################################################################################

# # Resource # Effect # Action # Principal # Condition #

#######################################################################################################################

# + # ${Custom::S3AutoDeleteObject # Allow # sts:AssumeRole # Service:lambda.amazonaws.com # #

# # sCustomResourceProvider/Role # # # # #

# # .Arn} # # # # #

#######################################################################################################################

# + # ${MyFirstBucket.Arn} # Allow # s3:DeleteObject* # AWS:

${Custom::S3AutoDeleteOb # #

# # ${MyFirstBucket.Arn}/* # # s3:GetBucket* # jectsCustomResourceProvider/ # #

# # # # s3:GetObject* # Role.Arn}

# #

# # # # s3:List* # # #

#######################################################################################################################

IAM Policy Changes

#######################################################################################################################

# # Resource # Managed Policy ARN #

#######################################################################################################################

# + # ${Custom::S3AutoDeleteObjectsCustomResourceProvider/Ro # {"Fn::Sub":"arn:

${AWS::Partition}:iam::aws:policy/serv #

# # le} # ice-role/

AWSLambdaBasicExecutionRole"} #

(30)

Modifying the app

#######################################################################################################################

(NOTE: There may be security-related changes not in this list. See https://github.com/aws/

aws-cdk/issues/1299) Parameters

[+] Parameter

AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/S3Bucket AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392S3BucketBF7A7F3F:

{"Type":"String","Description":"S3 bucket for asset

\"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""}

[+] Parameter

AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/

S3VersionKey

AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392S3VersionKeyFAF93626:

{"Type":"String","Description":"S3 key for asset version

\"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""}

[+] Parameter

AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/

ArtifactHash

AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392ArtifactHashE56CD69A:

{"Type":"String","Description":"Artifact hash for asset

\"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""}

Resources

[+] AWS::S3::BucketPolicy MyFirstBucket/Policy MyFirstBucketPolicy3243DEFD [+] Custom::S3AutoDeleteObjects MyFirstBucket/AutoDeleteObjectsCustomResource MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E

[+] AWS::IAM::Role Custom::S3AutoDeleteObjectsCustomResourceProvider/Role CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092

[+] AWS::Lambda::Function Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F

[~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 ## [~] DeletionPolicy

# ## [-] Retain # ## [+] Delete

## [~] UpdateReplacePolicy ## [-] Retain

## [+] Delete

This diff has four sections.

IAM Statement Changes and IAM Policy Changes - These permission changes are there because we set the AutoDeleteObjects property on our Amazon S3 bucket. The auto-delete feature uses a custom resource to delete the objects in the bucket before the bucket itself is deleted. The IAM objects grant the custom resource's code access to the bucket.

Parameters - The AWS CDK uses these entries to locate the Lambda function asset for the custom resource.

Resources - The new and changed resources in this stack. We can see the aforementioned IAM objects, the custom resource, and its associated Lambda function being added. We can also see that the bucket's DeletionPolicy and UpdateReplacePolicy attributes are being updated. These allow the bucket to be deleted along with the stack, and to be replaced with a new one.

You may be curious about why we specified RemovalPolicy in our AWS CDK app but got a DeletionPolicy property in the resulting AWS CloudFormation template. The AWS CDK uses a different name for the property because the AWS CDK default is to retain the bucket when the stack is deleted, while AWS CloudFormation's default is to delete it. See the section called “Removal policies” (p. 120) for further details.

It's informative to compare the output of cdk synth here with the previous output and see the many additional lines of AWS CloudFormation template that the AWS CDK generated for us based on these relatively small changes.

(31)

Modifying the app

Important

Since the autoDeleteObjects property is implemented using a AWS CloudFormation custom resource, which is implemented using an AWS Lambda function, our stack contains an asset (p. 143). This fact requires that our AWS account and region be bootstrapped (p. 181) so that there's an Amazon S3 bucket to hold the asset during deployment. If you haven't already bootstrapped, issue:

cdk bootstrap aws://ACCOUNT-NUMBER/REGION

Now let's deploy.

cdk deploy

The AWS CDK warns you about the security policy changes we've already seen in the diff. Enter y to approve the changes and deploy the updated stack. The CDK Toolkit updates the bucket configuration as you requested.

HelloCdkStack: deploying...

[0%] start: Publishing

4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392:current [100%] success: Published

4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392:current HelloCdkStack: creating CloudFormation changeset...

0/5 | 4:32:31 PM | UPDATE_IN_PROGRESS | AWS::CloudFormation::Stack | HelloCdkStack User Initiated

0/5 | 4:32:36 PM | CREATE_IN_PROGRESS | AWS::IAM::Role | Custom::S3AutoDeleteObjectsCustomResourceProvider/Role (CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092)

1/5 | 4:32:36 PM | UPDATE_COMPLETE | AWS::S3::Bucket | MyFirstBucket (MyFirstBucketB8884501)

1/5 | 4:32:36 PM | CREATE_IN_PROGRESS | AWS::IAM::Role | Custom::S3AutoDeleteObjectsCustomResourceProvider/Role

(CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092) Resource creation Initiated 3/5 | 4:32:54 PM | CREATE_COMPLETE | AWS::IAM::Role

| Custom::S3AutoDeleteObjectsCustomResourceProvider/Role (CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092) 3/5 | 4:32:56 PM | CREATE_IN_PROGRESS | AWS::Lambda::Function | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F)

3/5 | 4:32:56 PM | CREATE_IN_PROGRESS | AWS::S3::BucketPolicy | MyFirstBucket/

Policy (MyFirstBucketPolicy3243DEFD)

3/5 | 4:32:56 PM | CREATE_IN_PROGRESS | AWS::Lambda::Function | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler

(CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F) Resource creation Initiated

3/5 | 4:32:57 PM | CREATE_COMPLETE | AWS::Lambda::Function | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F)

3/5 | 4:32:57 PM | CREATE_IN_PROGRESS | AWS::S3::BucketPolicy | MyFirstBucket/

Policy (MyFirstBucketPolicy3243DEFD) Resource creation Initiated

4/5 | 4:32:57 PM | CREATE_COMPLETE | AWS::S3::BucketPolicy | MyFirstBucket/

Policy (MyFirstBucketPolicy3243DEFD)

4/5 | 4:32:59 PM | CREATE_IN_PROGRESS | Custom::S3AutoDeleteObjects | MyFirstBucket/AutoDeleteObjectsCustomResource/Default

(MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E)

5/5 | 4:33:06 PM | CREATE_IN_PROGRESS | Custom::S3AutoDeleteObjects | MyFirstBucket/AutoDeleteObjectsCustomResource/Default

(MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E) Resource creation Initiated 5/5 | 4:33:06 PM | CREATE_COMPLETE | Custom::S3AutoDeleteObjects

| MyFirstBucket/AutoDeleteObjectsCustomResource/Default (MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E)

5/5 | 4:33:08 PM | UPDATE_COMPLETE_CLEA | AWS::CloudFormation::Stack | HelloCdkStack

(32)

Destroying the app's resources

6/5 | 4:33:09 PM | UPDATE_COMPLETE | AWS::CloudFormation::Stack | HelloCdkStack # HelloCdkStack

Stack ARN:

arn:aws:cloudformation:REGION:ACCOUNT:stack/HelloCdkStack/UNIQUE-ID

Destroying the app's resources

Now that you're done with the quick tour, destroy your app's resources to avoid incurring any costs from the bucket you created, as follows.

cdk destroy

Enter y to approve the changes and delete any stack resources.

Note

If we hadn't changed the bucket's RemovalPolicy, the stack deletion would complete successfully, but the bucket would become orphaned (no longer associated with the stack).

Next steps

Where do you go now that you've dipped your toes in the AWS CDK?

• Try the CDK Workshop for a more in-depth tour involving a more complex project.

• Dig deeper into concepts like the section called “Environments” (p. 97), the section called

“Assets” (p. 143), the section called “Permissions” (p. 157), the section called “Context” (p. 164), the section called “Parameters” (p. 134), and the section called “Escape hatches” (p. 174).

• See the API reference to begin exploring the CDK constructs available for your favorite AWS services.

• Visit Construct Hub to discover constructs created by AWS and others.

• Explore Examples of using the AWS CDK.

The AWS CDK is an open-source project. Want to contribute?

(33)

AWS CDK prerequisites

Working with the AWS CDK

The AWS Cloud Development Kit (CDK) lets you define your AWS cloud infrastructure in a general- purpose programming language. Currently, the AWS CDK supports TypeScript, JavaScript, Python, Java, C#, and (in developer preview) Go. It is also possible to use other JVM and .NET languages, though we are unable to provide support for every such language.

NoteThis Guide does not currently include instructions or code examples for Go aside from the section called “In Go” (p. 51). Go support is currently in developer preview.

We develop the AWS CDK in TypeScript and use JSII to provide a "native" experience in other supported languages. For example, we distribute AWS Construct Library modules using your preferred language's standard repository, and you install them using the language's standard package manager. Methods and properties are even named using your language's recommended naming patterns.

AWS CDK prerequisites

To use the AWS CDK, you need an AWS account and a corresponding access key. If you don't have an AWS account yet, see Create and Activate an AWS Account. To find out how to obtain an access key ID and secret access key for your AWS account, see Understanding and Getting Your Security Credentials. To find out how to configure your workstation so the AWS CDK uses your credentials, see Setting Credentials in Node.js.

Tip

If you have the AWS CLI installed, the simplest way to set up your workstation with your AWS credentials is to open a command prompt and type:

aws configure

All AWS CDK applications require Node.js 10.13 or later, even if you work in Python, Java, or C#. You may download a compatible version at nodejs.org. We recommend the active LTS version (at this writing, the latest 16.x release). Node.js versions 13.0.0 through 13.6.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies.

After installing Node.js, install the AWS CDK Toolkit (the cdk command):

npm install -g aws-cdk

NoteIf you get a permission error, and have administrator access on your system, try sudo npm install -g aws-cdk.

Test the installation by issuing cdk --version.

If you get an error message at this point, try uninstalling (npm uninstall -g aws-cdk) and reinstalling. As a last resort, delete the node-modules folder from the current project as well as the global node-modules folder. To figure out where this folder is, issue npm config get prefix.

Language-specific prerequisites

The specific language you work in also has its own prerequisites, described in the corresponding topic listed here.

(34)

AWS Construct Library

• the section called “In TypeScript” (p. 28)

• the section called “In JavaScript” (p. 31)

• the section called “In Python” (p. 38)

• the section called “In Java” (p. 43)

• the section called “In C#” (p. 46)

• the section called “In Go” (p. 51)

AWS Construct Library

The AWS CDK includes the AWS Construct Library, a collection of constructs organized by AWS service.

The library's constructs are mainly in a single module, colloquially called aws-cdk-lib because that's its name in TypeScript. The actual package name of the main CDK package varies by language.

TypeScript

Install npm install aws-cdk-lib

Import const cdk = require('aws-cdk-lib');

JavaScript

Install npm install aws-cdk-lib

Import const cdk = require('aws-cdk-lib');

Python

Install python -m pip install aws-cdk-lib

Import import aws_cdk as cdk

Java

Add to pom.xml Group software.amazon.awscdk; artifact

aws-cdk-lib

Import import software.amazon.awscdk.App;

(for example)

C#

Install dotnet add package Amazon.CDK.Lib

Import using Amazon.CDK;

NoteExperimental constructs are provided as separate modules.

(35)

Interfaces vs. construct classes

The AWS CDK API Reference provides detailed documentation of the constructs (and other components) in the library. A version of the API Reference is provided for each supported programming language.

Each module's reference material is broken into the following sections.

• Overview: Introductory material you'll need to know to work with the service in the AWS CDK, including concepts and examples.

• Constructs: Library classes that represent one or more concrete AWS resources. These are the

"curated" (L2) resources or patterns (L3 resources) that provide a high-level interface with sane defaults.

• Classes: Non-construct classes that provide functionality used by constructs in the module.

• Structs: Data structures (attribute bundles) that define the structure of composite values such as properties (the props argument of constructs) and options.

• Interfaces: Interfaces, whose names all begin with "I", define the absolute minimum functionality for the corresponding construct or other class. The CDK uses construct interfaces to represent AWS resources that are defined outside your AWS CDK app and imported by methods such as Bucket.fromBucketArn().

• Enums: Collections of named values for use in specifying *certain construct parameters. Using an enumerated value allows the CDK to check these values for validity during synthesis.

• CloudFormation Resources: These L1 constructs, whose names begin with "Cfn", represent exactly the resources defined in the CloudFormation specification. They are automatically generated from that specification with each CDK release. Each L2 or L3 construct encapsulates one or more CloudFormation resources.

• CloudFormation Property Types: The collection of named values that define the properties for each CloudFormation Resource.

Interfaces vs. construct classes

The AWS CDK uses interfaces in a specific way that might not be obvious even if you are familiar with interfaces as a programming concept.

The AWS CDK supports importing resources defined outside CDK applications using methods such as Bucket.fromBucketArn(). Imported resources cannot be modified and may not have all the functionality available with resources defined in your CDK app using e.g. the Bucket class. Interfaces, then, represent the bare minimum functionality available in the CDK for a given AWS resource type, including imported resources.

When instantiating resources in your CDK app, then, you should always use concrete classes such as Bucket. When specifying the type of an argument you are accepting in one of your own constructs, use the interface type such as IBucket if you are prepared to deal with imported resources (that is, you won't need to change them). If you require a CDK-defined construct, specify the most general type you can use.

Some interfaces are minimum versions of properties or options bundles (shown in the AWS CDK API Reference as Structs) that are associated with specific constructs. For example, IBucketProps is the smallest set of properties required to instantiate a bucket. Such interfaces can be useful when subclassing constructs to accept arguments that you'll pass on to your parent class. If you require one or more additional properties, you'll want to implement or derive from this interface, or from a more specific type such as BucketProps.

NoteSome programming languages supported by the AWS CDK don't have an interface feature. In these languages, interfaces are just ordinary classes. You can identify them by their names, which follow the pattern of an initial "I" followed by the name of some other construct (e.g.

IBucket). The same rules apply.

參考文獻

相關文件

• The  ArrayList class is an example of a  collection class. • Starting with version 5.0, Java has added a  new kind of for loop called a for each

A quote from Dan Ariely, “Big data is like teenage sex: everyone talks about it, nobody really knows how to do it, everyone thinks everyone else is doing it, so everyone claims they

The Secondary Education Curriculum Guide (SECG) is prepared by the Curriculum Development Council (CDC) to advise secondary schools on how to sustain the Learning to

(a) In your group, discuss what impact the social issues in Learning Activity 1 (and any other socials issues you can think of) have on the world, Hong Kong and you.. Choose the

• Teaching grammar through texts enables students to see how the choice of language items is?. affected by the context and how it shapes the tone, style and register of

The course objective is designed to let students learn the following topics: (1) international trade, (2) business letters highly used in trade, (2) business letters highly used

If necessary, you might like to guide students to read over the notes and discuss the roles and language required of a chairperson or secretary to prepare them for the activity9.

• Suppose, instead, we run the algorithm for the same running time mkT (n) once and rejects the input if it does not stop within the time bound.. • By Markov’s inequality, this