GA になった AWS CDK Blocks を試してみた

GA になった AWS CDK Blocks を試してみた

GA になった AWS CDK Blocks で、KVStore と AsyncJob を使うアプリを作り、ローカル実行から AWS へのデプロイ・撤去まで試しました。同じコードのままローカルでも AWS 上でも動かせ、sandbox のスタックは1コマンドで撤去できました。
2026.11.25

はじめに

2026年11月20日に、AWS CDK Blocks(Preview 時の名称は AWS Blocks)が GA になりました。

https://aws.amazon.com/jp/about-aws/whats-new/2026/11/aws-cdk-blocks-ga/

CDK Blocks の Block は、CDK construct に、アプリから使うための接続コードとローカル実装を加えた npm パッケージです。

この記事では、KVStore と AsyncJob を使うアプリを作り、AWS へのデプロイと撤去までを試しました。

検証環境

  • 実行環境: Docker(node:22、Linux)
  • Node.js: v22.23.3
  • npm: 10.9.9
  • aws-cdk-blocks: 1.0.1
  • @aws-cdk-blocks/core: 1.0.1
  • @aws-cdk-blocks/bb-kv-store: 1.0.0
  • @aws-cdk-blocks/bb-async-job: 1.0.0
  • @aws-cdk-blocks/create-blocks-app: 1.0.1(テンプレート default 0.1.0)
  • @aws-cdk-blocks/create-block: 1.0.0
  • aws-cdk-lib: 2.278.0
  • aws-cdk(CLI): 2.1149.0
  • リージョン: 東京(ap-northeast-1)

ローカル実行

Block を定義したアプリを、ローカルの dev サーバーで動かしました。

アプリの作成

npm create @aws-cdk-blocks/blocks-app@latest my-app
cd my-app
npm run dev

npm create の実行時には、使用状況データの収集についての説明が出力され、オプトアウトの方法として cdk cli-telemetry --disable の実行と環境変数 CDK_DISABLE_CLI_TELEMETRY=1 の設定が案内されました。

dev サーバーが起動すると、次のように表示されました。

AWS CDK Blocks local server running on http://localhost:3000

使いたい Block の API は、アプリのディレクトリで調べられます。npm run docs で Block の一覧を表示でき、npm run docs AsyncJob のように Block 名を付けると個別のガイドを読めます。

バックエンドの定義

cdk-blocks/index.ts に、KVStore、AsyncJob、ApiNamespace を定義しました。この記事ではフロントエンド(src/)を使わず、ApiNamespace の関数を scripts/local-check.ts から呼びます。

import { ApiNamespace, Scope, KVStore, AsyncJob } from 'aws-cdk-blocks';
import { z } from 'zod';

const scope = new Scope('my-app');

// KVStore: ローカルではファイル、AWS では DynamoDB テーブル
const notes = new KVStore(scope, 'notes', {
  schema: z.object({ id: z.string(), text: z.string() }),
  key: { partitionKey: 'id' },
});

type Payload = { mode: 'ok' | 'fail-twice' | 'always-fail'; noteId: string };

// AsyncJob: ローカルではプロセス内キュー、AWS では SQS + DLQ + Lambda
const worker = new AsyncJob<Payload>(scope, 'worker', {
  maxRetries: 3,
  trackStatus: true,
  handler: async (payload, ctx) => {
    console.log(`[worker] job=${ctx.jobId} mode=${payload.mode} receiveCount=${ctx.receiveCount}`);
    if (payload.mode === 'always-fail') {
      throw new Error(`always-fail (receiveCount=${ctx.receiveCount})`);
    }
    if (payload.mode === 'fail-twice' && ctx.receiveCount < 3) {
      throw new Error(`fail-twice (receiveCount=${ctx.receiveCount})`);
    }
    await notes.put({ id: payload.noteId }, { id: payload.noteId, text: `processed by job ${ctx.jobId} on attempt ${ctx.receiveCount}` });
  },
});

export const api = new ApiNamespace(scope, 'api', () => ({
  async putNote(id: string, text: string) {
    await notes.put({ id }, { id, text });
    return { ok: true };
  },
  async getNote(id: string) {
    return await notes.get({ id });
  },
  async submitJob(mode: Payload['mode'], noteId: string) {
    return await worker.submit({ mode, noteId });
  },
  async jobStatus(jobId: string) {
    return await worker.getStatus(jobId);
  },
}));

呼び出しスクリプトは、dev サーバーを起動したまま別のターミナルで、シナリオ名(kv、ok、fail-twice、always-fail、greeting)を指定して実行しました。greeting は、後述の「カスタム Block」の節で api にメソッドを追加してから実行しました。

BLOCKS_API_URL=http://localhost:3000/cdk-blocks/api npx tsx scripts/local-check.ts <シナリオ名>
scripts/local-check.ts の全文
// ローカルの dev サーバーに対して、KVStore と AsyncJob を呼び出す
// 実行: BLOCKS_API_URL=http://localhost:3000/cdk-blocks/api npx tsx scripts/local-check.ts <scenario>
import { setTimeout as sleep } from 'node:timers/promises';
import { api } from 'cdk-blocks';

const scenario = process.argv[2] ?? 'kv';

async function waitDone(jobId: string) {
  for (let i = 0; i < 40; i++) {
    const s = await api.jobStatus(jobId);
    if (s && (s.state === 'complete' || s.state === 'failed')) return s;
    await sleep(250);
  }
  return await api.jobStatus(jobId);
}

if (scenario === 'kv') {
  console.log('putNote:', JSON.stringify(await api.putNote('n1', 'hello from local')));
  console.log('getNote n1:', JSON.stringify(await api.getNote('n1')));
  console.log('getNote missing:', JSON.stringify(await api.getNote('missing')));
} else if (scenario === 'greeting') {
  console.log('setGreeting:', JSON.stringify(await api.setGreeting('alice', 'Hello Alice')));
  console.log('getGreeting alice:', JSON.stringify(await api.getGreeting('alice')));
  try {
    await api.setGreeting('bob', 'x'.repeat(101));
    console.log('over-length: accepted (unexpected)');
  } catch (e) {
    console.log('over-length rejected:', (e as Error).name, '-', (e as Error).message);
  }
} else {
  const mode = scenario as 'ok' | 'fail-twice' | 'always-fail';
  const noteId = `job-${mode}`;
  const { jobId } = await api.submitJob(mode, noteId);
  console.log('submitted:', jobId, 'mode=', mode);
  const s = await waitDone(jobId);
  console.log('status.state:', s?.state, 'attempts:', s?.attempts, 'error:', s?.error);
  console.log('transitions:', s?.transitions.map((t) => `${t.state}#${t.attempt}`).join(' -> '));
  console.log('note after job:', JSON.stringify(await api.getNote(noteId)));
}

KVStore の読み書き

kv シナリオの結果です。

putNote: {"ok":true}
getNote n1: {"id":"n1","text":"hello from local"}
getNote missing: null

ローカルの KVStore のデータは、.cdk-blocks/local/data/my-app-notes/store.json に保存されました。

{
  "version": 2,
  "items": [
    {
      "id": "n1",
      "text": "hello from local"
    }
  ]
}

AsyncJob のリトライと DLQ

ローカルでの実行結果

submitJob で、成功(ok)、2回失敗してから成功(fail-twice)、常に失敗(always-fail)の3モードのジョブを投入しました。

maxRetries は、リトライ回数ではなく、最初の配信を含む総配信回数です。今回の 3 は、最初の1回とリトライ2回にあたります。

モード 最終状態 attempts transitions
ok complete 1 queued#0 -> processing#1 -> complete#1
fail-twice complete 3 queued#0 -> processing#1 -> processing#2 -> processing#3 -> complete#3
always-fail failed 3 queued#0 -> processing#1 -> processing#2 -> processing#3 -> failed#3

always-fail の status には、最後のハンドラーエラーが error: always-fail (receiveCount=3) として記録されました。

dev サーバーのログには、3回失敗した always-fail のジョブについて moved to DLQ と表示され、payload も出力されました。

[AsyncJob:worker] submitted job a4463d7b-5b21
[worker] job=a4463d7b-5b21 mode=always-fail receiveCount=1
[AsyncJob:worker] job a4463d7b-5b21 failed (attempt 1/3): always-fail (receiveCount=1)
[AsyncJob:worker] retrying job a4463d7b-5b21 (attempt 2/3)
[worker] job=a4463d7b-5b21 mode=always-fail receiveCount=2
[AsyncJob:worker] job a4463d7b-5b21 failed (attempt 2/3): always-fail (receiveCount=2)
[AsyncJob:worker] retrying job a4463d7b-5b21 (attempt 3/3)
[worker] job=a4463d7b-5b21 mode=always-fail receiveCount=3
[AsyncJob:worker] job a4463d7b-5b21 moved to DLQ after 3 attempts
[AsyncJob:worker] DLQ payload: {"mode":"always-fail","noteId":"job-always-fail"}

cdk synth の出力

同じ AsyncJob の定義が cdk synth でどのリソースになるかを確認しました。

npx cdk synth -c sandboxMode=true --quiet

テンプレートは cdk.out/<スタック名>.template.json に出力されました。次の表は、AsyncJob から生成された SQS キュー、DLQ、event source mapping、ステータス用テーブルの主な設定値です。

リソース 設定 値
メインキュー VisibilityTimeout 905
メインキュー RedrivePolicy の maxReceiveCount 3
メインキュー SqsManagedSseEnabled true
DLQ MessageRetentionPeriod 1209600(14日)
event source mapping BatchSize 10
event source mapping MaximumBatchingWindowInSeconds 5
event source mapping FunctionResponseTypes ReportBatchItemFailures
worker-status テーブル(trackStatus: true のとき) BillingMode PAY_PER_REQUEST

カスタム Block

組織の要件を組み込んだ Block を create-block で作り、アプリから使いました。ここで作った GreetingStore には、次の要件を入れました。

  • KVStore を内包する
  • テーブルの PITR(ポイントインタイムリカバリ)を有効に固定する
  • メッセージ長を既定で 1〜100文字に制限する

雛形の生成

create-block の README には、次のコマンドが載っています。

npm create @aws-cdk-blocks/block@latest <ClassName>

検証した環境(Docker の node:22、npm 10.9.9)では、npm create @aws-cdk-blocks/block@latest -- GreetingStore --dry-run を実行しても何も出力されませんでした。パッケージの dist/index.js を node で直接実行するとヘルプが表示されたため、@aws-cdk-blocks/create-block を別のディレクトリへ npm install し、アプリのルートから dist/index.js を直接実行しました。

# アプリとは別のディレクトリで実行する
npm install @aws-cdk-blocks/create-block
# アプリのルートで実行する
node <導入先ディレクトリ>/node_modules/@aws-cdk-blocks/create-block/dist/index.js GreetingStore --yes

アプリが npm workspaces を使っているため、create-block は customer モードで動作しました。packages/bb-greeting-store に15ファイルが生成され、ルートの package.json の workspaces にこのパッケージが追記されました。生成直後のビルドとテスト(3件)も通りました。

生成されたファイルのうち、次の4つは実行される場面ごとの入口です。

ファイル 使われる場面
index.mock.ts ローカル開発とテスト
index.aws.ts デプロイ後の Lambda 実行時
index.cdk.ts cdk synth の実行時
index.browser.ts ブラウザーで読み込まれるとき(スタブ)

要件の実装

PITR の固定は、synth で使われる index.cdk.ts に書きました。

packages/bb-greeting-store/src/index.cdk.ts

export class GreetingStore extends Scope {
	constructor(scope: ScopeParent, id: string, _options?: GreetingStoreOptions) {
		super(id, { parent: scope, bbName: BB_NAME });
		new KVStore(this, 'store', { pointInTimeRecovery: true });
	}
	// ...
}

メッセージ長のチェックは、ローカルで使われる index.mock.ts に書きました。

packages/bb-greeting-store/src/index.mock.ts

export class GreetingStore extends Scope {
	private readonly store: KVStore;
	private readonly maxLength: number;

	constructor(scope: ScopeParent, id: string, options?: GreetingStoreOptions) {
		super(id, { parent: scope, bbName: BB_NAME, bbVersion: BB_VERSION });
		registerSdkIdentifiers(this.fullId, {});
		this.maxLength = options?.maxLength ?? 100;
		this.store = new KVStore(this, 'store', { pointInTimeRecovery: true });
	}

	/** Save a greeting for `name`. Throws `InvalidInputException` when it is empty or too long. */
	async setGreeting(name: string, message: string): Promise<void> {
		if (message.length === 0 || message.length > this.maxLength) {
			throw blocksError(GreetingStoreErrors.InvalidInput, `message must be 1-${this.maxLength} characters`);
		}
		await this.store.put(name, message);
	}

	/** Read the greeting for `name`. Returns `null` when none is saved. */
	async getGreeting(name: string): Promise<string | null> {
		return await this.store.get(name);
	}
}

デプロイ後の Lambda では index.aws.ts が使われるため、同じチェックをこちらにも書きました。コンストラクターと setGreeting は、index.mock.ts と同じ内容にしました。

GreetingStoreErrors.InvalidInput と maxLength オプションは、それぞれ errors.ts と types.ts で定義しました。

errors.ts と types.ts

packages/bb-greeting-store/src/errors.ts

/**
 * Typed error constants for GreetingStore. Match them in catch blocks with
 * `isBlocksError(e, GreetingStoreErrors.Foo)` from `@aws-cdk-blocks/core` — errors
 * cross the wire by `name`, so the same guard works server- and client-side.
 */
export const GreetingStoreErrors = {
	/** The greeting is empty or longer than `maxLength`. */
	InvalidInput: 'InvalidInputException',
} as const;

packages/bb-greeting-store/src/types.ts

/**
 * Shared types for GreetingStore. Imported by the mock, aws, cdk, and browser
 * entry points. Types only — this file has zero runtime dependencies.
 */

/** Options for constructing a {@link GreetingStore}. */
export interface GreetingStoreOptions {
	/** Maximum greeting length. 組織のルールとして既定を 100 文字にする。 */
	maxLength?: number;
}

アプリからの利用

Block の package.json の exports は ./dist/*.js を指すため、src/ を変更したあとに Block をビルドしました。

cd packages/bb-greeting-store && npm run build

cdk-blocks/index.ts では、GreetingStore を import してインスタンスを作成し、api に2つのメソッドを追加しました。

import { GreetingStore } from '@app/bb-greeting-store';

// ...

// カスタム Block(packages/bb-greeting-store)
const greetings = new GreetingStore(scope, 'greetings');

// ...

export const api = new ApiNamespace(scope, 'api', () => ({
  // ...
  async setGreeting(name: string, message: string) {
    await greetings.setGreeting(name, message);
    return { ok: true };
  },
  async getGreeting(name: string) {
    return await greetings.getGreeting(name);
  },
  // ...
}));

greeting シナリオの結果です。

setGreeting: {"ok":true}
getGreeting alice: "Hello Alice"
over-length rejected: InvalidInputException - InvalidInputException: message must be 1-100 characters

synth したテンプレートで PointInTimeRecoveryEnabled が true になっていたのは greetings-store テーブルだけでした。

AWS 上での検証

デプロイ

デプロイ先のアカウントとリージョンで、bootstrap を済ませておきます。bootstrap は、アカウントとリージョンの組み合わせごとに1回だけ必要です。

デプロイは、次のコマンドで実行しました。

npm run sandbox:deploy

出力は次のとおりでした(API ID は伏せています)。

   CloudFormation: applying changes
   68 resources applied in 3m 21s

✅ Sandbox deployed!
📡 API URL: https://<api-id>.execute-api.ap-northeast-1.amazonaws.com/prod/cdk-blocks/api

動作確認

ローカルと同じスクリプトを、環境変数 BLOCKS_API_URL に AWS の API URL を指定して実行しました。

BLOCKS_API_URL=https://<api-id>.execute-api.ap-northeast-1.amazonaws.com/prod/cdk-blocks/api npx tsx scripts/local-check.ts ok
submitted: de2ca1d1-8f0c-4f6c-8aef-73bd95621d82 mode= ok
status.state: complete attempts: 1 error: undefined
transitions: queued#0 -> processing#1 -> complete#1
note after job: {"id":"job-ok","text":"processed by job de2ca1d1-8f0c-4f6c-8aef-73bd95621d82 on attempt 1"}

kv と greeting のシナリオも、ローカルと同じ結果でした。

デプロイ後の SQS と DynamoDB の設定は、AWS CLI の読み取り系コマンドで確認しました。キューの URL には、メインキューと DLQ のものをそれぞれ指定しました。

aws sqs get-queue-attributes --queue-url <キューの URL> --attribute-names RedrivePolicy VisibilityTimeout MessageRetentionPeriod
aws dynamodb describe-continuous-backups --table-name <テーブル名>

メインキューは VisibilityTimeout が 905、RedrivePolicy の maxReceiveCount が 3 でした。DLQ の MessageRetentionPeriod は 1209600 でした。PITR が ENABLED だったのは greetings-store テーブルだけで、notes と worker-status は DISABLED でした。いずれも synth の値と一致しました。

撤去

npm run sandbox:destroy
   CloudFormation: removing changes
   68 resources removed in 2m 47s

✅ Sandbox destroyed!

撤去後、スタックは DELETE_COMPLETE になりましたが、CDK のヘルパー Lambda 関数2つ分のロググループが残りました。残ったロググループはスタックの管理外のため、手動で削除します。

  • /aws/lambda/<スタック名>-CustomCDKBucketDeploymen-<suffix>
  • /aws/lambda/<スタック名>-CustomS3AutoDeleteObject-<suffix>

sandbox のスタックは、1コマンドで撤去できました。

本番用の npm run deploy で使われるプリセットでは、テーブルやバケットの削除ポリシーが RETAIN になります。

https://docs.aws.amazon.com/cdk/blocks/devguide/deploy-to-aws.html

まとめ

2026年6月に Public Preview として提供された AWS Blocks が、AWS CDK Blocks として GA になりました。

https://dev.classmethod.jp/articles/20260620-aws-blocks-preview/

KVStore と AsyncJob を使うアプリを、同じコードのままローカルでも AWS 上でも動かせました。CDK Blocks には、DLQ を使ったリトライ実装など、AWS サービス固有のベストプラクティスが組み込まれており、バックエンドのプロトタイプから利用できます。アプリケーションの迅速な開発サイクルを支える仕組みとして、お試しください。

この記事をシェアする

AWSのお困り事はクラスメソッドへ

関連記事