Open29

CDK で Docker 上の LocalStack にさまざまな AWS リソース群(とりあえず S3, Lambda, API Gateway)を作成する

amay077amay077
#!/bin/bash
awslocal s3 mb s3://test-bucket
cd /home/localstack/data/
awslocal s3 cp sample.txt s3://test-bucket/
awslocal s3 ls s3://test-bucket

でバケットが作成されてないっぽいので、直接コンテナ内でコマンド叩いてみる。

docker exec -it localstack bash

コンテナ内でコマンド実行したらOK。

amay077amay077

改めてホスト側から確認。

  • sample.txtdata/ に、init.dscripts/ に置かなきゃだった(汗
  • また、init.d に権限付けておく chmod 777 init.d

改めて

docker compose down
docker compose up

で、正しくホストから

curl http://localhost:4566/test-bucket/sample.txt

が通るようになった。

amay077amay077
cdk init --language typescript
mkdir hello-cdk
cd hello-cdk
npm install @aws-cdk/aws-apigateway @aws-cdk/aws-lambda @aws-cdk/aws-dynamodb

まで一気に。dynamodb は目的外だけど一応。

amay077amay077
cdk bootstrap

失敗。

hello-cdk % cdk bootstrap
 ⏳  Bootstrapping environment aws://762063040921/ap-northeast-1...
 ❌  Environment aws://762063040921/ap-northeast-1 failed bootstrapping: InvalidClientTokenId: The security token included in the request is invalid.
    at Request.extractError (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-sdk/lib/protocol/query.js:50:29)
    at Request.callListeners (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
    at Request.emit (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
    at Request.emit (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-sdk/lib/request.js:686:14)
    at Request.transition (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-sdk/lib/request.js:22:10)
    at AcceptorStateMachine.runTo (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-sdk/lib/state_machine.js:14:12)
    at /Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-sdk/lib/state_machine.js:26:10
    at Request.<anonymous> (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-sdk/lib/request.js:38:9)
    at Request.<anonymous> (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-sdk/lib/request.js:688:12)
    at Request.callListeners (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-sdk/lib/sequential_executor.js:116:18) {
  code: 'InvalidClientTokenId',
  time: 2024-06-04T04:45:58.320Z,
  requestId: '6d421614-60e0-457a-a975-c3c28fa8018d',
  statusCode: 403,
  retryable: false,
  retryDelay: 329.79703877606846
}

Docker の LocalStack を参照するようにしなきゃ。

amay077amay077

LocalStack と CDK で遊んでみる (1)

npm install -g aws-cdk-local

もう入ってたw

cdk の代わりに cdklocal を使うようだが、cdk init はもう実行してしまったので無視して、

cdklocal bootstrap aws://000000000000/us-east-1

を実行。
成功したっぽい。

amay077amay077

https://zenn.dev/link/comments/33ed2cef683805 に戻って、

npm run watch

を実行。いきなり大量のエラーが。

[13:50:48] Starting compilation in watch mode...

node_modules/@types/babel__traverse/index.d.ts:302:20 - error TS1005: ']' expected.

302         [N in Node as N["type"]]?: VisitNode<S, N extends { type: N["type"] } ? N : never>;
                       ~~

node_modules/@types/babel__traverse/index.d.ts:302:23 - error TS1005: ';' expected.

302         [N in Node as N["type"]]?: VisitNode<S, N extends { type: N["type"] } ? N : never>;
                          ~

node_modules/@types/babel__traverse/index.d.ts:302:32 - error TS1005: ';' expected.

302         [N in Node as N["type"]]?: VisitNode<S, N extends { type: N["type"] } ? N : never>;
                                   ~

node_modules/@types/babel__traverse/index.d.ts:302:33 - error TS1128: Declaration or statement expected.

302         [N in Node as N["type"]]?: VisitNode<S, N extends { type: N["type"] } ? N : never>;
                                    ~

hello-cdk/package-lock.json の typescript のバージョン 3.9.10 だけど大丈夫か?

amay077amay077
rm -rf /node_modules
rm package-lock.json

して、 npm i してみたけど変わらず。

amay077amay077
npm uninstall typescript
npm i -D typescript

して、npm run build でエラーなくなった。

amay077amay077

hello-cdk/lib/hello-cdk-stack.ts を下のように記述。

import { App, RemovalPolicy, Stack, StackProps } from 'aws-cdk-lib';
import { AttributeType, Table } from 'aws-cdk-lib/aws-dynamodb';
import { Construct } from 'constructs';

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

    new Table(this, "items", {
      partitionKey: {
        name: "itemId",
        type: AttributeType.STRING,
      },
      tableName: "items",
      removalPolicy: RemovalPolicy.DESTROY, // NOT recommended for production code
    });    
  }
}

const app = new App();
new HelloCdkStack(app, "HelloCdkStack");
app.synth();

cdklocal deploy してみたらエラー。

cdklocal deploy

✨  Synthesis time: 3.2s

Could not assume arn:aws:iam::000000000000:role/cdk-hnb659fds-lookup-role-000000000000-ap-northeast-1, proceeding anyway.
(To get rid of this warning, please upgrade to bootstrap version >= 8)
HelloCdkStack: deploying...

 ❌  HelloCdkStack failed: Error: HelloCdkStack: SSM parameter /cdk-bootstrap/hnb659fds/version not found. Has the environment been bootstrapped? Please run 'cdk bootstrap' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)
    at CloudFormationDeployments.validateBootstrapStackVersion (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/api/cloudformation-deployments.ts:523:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at CloudFormationDeployments.publishStackAssets (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/api/cloudformation-deployments.ts:498:7)
    at CloudFormationDeployments.deployStack (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/api/cloudformation-deployments.ts:309:5)
    at CdkToolkit.deploy (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/cdk-toolkit.ts:208:24)
    at initCommandLine (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/cli.ts:310:12)

NOTICES

19179   (aws-eks): Regression in installing Helm charts from assets

        Overview: Helm charts fail to install when provided as an asset. This
                  issue does not affect charts installed from a repository.

        Affected versions: framework: 2.14.0, framework: 1.146.0

        More information at: https://github.com/aws/aws-cdk/issues/19179


If you don’t want to see a notice anymore, use "cdk acknowledge <id>". For example, "cdk acknowledge 28465".
HelloCdkStack: SSM parameter /cdk-bootstrap/hnb659fds/version not found. Has the environment been bootstrapped? Please run 'cdk bootstrap' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)

cdklocal init しないとダメかなあ?

amay077amay077

cdklocal でやりなおしてみる。

rm -rf hello-cdk
mkdir hello-cdk
cd hello-cdk 
cdklocal init --language typescript
cdklocal bootstrap aws://000000000000/us-east-1

また、npm run build でエラー出まくるので、

npm uninstall typescript
npm i -D typescript

もする。

amay077amay077

さっきのソースコードを貼り付けて

npm run build
 cdklocal deploy  

してみたけど同じエラー。

hello-cdk % cdklocal deploy                                

✨  Synthesis time: 2.64s

Could not assume arn:aws:iam::000000000000:role/cdk-hnb659fds-lookup-role-000000000000-ap-northeast-1, proceeding anyway.
(To get rid of this warning, please upgrade to bootstrap version >= 8)
HelloCdkStack: deploying...

 ❌  HelloCdkStack failed: Error: HelloCdkStack: SSM parameter /cdk-bootstrap/hnb659fds/version not found. Has the environment been bootstrapped? Please run 'cdk bootstrap' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)
    at CloudFormationDeployments.validateBootstrapStackVersion (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/api/cloudformation-deployments.ts:523:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at CloudFormationDeployments.publishStackAssets (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/api/cloudformation-deployments.ts:498:7)
    at CloudFormationDeployments.deployStack (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/api/cloudformation-deployments.ts:309:5)
    at CdkToolkit.deploy (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/cdk-toolkit.ts:208:24)
    at initCommandLine (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/cli.ts:310:12)

NOTICES

19179   (aws-eks): Regression in installing Helm charts from assets

        Overview: Helm charts fail to install when provided as an asset. This
                  issue does not affect charts installed from a repository.

        Affected versions: framework: 2.14.0, framework: 1.146.0

        More information at: https://github.com/aws/aws-cdk/issues/19179


If you don’t want to see a notice anymore, use "cdk acknowledge <id>". For example, "cdk acknowledge 28465".
HelloCdkStack: SSM parameter /cdk-bootstrap/hnb659fds/version not found. Has the environment been bootstrapped? Please run 'cdk bootstrap' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)
amay077amay077
cdklocal bootstrap aws://000000000000/us-east-1

が怪しいと思い、

cdklocal bootstrap

の後で改めて

 cdklocal deploy  

したら通った。

HelloCdkStack: deploying...
[0%] start: Publishing 4ed6d2ccddb4cf7d99252edeef4be88f6939f96d06704357b6128cc893b93b81:current_account-current_region
[100%] success: Published 4ed6d2ccddb4cf7d99252edeef4be88f6939f96d06704357b6128cc893b93b81:current_account-current_region
HelloCdkStack: creating CloudFormation changeset...




 ✅  HelloCdkStack

✨  Deployment time: 5.16s

Stack ARN:
arn:aws:cloudformation:ap-northeast-1:000000000000:stack/HelloCdkStack/2b7a3089

✨  Total time: 8.04s
amay077amay077

再び https://zenn.dev/link/comments/33ed2cef683805 に戻って、Lambda を作成する。

記事では Dynamo からデータを取得するコード例が記述されているが、どうせ Dynamo は使わないので、単純な Hello World にして↓を hello-cdk/lib/lambda/get-item.ts に記述。

export const handler = async (event: any = {}): Promise<any> => {
  return { statusCode: 200, body: JSON.stringify({ message: 'hello lambdadadadada' }) };
};
amay077amay077

Lambda を追加

hello-cdk/lib/hello-cdk-stack.ts を↓のように修正。
(もはや new Table は要らないが)

Function の auto import が効かなかったので、手動で import 文を追加した。

import { App, RemovalPolicy, Stack, StackProps } from 'aws-cdk-lib';
import { AttributeType, Table } from 'aws-cdk-lib/aws-dynamodb';
import { Runtime, Function, AssetCode } from 'aws-cdk-lib/aws-lambda';
import { Construct } from 'constructs';

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

    new Table(this, "items", {
      partitionKey: {
        name: "itemId",
        type: AttributeType.STRING,
      },
      tableName: "items",
      removalPolicy: RemovalPolicy.DESTROY, // NOT recommended for production code
    });    

    new Function(this, "getOneItemFunction", {
      code: new AssetCode("lib/lambda"),
      handler: "get-item.handler",
      runtime: Runtime.NODEJS_8_10,
    });    
  }
}

const app = new App();
new HelloCdkStack(app, "HelloCdkStack");
app.synth();

``cdklocal diff``` したら、うまくいってそう。

cdklocal diff  
Stack HelloCdkStack
IAM Statement Changes
┌───┬───────────────────────────────────────┬────────┬────────────────┬──────────────────────────────┬───────────┐
│   │ Resource                              │ Effect │ Action         │ Principal                    │ Condition │
├───┼───────────────────────────────────────┼────────┼────────────────┼──────────────────────────────┼───────────┤
│ + │ ${getOneItemFunction/ServiceRole.Arn} │ Allow  │ sts:AssumeRole │ Service:lambda.amazonaws.com │           │
└───┴───────────────────────────────────────┴────────┴────────────────┴──────────────────────────────┴───────────┘
IAM Policy Changes
┌───┬───────────────────────────────────┬────────────────────────────────────────────────────────────────────────────────┐
│   │ Resource                          │ Managed Policy ARN                                                             │
├───┼───────────────────────────────────┼────────────────────────────────────────────────────────────────────────────────┤
│ + │ ${getOneItemFunction/ServiceRole} │ arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole │
└───┴───────────────────────────────────┴────────────────────────────────────────────────────────────────────────────────┘
(NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299)

Resources
[+] AWS::IAM::Role getOneItemFunction/ServiceRole getOneItemFunctionServiceRoleCFD54796 
[+] AWS::Lambda::Function getOneItemFunction getOneItemFunctionE3257B22 

amay077amay077

API Gateway を追加

hello-cdk/lib/hello-cdk-stack.ts を↓のように修正。
curl から導通確認ができればよいので CORS 関連コードは無視した。

import { App, RemovalPolicy, Stack, StackProps } from 'aws-cdk-lib';
import { LambdaIntegration, RestApi } from 'aws-cdk-lib/aws-apigateway';
import { AttributeType, Table } from 'aws-cdk-lib/aws-dynamodb';
import { Runtime, Function, AssetCode } from 'aws-cdk-lib/aws-lambda';
import { Construct } from 'constructs';

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

    new Table(this, "items", {
      partitionKey: {
        name: "itemId",
        type: AttributeType.STRING,
      },
      tableName: "items",
      removalPolicy: RemovalPolicy.DESTROY, // NOT recommended for production code
    });    

    const getItemLambda = new Function(this, "getOneItemFunction", {
      code: new AssetCode("lib/lambda"),
      handler: "get-item.handler",
      runtime: Runtime.NODEJS_8_10,
    });

    // ApiGateway
    const api = new RestApi(this, "sampleApi", {
      restApiName: "Sample API",
    });
    const items = api.root.addResource("items");
    const singleItem = items.addResource("{id}");
    const getItemIntegration = new LambdaIntegration(getItemLambda);
    singleItem.addMethod("GET", getItemIntegration);    

  }
}

const app = new App();
new HelloCdkStack(app, "HelloCdkStack");
app.synth();
amay077amay077

cdklocal deploy したら、

HelloCdkStack: creating CloudFormation changeset...
14:23:03 | CREATE_FAILED        | AWS::Lambda::Function       | getOneItemFunctionE3257B22
An error occurred (InvalidParameterValueException) when calling the CreateFunction operation: Value nodejs8.10 at 'runtime' failed to satisfy constraint: Member must satisfy e
num value set: [nodejs20.x, provided.al2023, python3.12, java17, nodejs16.x, dotnet8, python3.10, java11, python3.11, dotnet6, java21, nodejs18.x, provided.al2, ruby3.3, java8
.al2, ruby3.2, python3.8, python3.9] or be a valid ARN

のエラー。
Runtime.NODEJS_8_10 (node 8.10) を指定していたので、「そりゃサポート外だわw」と nodejs16.x を Runtime.xxx から探してみたけど、無い。

package.json では "aws-cdk": "2.14.0" となっているけど、バージョン古杉内?

amay077amay077
npm uninstall aws-cdk aws-cdk-lib
npm i -D aws-cdk aws-cdk-lib

したらバージョンは、2.144.0 になった。

NODEJS_18_X, NODEJS_20_X が使えるようになったので、 NODEJS_18_X を使用。

amay077amay077

改めて cdklocal deploy したらエラー。

# cdklocal deploy          

This CDK CLI is not compatible with the CDK library used by your application. Please upgrade the CLI to the latest version.
(Cloud assembly schema version mismatch: Maximum schema version supported is 16.0.0, but found 36.0.0)
amay077amay077

-g インストールされていた aws-cdk と aws-cdk-local が古いのかな?と思い入れ直し。

npm uninstall -g aws-cdk aws-cdk-local
npm install -g aws-cdk aws-cdk-local
amay077amay077

↑とは関係ないと思うが、package-lock.json と node_modules を削除して npm i したらエラー。

npm i
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: hello-cdk@0.1.0
npm ERR! Found: typescript@5.4.5
npm ERR! node_modules/typescript
npm ERR!   dev typescript@"^5.4.5" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer typescript@">=3.8 <5.0" from ts-jest@26.5.6
npm ERR! node_modules/ts-jest
npm ERR!   dev ts-jest@"^26.2.0" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

ts-jest が許容する typescript のバージョンは 5.0までらしい、今は 5.4.5。

amay077amay077

前に進むしかねぇ!ということですべて入れ直し。

npm uninstall typescript jest ts-jest @types/jest
npm i -D typescript jest ts-jest @types/jest

成功。npm run build も通った。

package.json は現行こうなった(package-lock.json は面倒なのでみてない)。

  "devDependencies": {
    "@types/jest": "^29.5.12",
    "@types/node": "10.17.27",
    "aws-cdk": "^2.144.0",
    "aws-cdk-lib": "^2.144.0",
    "jest": "^29.7.0",
    "ts-jest": "^29.1.4",
    "ts-node": "^9.0.0",
    "typescript": "^5.4.5"
  },
amay077amay077

恐る恐る cdklocal deploy したらエラー。

% cdklocal deploy
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!                                                                            !!
!!  Node 17 has reached end-of-life on 2022-06-01 and is not supported.       !!
!!  Please upgrade to a supported node version as soon as possible.           !!
!!                                                                            !!
!!  This software is currently running on node v17.4.0.                       !!
!!  As of the current release of this software, supported node releases are:  !!
!!  - ^22.0.0 (Planned end-of-life: 2027-04-30)                               !!
!!  - ^20.0.0 (Planned end-of-life: 2026-04-30)                               !!
!!  - ^18.0.0 (Planned end-of-life: 2025-04-30)                               !!
!!                                                                            !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

✨  Synthesis time: 2.11s

HelloCdkStack:  start: Building 2ef654090e8bab22f351620217a28393ce798f6003ffb8f2317dc36ee345a48e:current_account-current_region
HelloCdkStack:  success: Built 2ef654090e8bab22f351620217a28393ce798f6003ffb8f2317dc36ee345a48e:current_account-current_region
HelloCdkStack:  start: Building d1beaf7a6c3c1c295226b75f1f6581161edbc528790443250b3ca5b1928b3eea:current_account-current_region
HelloCdkStack:  success: Built d1beaf7a6c3c1c295226b75f1f6581161edbc528790443250b3ca5b1928b3eea:current_account-current_region
HelloCdkStack:  start: Publishing 2ef654090e8bab22f351620217a28393ce798f6003ffb8f2317dc36ee345a48e:current_account-current_region
HelloCdkStack:  start: Publishing d1beaf7a6c3c1c295226b75f1f6581161edbc528790443250b3ca5b1928b3eea:current_account-current_region
HelloCdkStack:  success: Published d1beaf7a6c3c1c295226b75f1f6581161edbc528790443250b3ca5b1928b3eea:current_account-current_region
HelloCdkStack:  success: Published 2ef654090e8bab22f351620217a28393ce798f6003ffb8f2317dc36ee345a48e:current_account-current_region
HelloCdkStack: deploying... [1/1]
HelloCdkStack: creating CloudFormation changeset...
14:45:12 | UPDATE_FAILED        | AWS::Lambda::Function       | getOneItemFunctionE3257B22
Failed to delete resource with id getOneItemFunctionE3257B22 of type AWS::Lambda::Function

14:45:12 | UPDATE_FAILED        | AWS::Lambda::Function       | getOneItemFunctionE3257B22
Resource handler returned message: "Failed to delete resource with id getOneItemFunctionE3257B22 of type AWS::Lambda::Function" (RequestToken: 10c10335-276a-33d3-5c07-018b684c
3d26, HandlerErrorCode: InvalidRequest)None


 ❌  HelloCdkStack failed: Error: The stack named HelloCdkStack failed to deploy: CREATE_FAILED (Resource handler returned message: "Failed to delete resource with id getOneItemFunctionE3257B22 of type AWS::Lambda::Function" (RequestToken: 10c10335-276a-33d3-5c07-018b684c3d26, HandlerErrorCode: InvalidRequest)None): Failed to delete resource with id getOneItemFunctionE3257B22 of type AWS::Lambda::Function, Resource handler returned message: "Failed to delete resource with id getOneItemFunctionE3257B22 of type AWS::Lambda::Function" (RequestToken: 10c10335-276a-33d3-5c07-018b684c3d26, HandlerErrorCode: InvalidRequest)None
    at FullCloudFormationDeployment.monitorDeployment (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/index.js:442:10568)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Object.deployStack2 [as deployStack] (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/index.js:445:199515)
    at async /Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/index.js:445:181237

 ❌ Deployment failed: Error: The stack named HelloCdkStack failed to deploy: CREATE_FAILED (Resource handler returned message: "Failed to delete resource with id getOneItemFunctionE3257B22 of type AWS::Lambda::Function" (RequestToken: 10c10335-276a-33d3-5c07-018b684c3d26, HandlerErrorCode: InvalidRequest)None): Failed to delete resource with id getOneItemFunctionE3257B22 of type AWS::Lambda::Function, Resource handler returned message: "Failed to delete resource with id getOneItemFunctionE3257B22 of type AWS::Lambda::Function" (RequestToken: 10c10335-276a-33d3-5c07-018b684c3d26, HandlerErrorCode: InvalidRequest)None
    at FullCloudFormationDeployment.monitorDeployment (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/index.js:442:10568)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Object.deployStack2 [as deployStack] (/Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/index.js:445:199515)
    at async /Volumes/extssd/data/.anyenv/envs/nodenv/versions/17.4.0/lib/node_modules/aws-cdk/lib/index.js:445:181237

The stack named HelloCdkStack failed to deploy: CREATE_FAILED (Resource handler returned message: "Failed to delete resource with id getOneItemFunctionE3257B22 of type AWS::Lambda::Function" (RequestToken: 10c10335-276a-33d3-5c07-018b684c3d26, HandlerErrorCode: InvalidRequest)None): Failed to delete resource with id getOneItemFunctionE3257B22 of type AWS::Lambda::Function, Resource handler returned message: "Failed to delete resource with id getOneItemFunctionE3257B22 of type AWS::Lambda::Function" (RequestToken: 10c10335-276a-33d3-5c07-018b684c3d26, HandlerErrorCode: InvalidRequest)None

global インストールした node のバージョンが 17.x だったので、cdklocal を最新にしたらサポート切れとるでと怒られが発生。以降のエラーがそれに起因するかは不明。

amay077amay077

"Failed to delete resource with id getOneItemFunctionE3257B22 of type AWS::Lambda::Function"

って出てるから、何かゴミが残ってるのかな?と思い、Docker の LocalStack を再起動。

docker compose down
docker compose up -d

その後、cdklocal で bootstrap -> deploy を実行。

cdklocal bootstrap
cdklocal deploy

成功した。

(前略)
HelloCdkStack: deploying... [1/1]
HelloCdkStack: creating CloudFormation changeset...

 ✅  HelloCdkStack

✨  Deployment time: 20.16s

Outputs:
HelloCdkStack.sampleApiEndpoint5CD177F1 = https://2h34herwg7.execute-api.localhost.localstack.cloud:4566/prod/
Stack ARN:
arn:aws:cloudformation:ap-northeast-1:000000000000:stack/HelloCdkStack/b6f7b894

✨  Total time: 22.23s
amay077amay077
curl  https://2h34herwg7.execute-api.localhost.localstack.cloud:4566/prod/items/123

を実行したら

{"message":"hello lambdadadadada"}

が返却された。

amay077amay077

https://app.localstack.cloud/inst/default/resources

ローカルで起動した localstack(紛らわしいなw)のリソースを可視化できる。
アカウントは作っておかないとダメぽい。

RDS は Pro 版らしいので、Postgres をローカルにホストするのは localstack Free 版ではできないようだ。

amay077amay077

https://zenn.dev/link/comments/373e1cfe457491

localstack + AWS CDK で S3 のバケットを作ることはできたが、バケットにファイルをアップロードする機能が動作しない。本物のAWS S3 では動いていた。

これは LocalStack の Pro版 が必要、ということが判った。
LocalStack のログに出てた。

localstack_myapp01  | 2024-07-05T05:49:00.141  WARN --- [functhread44] l.s.c.deployment_utils     
  : No resource provider found for "Custom::CDKBucketDeployment". 
  To find out if Custom::CDKBucketDeployment is supported in LocalStack Pro, 
  please check out our docs at https://docs.localstack.cloud/user-guide/aws/cloudformation/#resources-pro--enterprise-edition

docker compose up -d してたから気付かなかった。
開発中は docker compose up の方がログが見られてよい。