ENGINEER BLOG ENGINEER BLOG
  • 公開日
  • 最終更新日

【CDK】Typescriptを使ったCDKプロジェクトを1から構築する

この記事を共有する

はじめに

パーソル&サーバーワークスの嶋田です。

皆さんはCDKプロジェクトをカスタマイズしたいと思ったことはありませんか?

導入するパッケージの選定や、プロジェクトのフォルダ構成をオリジナルで構築したい

本記事では、cdk init app --language typescriptのような、
テンプレートにそってCDKプロジェクトのセットアップを行うのではなく、
1からセットアップすることを目的としています。

開発プロジェクトのルートディレクトリを作成

$ mkdir cdk-scratch
$ cd cdk-scratch/

※cdk-scratchは任意の名前に変更してください

プロジェクトのセットアップ

$ npm init -y
Wrote to /home/ec2-user/cdk-scratch/package.json:
{
  "name": "cdk-scratch",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

必要なパッケージをインストール

$ npm install -D aws-cdk aws-cdk-lib constructs typescript ts-node @types/node
added 27 packages, and audited 64 packages in 12s
3 packages are looking for funding
  run `npm fund` for details
found 0 vulnerabilities

今回は cdk init app --language typescript を実行したときのディレクトリ構造を真似します。
※1からセットアップを行う例として bin / lib ディレクトリを作成しますが、
 ディレクトリ名は自由に変更可能です

$ mkdir bin lib
$ touch bin/cdk-scratch.ts lib/VPCStack.ts
$ tree -I 'node_modules'
.
├── bin
│   └── cdk-scratch.ts
├── lib
│   └── VPCStack.ts
├── package-lock.json
└── package.json
2 directories, 4 files

Typescriptのセットアップ

$ tsc --init
Created a new tsconfig.json with:
  target: es2016
  module: commonjs
  strict: true
  esModuleInterop: true
  skipLibCheck: true
  forceConsistentCasingInFileNames: true
You can learn more at https://aka.ms/tsconfig

es2016だと cdk synth / cdk deploy がエラーになり動作しないため、tsconfig.jsonファイルを編集します。

$ sed -i 's/"target": "es2016"/"target": "ES2020"/' tsconfig.json

cdk.jsonファイルを作成

※cdk-scratch.tsファイルの名前は、先ほどbin直下に作成したファイル名と合わせます。

$ cat < cdk.json
> {
>   "app": "npx ts-node bin/cdk-scratch.ts"
> }
> EOF

動作確認用CDKコード記述

bin/cdk-scratch.ts を以下のように書き換えます。

import 'source-map-support'
import { App } from 'aws-cdk-lib'
import { VPCStack } from '../lib/VPCStack'
// CDK
const app = new App()
const vpcStack = new VPCStack(app, 'VPC')

lib/VPCStack.ts を以下のように書き換えます。

import { Construct } from 'constructs'
import { Stack, StackProps } from 'aws-cdk-lib'
import { CfnSubnet, CfnVPC, CfnInternetGateway, CfnRouteTable, CfnSubnetRouteTableAssociation, CfnRoute, CfnVPCGatewayAttachment, CfnSubnetCidrBlock } from 'aws-cdk-lib/aws-ec2';
export class VPCStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    const cfnVpc = new CfnVPC(this, 'CfnVPC', {
      cidrBlock: '10.100.0.0/16'
    })
    const cfnSubnet1 = new CfnSubnet(this, 'CfnSubnet1', {
      vpcId: cfnVpc.ref,
      cidrBlock: '10.100.100.0/24'
    })
    const cfnSubnet2 = new CfnSubnet(this, 'CfnSubnet2', {
      vpcId: cfnVpc.ref,
      cidrBlock: '10.100.200.0/24'
    })
    const routeTable = new CfnRouteTable(this, 'CfnRouteTable', {
      vpcId: cfnVpc.ref
    })
    new CfnSubnetRouteTableAssociation(this, 'CfnSubnetRouteTableAssociation', {
      routeTableId: routeTable.ref,
      subnetId: cfnSubnet1.ref
    })
    const igw = new CfnInternetGateway(this, 'CfnInternetGateway')
    const gatewayAttachment = new CfnVPCGatewayAttachment(this, 'CfnVPCGatewayAttachment', {
      vpcId: cfnVpc.ref,
      internetGatewayId: igw.ref
    })
    new CfnRoute(this, 'CfnRoute', {
      destinationCidrBlock: '0.0.0.0/0',
      routeTableId: routeTable.ref,
      gatewayId: igw.ref
    }).addDependency(gatewayAttachment)
  }
}

cdk deployを実行

$ cdk deploy --require-approval never
✨  Synthesis time: 18.47s
VPC: deploying... [1/1]
VPC: creating CloudFormation changeset...
 ✅  VPC
✨  Deployment time: 42.06s
Stack ARN:
arn:aws:cloudformation:ap-northeast-1:012345678910:stack/VPC/cc2ee6f0-c35f-11ef-b55a-0ab9e60f1e4d
✨  Total time: 60.52s

最後に後片付け

1からプロジェクトを作成し、cdk deploy まで完了したので、不要なリソースを削除しましょう。
cdk destroy を実行して、当該プロジェクトフォルダを削除すれば後片付けはおしまいです。

お疲れさまでした。

この記事は私が書きました

嶋田 龍登

記事一覧

インフラからアプリのことまでなんでもやりたい、フルスタックを目指すエンジニア

嶋田 龍登

この記事を共有する

クラウドのご相談

CONTACT

クラウド導入や運用でお悩みの方は、お気軽にご相談ください。
専門家がサポートします。

サービス資料ダウンロード

DOWNLOAD

ビジネスをクラウドで加速させる準備はできていますか?
今すぐサービス資料をダウンロードして、詳細をご確認ください。