ソースコードから理解する技術-UnderSourceCode

手を動かす(プログラムを組む)ことで技術を理解するブログ

aws-cdkを触ってみた

少し(かなり?)遅れた感はありますが、aws-cdkを触ってみました。

https://docs.aws.amazon.com/ja_jp/cdk/latest/guide/getting_started.html#hello_world_tutorial
こちらの公式の「Hello World Tutorial」をほぼなぞっただけですが、いくつか独自にアレンジしたところもあるので、メモ書き程度に残しておきます。

aws-cdkのインストールはローカルにインストールからnpxを使ったインストールに変更しました

変更したところ

  • (TypeScriptでやったのだが) aws-cdkのモジュールはnpxにインストールした
  • Package.jsonの「scripts」にコマンドを用意してaws-cdkを各操作を出来るようにした
  • プログラムで構築できることを検証するため、動的にS3のバケット名を生成してみた

以下、変更したところの詳細です。

aws-cdkを使ってのプロジェクト作成

Hello World Tutorial」ではaws-cdkをグローバル領域にインストールしていますが、バージョンアップなどされることも考慮して、今回はnpxでプロジェクトを作成することにしました。
プロジェクト名は「hello-cdk-npx」とし、プロジェクト名と同名のフォルダを作成して以下のように実行します。

$ mkdir hello-cdk-npx
$ cd hello-cdk-npx
$ npx cdk init app --language=typescript
$ npx cdk --version

package.json

良く使うコマンドは全てpackage.jsonの「Scripts」に纏めました。
こうすれば「$ npm run deploy」のように「$ npm run ~」で統一して実行できます。以下、今回作成したpackage.jsonの「scripts」です。

  "scripts": {
    "build": "tsc",
    "watch": "tsc -w",
    "test": "jest",
    "cdk": "cdk",
    "synth": "npx cdk synth",
    "diff": "npx cdk diff",
    "deploy": "npx cdk deploy",
    "destroy": "npx cdk destroy"
  },

動的にS3のバケット名を生成

TypeScriptのプログラムで、日付を動的に取得してバケット名として指定してみました。
lib/hello-cdk-npx-stack.ts は以下のようになりました。

import core = require('@aws-cdk/core');
import s3 = require('@aws-cdk/aws-s3');

export class HelloCdkNpxStack extends core.Stack {
  constructor(scope: core.Construct, id: string, props?: core.StackProps) {
    super(scope, id, props);

    // The code that defines your stack goes here
    const now = new Date();
    const yyyymmdd = now.getFullYear().toString() + (now.getMonth()+1).toString() + now.getDate().toString();
    const myBucketName = "hello-cdk-" + yyyymmdd;

    new s3.Bucket(this, 'MyFirstBucket', {
      versioned: true,
      bucketName: myBucketName
    });
  }
}

バケット名を指定している以外は、以下の「Hello World Tutorial」から変わっていないです。
https://docs.aws.amazon.com/ja_jp/cdk/latest/guide/getting_started.html#hello_world_tutorial

実行

ここまで作成すれば、Makefileを使用して以下のコマンドでビルド、デプロイ、破棄を行うことができます。

$ npm run build
$ npm run synth
$ npm run deploy
$ npm run destroy

以上です。