Closed5

aws cdk v2に入門してみる

cdk v2がRC17まで来ているので移行を踏まえいろいろと試してみる。
v2からは都度サービスごとのパッケージをインストールする必要がないところが一番のメリットだと思う。(v1だと各パッケージのバージョン違いで謎のエラーが出るので)

https://github.com/aws/aws-cdk

https://docs.aws.amazon.com/cdk/latest/guide/work-with-cdk-v2.html

https://aws.amazon.com/jp/blogs/news/announcing-aws-cloud-development-kit-v2-developer-preview/

セットアップスクリプトはまだないので、スクラッチでの環境構築。

$ mkdir aws-cdk-v2-sample && cd aws-cdk-v2-sample
$ npm init -y
- $ npm i -D aws-cdk aws-cdk-lib constructs ts-node typescript
+ $ npm i -D aws-cdk@2.0.0-rc.17 aws-cdk-lib constructs ts-node typescript
/cdk.json
{
  "app": "npx ts-node infrastructure/bootstrap.ts",
}
/infrastructure/bootstrap.ts
import { SampleStack } from './sampleStack'
import { App } from 'aws-cdk-lib'

const app = new App()
new SampleStack(app, 'Sample-app', {
  stackName: 'SampleApp'
})
/infrastructure/sampleStack.ts
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';

export class SampleStack extends Stack {
    constructor(scope: Construct, id: string, props: StackProps) {
        super(scope, id, props)
    }
} 
/tsconfig.json
{
  "compilerOptions": {
    "target": "ES2018",
    "module": "commonjs",
    "lib": [
      "es2018"
    ],
    "declaration": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": false,
    "inlineSourceMap": true,
    "inlineSources": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules",
    "cdk.out"
  ]
}
.gitignore
.gitignore
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# aws cdk
node_modules

# CDK asset staging directory
.cdk.staging
cdk.out

最低限のファイルを設置したのち、$ cdk stynthでエラーが出ないか確認。

$ cdk synth

deployするときにエラー。
cdk cliもバージョンアップの必要あり。
現時点での最新版rc.17にアップデートする。

$ npm i -g aws-cdk@2.0.0-rc.17
package.json
  "devDependencies": {
    "@types/aws-lambda": "^8.10.82",
    "@types/node": "^16.6.0",
    "aws-cdk": "^2.0.0-rc.17",
    "aws-cdk-lib": "^2.0.0-rc.17",
    "constructs": "^10.0.5",
    "esbuild": "^0.12.19",
    "ts-node": "^10.2.0",
    "typescript": "^4.3.5"
  }

bootstrapもv1とは異なるため再度作り直す必要あり。

$ cdk bootstrap
$ cdk deploy

Fargateの環境をつくる

v1と一部メソッド名は違うものの補完を使えばほぼそのまま。
コンテナイメージはawsのサンプルを一旦利用してみる。

/infrastructure/bootstrap.ts
import { FargateStack } from './fargateStack';
import { App } from 'aws-cdk-lib';

const app = new App();
new FargateStack(app, 'fargateApp', {
  stackName: 'FargateApp',
});
/infrastructure/fargateStack.ts
import { aws_ec2, aws_ecs, aws_ecs_patterns, Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';

export class FargateStack extends Stack {
  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);

    const vpc = new aws_ec2.Vpc(this, 'FargateVpc');

    const cluster = new aws_ecs.Cluster(this, 'FargateCluster', {
      vpc,
    });

    const loadBalancedFargateService = new aws_ecs_patterns.ApplicationLoadBalancedFargateService(
      this,
      'FargateService',
      {
        cluster,
        memoryLimitMiB: 1024,
        cpu: 512,
        taskImageOptions: {
          image: aws_ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
        },
      },
    );

    loadBalancedFargateService.targetGroup.configureHealthCheck({
      path: '/custom-health-path',
    });
  }
}
$ cdk synth

でエラーが出ないことを確認して、

$ cdk deploy

このスクラップは2021/11/16にクローズされました
ログインするとコメントできます