Skip to content

Commit

Permalink
CDKのメジャーバージョンアップ (#14)
Browse files Browse the repository at this point in the history
* deps: vup cdk to v2

* feat: update context.json

* refactor: remove context

* deps: update outdated modules

* refactor: mark get context as deprecated

* a bit

* doc

* fix: review back
  • Loading branch information
horsewin authored Nov 29, 2022
1 parent 51c1a1e commit af97575
Show file tree
Hide file tree
Showing 25 changed files with 8,104 additions and 6,570 deletions.
72 changes: 37 additions & 35 deletions cdk-typescript/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

# AWS CDKサンプルコード

## Overview
Expand All @@ -14,10 +15,10 @@ CDKを実行するための事前設定を行います。
### ツールのバージョン

今回ハンズオン環境として利用するCloud9にはデフォルトでCDKがインストールされています。
2021年6月17日現在、Cloud9インスタンスを新しく起動してインストールされているバージョンは次のとおりです。
2022年11月1日現在、Cloud9インスタンスを新しく起動してインストールされているバージョンは次のとおりです。

- AWS CDK: 1.108.1
- Node.js: v10.24.1
- AWS CDK: 2.50.0 (build 4c11af6)
- Node.js: v16.16.0

本ハンズオンでは上記バージョンと筆者のローカル環境のバージョン(リポジトリ直下のREADME.mdのバージョン)で動作を確認しています。
しかし、Cloud9起動時に利用するAMIはAWS側で管理されています。
Expand All @@ -36,10 +37,6 @@ $ npm install
> [email protected] postinstall /home/ec2-user/environment/iac-story-code/cdk-typescript/node_modules/aws-cdk/node_modules/aws-sdk
> node scripts/check-node-version.js


> [email protected] postinstall /home/ec2-user/environment/iac-story-code/cdk-typescript
> npx patch-package

npx: installed 50 in 3.825s
```
Expand All @@ -53,19 +50,18 @@ $ pwd
/home/ec2-user/environment/iac-story-code/cdk-typescript

$ npm run setup
> cdk-typescript@0.1.0 setup /home/ec2-user/environment/iac-story-code/cdk-typescript
> cdk-typescript@1.1.0 setup
> cdk bootstrap

⏳ Bootstrapping environment aws://xxxxxxxx/ap-northeast-1...
Trusted accounts for deployment: (none)
Trusted accounts for lookup: (none)
Using default execution policy of 'arn:aws:iam::aws:policy/AdministratorAccess'. Pass '--cloudformation-execution-policies' to customize.
CDKToolkit: creating CloudFormation changeset...
[██████████████████████████████████████████████████████████] (3/3)



✅ Environment aws://xxxxxxxx/ap-northeast-1 bootstrapped.
```

コマンド実行後、S3に[cdktoolkit]と名のつくS3バケットが生成されたことを確認してください。
コマンド実行後、S3に[cdk-]と名のつくS3バケットが生成されたことを確認してください。


## CDKの実行
Expand Down Expand Up @@ -93,19 +89,26 @@ $ pwd

$ npm run deploy:dev:appb

> cdk-typescript@0.1.0 deploy:dev:appb /home/ec2-user/environment/iac-story-code/cdk-typescript
> cdk deploy cnis-app-base --context env=dev
> cdk-typescript@1.1.0 deploy:dev:appb
> cdk deploy cnis-app-base

✨ Synthesis time: 8.37s
cnis-app-base: building assets...
cnis-app-base: assets built
cnis-app-base: deploying...
cnis-app-base: creating CloudFormation changeset...
[██████████████████████████████████████████████████████████] (4/4)

✅ cnis-app-base
✨ Deployment time: 16.62s

Outputs:
Stack ARN:
arn:aws:cloudformation:ap-northeast-1:123456789012:stack/cnis-app-base/716d40e0-d03d-11eb-803a-0e15c04a62a9
arn:aws:cloudformation:ap-northeast-1:123456789012:stack/cnis-app-base/xxxxx-xxx-xxx

✨ Total time: 24.99s
```

ECRができていることを確認してください。
Expand All @@ -119,9 +122,10 @@ $ pwd
/home/ec2-user/environment/iac-story-code/cdk-typescript

$ npm run deploy:dev:base
> cdk-typescript@0.1.0 deploy:dev:base /home/ec2-user/environment/iac-story-code/cdk-typescript
> cdk deploy cnis-infra --context env=dev
> cdk-typescript@1.1.0 deploy:dev:base
> cdk deploy cnis-infra
:

cnis-infra
This deployment will make potentially sensitive changes according to your current security approval level (--require-approval broadening).
Please confirm you intend to make the following modifications:
Expand Down Expand Up @@ -173,17 +177,15 @@ Security Group Changes

Do you wish to deploy these changes (y/n)? y #"y"を入力してください
cnis-infra: deploying...
cnis-infra: creating CloudFormation changeset...

✅ cnis-infra
✨ Deployment time: 210.07s

Outputs:
cnis-infra.ExportsOutputFnGetAttcnissecurityGroupapp44B9640FGroupIdDD26EB74 = sg-0020ba4abccc3f8f2

Stack ARN:
arn:aws:cloudformation:ap-northeast-1:123456789012:stack/cnis-infra/c05da5b0-d03c-11eb-ab2a-0a03c4f678f1
arn:aws:cloudformation:ap-northeast-1:123456789012:stack/cnis-infra/xxxxx-xxx-xxx
✨ Total time: 218.49s
```

VPCやサブネット周りのリソースが作成できたことを確認してください。
Expand Down Expand Up @@ -236,22 +238,20 @@ $ pwd
/home/ec2-user/environment/iac-story-code/cdk-typescript

$ npm run deploy:dev:app
> cdk-typescript@0.1.0 deploy:dev:app /home/ec2-user/environment/iac-story-code/cdk-typescript
> cdk deploy cnis-app --context env=dev
> cdk-typescript@1.1.0 deploy:dev:app
> cdk deploy cnis-app

Including dependency stacks: cnis-infra, cnis-app-base
cnis-app-base
cnis-app-base: deploying...
✨ Synthesis time: 7.91s

cnis-app-base
cnis-app-base: building assets...
✅ cnis-app-base (no changes)

cnis-infra
cnis-infra: deploying...

✅ cnis-infra (no changes)

IAM Statement Changes
┌───┬─────────────────────────────┬────────┬────────────────┬─────────────────────────────────┬───────────┐
Expand All @@ -267,10 +267,12 @@ cnis-app: creating CloudFormation changeset...
[██████████████████████████████████████████████████████████] (10/10)

✅ cnis-app
✨ Deployment time: 214.73s

Stack ARN:
arn:aws:cloudformation:ap-northeast-1:xxxxxxxx:stack/cnis-app/27861db0-d03f-11eb-96a0-0e9105d7f1cd
arn:aws:cloudformation:ap-northeast-1:123456789012:stack/cnis-app/xxxxx-xxx-xxx

✨ Total time: 222.64s
```

スタック作成が完了したことを確認してください。
Expand Down Expand Up @@ -354,7 +356,7 @@ $ pwd

$ npm run destroy:all

> cdk-typescript@0.1.0 destroy:all /home/ec2-user/environment/iac-story-code/cdk-typescript
> cdk-typescript@1.1.0 destroy:all
> cdk destroy --all

Are you sure you want to delete: cnis-app, cnis-infra, cnis-app-base (y/n)? y #"y"を入力してください
Expand Down Expand Up @@ -387,4 +389,4 @@ cnis-app-base: destroying...
お疲れ様でした。

## 補記
- ニーズがあれば、ハンズオン資料を充実させたいと思うので、必要であればプルリク上げてください。
- ニーズがあれば、ハンズオン資料を充実させたいと思うので、必要であればプルリク上げてください。
10 changes: 5 additions & 5 deletions cdk-typescript/bin/cdk-typescript.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
#!/usr/bin/env node
import * as cdk from "@aws-cdk/core";
import * as cdk from "aws-cdk-lib";
import { CnisInfraStack } from "../lib/infrastructure-stack";
import { AppStack } from "../lib/app-stack";
import constants from "../constants";
import { env } from "../environment";
import { AppBaseStack } from "../lib/appbase-stack";

const app = new cdk.App();

try {
const infra = new CnisInfraStack(app, `${constants.ServicePrefix}-infra`);
const infra = new CnisInfraStack(app, `${env.global.servicePrefix}-infra`);

const { vpc, securityGroupList, ecsTaskExecutionRole, cluster } = infra;
const appbase = new AppBaseStack(app, `${constants.ServicePrefix}-app-base`);
const appbase = new AppBaseStack(app, `${env.global.servicePrefix}-app-base`);

new AppStack(app, `${constants.ServicePrefix}-app`, {
new AppStack(app, `${env.global.servicePrefix}-app`, {
vpc,
securityGroups: securityGroupList,
controlPlane: {
Expand Down
8 changes: 8 additions & 0 deletions cdk-typescript/cdk.context.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"acknowledged-issue-numbers": [
null,
null,
16603,
16603
]
}
24 changes: 1 addition & 23 deletions cdk-typescript/cdk.json
Original file line number Diff line number Diff line change
@@ -1,26 +1,4 @@
{
"app": "npx ts-node --prefer-ts-exts bin/cdk-typescript.ts",
"context": {
"@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": true,
"@aws-cdk/core:enableStackNameDuplicates": "true",
"aws-cdk:enableDiffNoFail": "true",
"@aws-cdk/core:stackRelativeExports": "true",
"@aws-cdk/aws-ecr-assets:dockerIgnoreSupport": true,
"@aws-cdk/aws-secretsmanager:parseOwnedSecretName": true,
"@aws-cdk/aws-kms:defaultKeyPolicies": true,
"@aws-cdk/aws-s3:grantWriteWithoutAcl": true,
"@aws-cdk/aws-ecs-patterns:removeDefaultDesiredCount": true,
"@aws-cdk/aws-rds:lowercaseDbIdentifier": true,
"@aws-cdk/aws-efs:defaultEncryptionAtRest": true,
"@aws-cdk/aws-lambda:recognizeVersionProps": true,
"dev": {
"serviceParameters": {
"desiredCount": 1,
"taskCpu": 256,
"taskMemory": 512,
"containerCpu": 256,
"containerMemory": 512
}
}
}
"context": {}
}
4 changes: 0 additions & 4 deletions cdk-typescript/constants.ts

This file was deleted.

57 changes: 57 additions & 0 deletions cdk-typescript/environment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const ENV_NAMES = ["dev", "stg", "prd"] as const;
type EnvType = typeof ENV_NAMES[number];

type EnvParamType = {
global: {
servicePrefix: string;
projectName: string;
};
cluster: {
desiredCount: 1 | 2 | 4;
taskCpu: number;
taskMemory: number;
containerCpu: number;
containerMemory: number;
};
};

const commonParam: EnvParamType = {
global: {
servicePrefix: "cnis",
projectName: "CloudNativeIaCStory",
},
cluster: {
desiredCount: 1,
taskCpu: 256,
taskMemory: 512,
containerCpu: 256,
containerMemory: 512,
},
};

const envName: EnvType = (process.env.DEPLOY_ENV as EnvType) || "dev";
if (!ENV_NAMES.includes(envName)) {
throw Error(`Invalid env name specified ${envName}`);
}

const envParamMap: Record<EnvType, EnvParamType> = {
dev: {
...commonParam,
},
stg: {
...commonParam,
cluster: {
...commonParam.cluster,
desiredCount: 2,
},
},
prd: {
...commonParam,
cluster: {
...commonParam.cluster,
desiredCount: 2,
},
},
};

export const env = envParamMap[envName];
29 changes: 14 additions & 15 deletions cdk-typescript/lib/app-stack.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import * as cdk from "@aws-cdk/core";
import { Stack, StackProps, Tags } from "@aws-cdk/core";
import constants from "../constants";
import { StringParameter } from "@aws-cdk/aws-ssm";
import { ISecurityGroup, IVpc } from "@aws-cdk/aws-ec2";
import * as cdk from "aws-cdk-lib";
import { Stack, StackProps, Tags } from "aws-cdk-lib";
import { SecurityGroupNameType } from "../model";
import { EcsService as CnisEcsService } from "./modules/services/ecs-service";
import { getEnvContext } from "./helper";
import { FargateTaskDefinition, ICluster } from "@aws-cdk/aws-ecs";
import { ContainerDefinition } from "./modules/services/container-definition";
import { IRole } from "@aws-cdk/aws-iam";
import { IRepository } from "@aws-cdk/aws-ecr/lib/repository";
import { ILogGroup } from "@aws-cdk/aws-logs";
import { AppLoadBalancer as CnisAlb } from "./modules/loadbalancer/alb";
import { parameterKeys } from "../params";
import { ISecurityGroup, IVpc } from "aws-cdk-lib/aws-ec2";
import { FargateTaskDefinition, ICluster } from "aws-cdk-lib/aws-ecs";
import { IRole } from "aws-cdk-lib/aws-iam";
import { IRepository } from "aws-cdk-lib/aws-ecr";
import { ILogGroup } from "aws-cdk-lib/aws-logs";
import { StringParameter } from "aws-cdk-lib/aws-ssm";
import { env } from "../environment";

interface IAppStackProps extends StackProps {
vpc: IVpc;
Expand All @@ -32,15 +31,15 @@ export class AppStack extends Stack {
const { vpc, securityGroups, controlPlane } = props;
const { executionRole, cluster, repository, logGroup } = controlPlane;

Tags.of(this).add("Project", constants.ProjectName);
const { taskCpu, taskMemory } = getEnvContext(this).serviceParameters;
Tags.of(this).add("Project", env.global.projectName);
const { taskCpu, taskMemory } = env.cluster;

// ALB
const securityGroup = securityGroups.get(SecurityGroupNameType.ingress);
if (!securityGroup) {
throw new Error("No alb security group is set");
}
const albInfo = new CnisAlb(this, `${constants.ServicePrefix}-alb`, {
const albInfo = new CnisAlb(this, `${env.global.servicePrefix}-alb`, {
vpc,
securityGroup,
});
Expand All @@ -51,7 +50,7 @@ export class AppStack extends Stack {
cpu: taskCpu,
executionRole,

family: `${constants.ServicePrefix}-ecs-taskdef-app`,
family: `${env.global.servicePrefix}-ecs-taskdef-app`,
});

// コンテナ定義の作成
Expand All @@ -74,7 +73,7 @@ export class AppStack extends Stack {
if (!appSecurityGroup) {
throw new Error("No application security group for cluster found");
}
new CnisEcsService(this, `${constants.ServicePrefix}-ecs-service`, {
new CnisEcsService(this, `${env.global.servicePrefix}-ecs-service`, {
cluster,
serviceSecurityGroup: appSecurityGroup,
taskDefinition,
Expand Down
Loading

0 comments on commit af97575

Please sign in to comment.