CDK基础设施
AWS CDK 是一个用于通过代码定义云基础设施并通过 AWS CloudFormation 进行配置的框架。
TypeScript 基础设施生成器会创建一个用 TypeScript 编写的 AWS CDK 基础设施应用程序。生成的应用程序通过 CFN Guard 检查包含安全最佳实践。
使用方法
生成基础设施项目
您可以通过两种方式生成新的基础设施项目:
- 安装 Nx Console VSCode Plugin 如果您尚未安装
- 在VSCode中打开Nx控制台
- 点击
Generate (UI)
在"Common Nx Commands"部分 - 搜索
@aws/nx-plugin - ts#infra
- 填写必需参数
- 点击
Generate
pnpm nx g @aws/nx-plugin:ts#infra
yarn nx g @aws/nx-plugin:ts#infra
npx nx g @aws/nx-plugin:ts#infra
bunx nx g @aws/nx-plugin:ts#infra
选项
参数 | 类型 | 默认值 | 描述 |
---|---|---|---|
name 必需 | string | - | The name of the application. |
ruleSet | string | aws_prototyping | Rule set to validate your AWS resources with. |
directory | string | packages | The directory of the new application. |
生成器输出
生成器将在 <directory>/<name>
目录下创建以下项目结构:
文件夹src
- main.ts 实例化要部署的 CDK 堆栈的应用程序入口点
文件夹stacks CDK 堆栈定义
- application-stack.ts 主应用程序堆栈
- cdk.json CDK 配置
- project.json 项目配置和构建目标
实现您的 CDK 基础设施
您可以在 src/stacks/application-stack.ts
中开始编写 CDK 基础设施代码,例如:
import * as cdk from 'aws-cdk-lib';import { Bucket } from 'aws-cdk-lib/aws-s3'import { Construct } from 'constructs';
export class ApplicationStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props);
// 在此声明您的基础设施 new Bucket(this, 'MyBucket'); }}
API 基础设施
如果您使用过 tRPC API 或 FastAPI 生成器创建 API,您会注意到在 packages/common/constructs
中已有一些用于部署它们的构造。
例如,如果您创建了一个名为 my-api
的 tRPC API,只需导入并实例化该构造即可添加部署所需的所有基础设施:
import * as cdk from 'aws-cdk-lib';import { Construct } from 'constructs';import { MyApi } from ':my-scope/common-constructs';
export class ApplicationStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props);
// 为您的 API 添加基础设施 new MyApi(this, 'MyApi'); }}
网站基础设施
如果您使用过 CloudScape 网站 生成器,您会注意到在 packages/common/constructs
中已有用于部署它的构造。例如:
import * as cdk from 'aws-cdk-lib';import { Construct } from 'constructs';import { MyWebsite } from ':my-scope/common-constructs';
export class ApplicationStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props);
// 为您的网站添加基础设施 new MyWebsite(this, 'MyWebsite'); }}
必须确保在声明网站构造 之后 声明任何 API 构造,以便网站的 运行时配置 能包含所有 API 配置。
合成您的基础设施
作为 build
目标的一部分,除了运行 默认的编译、lint 和测试目标 外,您的基础设施项目会被 合成 为 CloudFormation。也可以通过单独执行 synth
目标来运行:
pnpm nx run <my-infra>:synth
yarn nx run <my-infra>:synth
npx nx run <my-infra>:synth
bunx nx run <my-infra>:synth
您可以在根 dist
文件夹下的 dist/packages/<my-infra-project>/cdk.out
中找到合成后的云汇编产物。
引导您的 AWS 账户
如果是首次向某个 AWS 账户部署 CDK 应用程序,需要先进行账户引导。
首先,确保已 为 AWS 账户配置凭证。
接下来,可以使用 cdk bootstrap
命令:
npx cdk bootstrap aws://<account-id>/<region>
更多细节请参考 CDK 文档。
部署到 AWS
构建完成后,可以使用 deploy
目标将基础设施部署到 AWS。
首先,确保已 为 AWS 账户配置凭证。
然后运行部署目标:
pnpm nx run <my-infra>:deploy --all
yarn nx run <my-infra>:deploy --all
npx nx run <my-infra>:deploy --all
bunx nx run <my-infra>:deploy --all