CLOVER🍀

That was when it all began.

Amazon EventBridgeでスケジューリング起動するAWS Lambda関数を、AWS SAM+LocalStackで試す

これは、なにをしたくて書いたもの?

Amazon EventBridgeを使って、AWS Lambda関数をスケジュール実行させてみたいなということで。

LocalStackでAmazon EventBridgeを使えそうだったので、試してみることにしました。

Amazon EventBridge

Amazon EventBridgeは、イベントを受信してターゲットにルーティングするサービスらしいです。

Amazon EventBridge とは - Amazon EventBridge

登場要素としてはAmazon EventBridgeに届くイベント、イベントが関連付けられるイベントバス、そしてイベントバスに関連付けられた
ルールです。

イベントバスとは、イベントを受信するパイプラインです。イベントバスに関連付けられたルールによって、受信したイベントが評価されます。各ルールは、イベントがルールの条件に一致するかどうかをチェックします。ルールを特定のイベントバスに関連付けると、そのルールはそのイベントバスで受信したイベントにのみ適用されます。

Amazon EventBridge イベントバス - Amazon EventBridge

イベントとは、AWS 環境、SaaS パートナーサービスやアプリケーション、またはお客様のアプリケーションやサービスなどの環境での変化を示します。

Amazon EventBridge イベント - Amazon EventBridge

ルールは、受信したイベントをマッチングし、処理のためにターゲットに送信します。1 つのルールで複数のターゲットにイベントを送信し、並行して実行することができます。ルールは、イベントパターンまたはスケジュールに基づいて作成します。イベントパターンでは、ルールでマッチングするイベント構造とフィールドを定義します。スケジュールに基づいたルールは、一定の間隔でアクションを実行します。

Amazon EventBridge ルール - Amazon EventBridge

今回は、スケジュールに基づいたルールを使います。

スケジュールに従って実行する Amazon EventBridge ルールの作成 - Amazon EventBridge

なお、イベント受信時のルールについてはこちらです。

イベントに反応する Amazon EventBridge ルールの作成 - Amazon EventBridge

環境

今回の環境は、こちら。

$ python3 -V
Python 3.8.10


$ localstack --version
1.2.0

LocalStackを起動。

$ LAMBDA_EXECUTOR=docker-reuse localstack start

AWS CLIおよびAWS SAM CLIと、合わせてLocalStackの関連ツール。

$ awslocal --version
aws-cli/2.8.2 Python/3.9.11 Linux/5.4.0-126-generic exe/x86_64.ubuntu.20 prompt/off


$ samlocal --version
SAM CLI, version 1.53.0

アプリケーションを作成する際に使用するNode.jsのバージョン。

$ node --version
v16.17.1


$ npm --version
8.15.0

AWS Lambda関数としても、Node.js 16で動かすことにします。

AWS SAMプロジェクトを作成する

まずは、AWS SAMプロジェクトを作成します。ランタイムはNode.js 16、テンプレートはquick-start-cloudwatch-eventsを選択します。

$ samlocal init --name sam-lambda-eventbridge --runtime nodejs16.x --app-template quick-start-cloudwatch-events --package-type Zip --no-tracing

名前がcloudwatch-eventsとなっていますが、これはAmazon EventBridgeが以前Amazon CloudWatch Eventsと呼ばれていた頃の名残り
なんでしょうね。

EventBridge は、以前は Amazon CloudWatch Events と呼ばれていました。CloudWatch Events で作成したデフォルトのイベントバスとルールも EventBridge コンソールに表示されます。EventBridge では同じ CloudWatch Events API を使用するため、CloudWatch Events API を使用するコードに変化はありません。EventBridge に追加された新機能は、CloudWatch Events には追加されません。

Amazon EventBridge とは - Amazon EventBridge

AWS SAMのAmazon EventBridge向けのテンプレートにTypeScriptのものはないため、ここからプロジェクトをTypeScriptに変えていきます。

ディレクトリ内に移動。

$ cd sam-lambda-eventbridge

構成。

$ tree
.
├── README.md
├── __tests__
│   └── unit
│       └── handlers
│           └── scheduled-event-logger.test.js
├── buildspec.yml
├── events
│   └── event-cloudwatch-event.json
├── package.json
├── src
│   └── handlers
│       └── scheduled-event-logger.js
└── template.yaml

6 directories, 7 files

生成された各ファイルも見ておきます。

package.json

{
    "name": "replaced-by-user-input",
    "description": "replaced-by-user-input",
    "version": "0.0.1",
    "private": true,
    "dependencies": {},
    "devDependencies": {
        "jest": "^26.6.3"
    },
    "scripts": {
        "test": "jest"
    }
}

src/handlers/scheduled-event-logger.js

/**
 * A Lambda function that logs the payload received from a CloudWatch scheduled event.
 */
exports.scheduledEventLoggerHandler = async (event, context) => {
    // All log statements are written to CloudWatch by default. For more information, see
    // https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-logging.html
    console.info(JSON.stringify(event));
}

__tests__/unit/handlers/scheduled-event-logger.test.js

// Import all functions from scheduled-event-logger.js
const scheduledEventLogger = require('../../../src/handlers/scheduled-event-logger.js');

describe('Test for sqs-payload-logger', function () {
  // This test invokes the scheduled-event-logger Lambda function and verifies that the received payload is logged
  it('Verifies the payload is logged', async () => {
    // Mock console.log statements so we can verify them. For more information, see
    // https://jestjs.io/docs/en/mock-functions.html
    console.info = jest.fn()

    // Create a sample payload with CloudWatch scheduled event message format
    var payload = {
      "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c",
      "detail-type": "Scheduled Event",
      "source": "aws.events",
      "account": "",
      "time": "1970-01-01T00:00:00Z",
      "region": "us-west-2",
      "resources": [
        "arn:aws:events:us-west-2:123456789012:rule/ExampleRule"
      ],
      "detail": {}
    }

    await scheduledEventLogger.scheduledEventLoggerHandler(payload, null)

    // Verify that console.info has been called with the expected payload
    expect(console.info).toHaveBeenCalledWith(JSON.stringify(payload))
  });
});

events/event-cloudwatch-event.json

{
  "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c",
  "detail-type": "Scheduled Event",
  "source": "aws.events",
  "account": "",
  "time": "1970-01-01T00:00:00Z",
  "region": "us-west-2",
  "resources": [
    "arn:aws:events:us-west-2:123456789012:rule/ExampleRule"
  ],
  "detail": {}
}

buildspec.yml

version: 0.2

phases:
  install:
    commands:
      # Install all dependencies (including dependencies for running tests)
      - npm install
  pre_build:
    commands:
      # Discover and run unit tests in the '__tests__' directory
      - npm run test
      # Remove all unit tests to reduce the size of the package that will be ultimately uploaded to Lambda
      - rm -rf ./__tests__
      # Remove all dependencies not needed for the Lambda deployment package (the packages from devDependencies in package.json)
      - npm prune --production
  build:
    commands:
      # Use AWS SAM to package the application by using AWS CloudFormation
      - aws cloudformation package --template template.yaml --s3-bucket $S3_BUCKET --output-template template-export.yml
artifacts:
  type: zip
  files:
    - template-export.yml

template.yaml

# This is the SAM template that represents the architecture of your serverless application
# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html

# The AWSTemplateFormatVersion identifies the capabilities of the template
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/format-version-structure.html
AWSTemplateFormatVersion: 2010-09-09
Description: >-
  sam-lambda-eventbridge

# Transform section specifies one or more macros that AWS CloudFormation uses to process your template
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-section-structure.html
Transform:
- AWS::Serverless-2016-10-31

# Resources declares the AWS resources that you want to include in the stack
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html
Resources:
  # This is the Lambda function definition associated with the source code: sqs-payload-logger.js. For all available properties, see
  # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
  ScheduledEventLogger:
    Type: AWS::Serverless::Function
    Properties:
      Description: A Lambda function that logs the payload of messages sent to an associated SQS queue.
      Runtime: nodejs16.x
      Architectures:
        - x86_64
      Handler: src/handlers/scheduled-event-logger.scheduledEventLoggerHandler
      # This property associates this Lambda function with a scheduled CloudWatch Event. For all available properties, see
      # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#schedule
      # This example runs every hour.
      Events:
        CloudWatchEvent:
          Type: Schedule
          Properties:
            Schedule: cron(0 * * * ? *)
      MemorySize: 128
      Timeout: 100

よーく見ると、テストコードやtemplate.yamlにSQSの名前が入っていますね。Amazon SQS向けのテンプレートを流用して作ったんでしょうか。

TypeScriptプロジェクトに変更する

ここから、TypeScriptプロジェクトに変更していきます。

AWS SAMのTypeScript向けのテンプレートも参考にしています。

https://github.com/aws/aws-sam-cli-app-templates/tree/f7af69d483450d09f1bd5ea300d57e00032370c7/nodejs16.x/cookiecutter-aws-sam-hello-typescript-nodejs/%7B%7Bcookiecutter.project_name%7D%7D

まず、package.jsonからdependenciesおよびdevDependenciesを削除

{
    "name": "replaced-by-user-input",
    "description": "replaced-by-user-input",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "test": "jest"
    }
}

npmモジュールをインストール。

$ npm i esbuild
$ npm i -D typescript eslint eslint-config-prettier eslint-plugin-prettier prettier @typescript-eslint/eslint-plugin @typescript-eslint/parser
$ npm i -D jest esbuild-jest
$ npm i -D @types/node@v16 @types/aws-lambda @types/jest

依存関係は、このようになりました。

    "dependencies": {
        "esbuild": "^0.15.10"
    },
    "devDependencies": {
        "@types/aws-lambda": "^8.10.106",
        "@types/jest": "^29.1.2",
        "@types/node": "^16.11.64",
        "@typescript-eslint/eslint-plugin": "^5.39.0",
        "@typescript-eslint/parser": "^5.39.0",
        "esbuild-jest": "^0.5.0",
        "eslint": "^8.25.0",
        "eslint-config-prettier": "^8.5.0",
        "eslint-plugin-prettier": "^4.2.1",
        "jest": "^29.1.2",
        "prettier": "^2.7.1",
        "typescript": "^4.8.4"
    }

scriptsも設定。

    "scripts": {
        "test": "jest",
        "lint": "eslint src --ext .ts",
        "format": "prettier --write src __tests__"
    },

インストールしたモジュールに合わせて、設定ファイルを作成します。

tsconfig.json

{
  "compilerOptions": {
    "target": "es2020",
    "strict": true,
    "baseUrl": "./src",
    "outDir": "dist",
    "noEmit": true,
    "sourceMap": false,
    "module":"es2015",
    "moduleResolution":"node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
  },
  "exclude": ["node_modules", "**/*.test.ts"]
}

jest.config.js

module.exports = {
  testEnvironment: 'node',
  transform: {
    "^.+\\.tsx?$": "esbuild-jest"
  }
};

.prettierrc.json

{
  "singleQuote": true,
  "printWidth": 120
}

.eslintrc.js

module.exports = {
  parser: "@typescript-eslint/parser",
  parserOptions: {
    ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features
    sourceType: "module"
  },
  extends: [
    "plugin:@typescript-eslint/recommended", // recommended rules from the @typescript-eslint/eslint-plugin
    "plugin:prettier/recommended" // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
  ],
  rules: {
    // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
    // e.g. "@typescript-eslint/explicit-function-return-type": "off",
  }
};

.eslintignore

node_modules
.aws-sam

.npmignore

tests/*

元のJavaScriptソースコードを参考にしつつ、テストコードを作成しましょう。

src/handlers/scheduled-event-logger.ts

import { Context, ScheduledEvent } from 'aws-lambda';

export const scheduledEventLoggerHandler = async (event: ScheduledEvent, context: Context) => {
  console.log('trigger lambda!!');
  console.info(JSON.stringify(event, null, 2));
};

諸事情(後述)があって、元のJavaScriptにはなかったconsole#logを追加しています。

__tests__/unit/handlers/scheduled-event-logger.test.ts

import { Context, ScheduledEvent } from 'aws-lambda';
import { scheduledEventLoggerHandler } from '../../../src/handlers/scheduled-event-logger';

test('Test for eventbridge-payload-logger', async () => {
  console.info = jest.fn();

  const payload: ScheduledEvent = {
    id: 'cdc73f9d-aea9-11e3-9d5a-835b769c0d9c',
    'detail-type': 'Scheduled Event',
    source: 'aws.events',
    account: '',
    time: '1970-01-01T00:00:00Z',
    region: 'us-west-2',
    resources: ['arn:aws:events:us-west-2:123456789012:rule/ExampleRule'],
    detail: {},
    version: '1',
  };

  await scheduledEventLoggerHandler(payload, {} as Context);

  expect(console.info).toHaveBeenCalledWith(JSON.stringify(payload, null, 2));
});

payloadは、sam local generate-event cloudwatch scheduled-eventで生成したものとほぼ同じですね。

$ samlocal local generate-event cloudwatch scheduled-event
{
  "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c",
  "detail-type": "Scheduled Event",
  "source": "aws.events",
  "account": "123456789012",
  "time": "1970-01-01T00:00:00Z",
  "region": "us-east-1",
  "resources": [
    "arn:aws:events:us-east-1:123456789012:rule/ExampleRule"
  ],
  "detail": {}
}

ScheduledEvent型にすると、versionが足りないと怒られたので追加しましたが…。

ソースコードは作成したので、もともとのJavaScriptファイルは削除。

$ rm src/handlers/scheduled-event-logger.js __tests__/unit/handlers/scheduled-event-logger.test.js

テストを実行して確認。

$ npm test

> replaced-by-user-input@0.0.1 test
> jest

  console.log
    trigger lambda!!

      at scheduledEventLoggerHandler (src/handlers/scheduled-event-logger.ts:24:11)

 PASS  __tests__/unit/handlers/scheduled-event-logger.test.ts
  ✓ Test for eventbridge-payload-logger (23 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.356 s, estimated 2 s
Ran all test suites.

OKですね。

LocalStackにデプロイする

ソースコードはできたので、LocalStackにデプロイしましょう。

その前に、少しtemplate.yamlを修正します。

TypeScriptをesbuildでビルドするために、Metadataを追加

    Metadata: # Manage esbuild properties
      BuildMethod: esbuild
      BuildProperties:
        Minify: true
        Target: "es2020"
        # Sourcemap: true # Enabling source maps will create the required NODE_OPTIONS environment variables on your lambda function during sam build
        EntryPoints: 
        - src/handlers/scheduled-event-logger.ts

Handlerの設定を修正。

      # Handler: src/handlers/scheduled-event-logger.scheduledEventLoggerHandler
      Handler: scheduled-event-logger.scheduledEventLoggerHandler

Scheduleは1時間に1回実行するようになっていたので、今回は1分ごとに実行するよう修正。

            # Schedule: cron(0 * * * ? *)
            Schedule: cron(0/1 * * * ? *)

あと、LocalStack固有の話として生成されたTransformがこのままだと動かないので、以下のように修正。

# Transform:
# - AWS::Serverless-2016-10-31
Transform: AWS::Serverless-2016-10-31

全体としてはこうなりました。

template.yaml

# This is the SAM template that represents the architecture of your serverless application
# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html

# The AWSTemplateFormatVersion identifies the capabilities of the template
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/format-version-structure.html
AWSTemplateFormatVersion: 2010-09-09
Description: >-
  sam-lambda-eventbridge

# Transform section specifies one or more macros that AWS CloudFormation uses to process your template
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-section-structure.html
# Transform:
# - AWS::Serverless-2016-10-31
Transform: AWS::Serverless-2016-10-31

# Resources declares the AWS resources that you want to include in the stack
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html
Resources:
  # This is the Lambda function definition associated with the source code: sqs-payload-logger.js. For all available properties, see
  # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
  ScheduledEventLogger:
    Type: AWS::Serverless::Function
    Properties:
      Description: A Lambda function that logs the payload of messages sent to an associated SQS queue.
      Runtime: nodejs16.x
      Architectures:
        - x86_64
      # Handler: src/handlers/scheduled-event-logger.scheduledEventLoggerHandler
      Handler: scheduled-event-logger.scheduledEventLoggerHandler
      # This property associates this Lambda function with a scheduled CloudWatch Event. For all available properties, see
      # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#schedule
      # This example runs every hour.
      Events:
        CloudWatchEvent:
          Type: Schedule
          Properties:
            # Schedule: cron(0 * * * ? *)
            Schedule: cron(0/1 * * * ? *)
      MemorySize: 128
      Timeout: 100
    Metadata: # Manage esbuild properties
      BuildMethod: esbuild
      BuildProperties:
        Minify: true
        Target: "es2020"
        # Sourcemap: true # Enabling source maps will create the required NODE_OPTIONS environment variables on your lambda function during sam build
        EntryPoints:
        - src/handlers/scheduled-event-logger.ts

ちなみに、ScheduleというのはAmazon EventBridgeのスケジュールルールを指しています。

        CloudWatchEvent:
          Type: Schedule

Schedule - AWS Serverless Application Model

今回は使いませんが、イベントルールの場合はこちらですね。

EventBridgeRule - AWS Serverless Application Model

では、デプロイします。

$ yes | samlocal sync --stack-name $(uuidgen) --region us-east-1 --no-dependency-layer

リソースが作成されたようです。

2022-10-09 02:33:40 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 0.5 seconds)
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                             ResourceType                               LogicalResourceId                          ResourceStatusReason
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE_COMPLETE                            AWS::CloudFormation::Stack                 ScheduledEventLoggerRole                   -
CREATE_COMPLETE                            AWS::CloudFormation::Stack                 ScheduledEventLogger                       -
CREATE_COMPLETE                            AWS::CloudFormation::Stack                 ScheduledEventLoggerCloudWatchEvent        -
CREATE_COMPLETE                            AWS::CloudFormation::Stack                 ScheduledEventLoggerCloudWatchEventPermi   -
                                                                                      ssion
CREATE_COMPLETE                            AWS::CloudFormation::Stack                 9a5ee5c1-6e0f-4d99-bc43-9893f11ca893       -
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Stack creation succeeded. Sync infra completed.

少し確認してみましょう。

Amazon EventBridgeの確認。

$ awslocal events list-rules
{
    "Rules": [
        {
            "Name": "9a5ee5c1-6e0f-4d99-bc43-9893f-ScheduledEventLoggerClou-ac02b4c6",
            "Arn": "arn:aws:events:us-east-1:000000000000:rule/9a5ee5c1-6e0f-4d99-bc43-9893f-ScheduledEventLoggerClou-ac02b4c6",
            "State": "ENABLED",
            "ScheduleExpression": "cron(0/1 * * * ? *)",
            "EventBusName": "default"
        }
    ]
}

作成されていますね。

AWS Lambda関数。

$ awslocal lambda list-functions
{
    "Functions": [
        {
            "FunctionName": "9a5ee5c1-6e0f-4d99-bc43-9893f11ca-ScheduledEventLogger-406fe599",
            "FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:9a5ee5c1-6e0f-4d99-bc43-9893f11ca-ScheduledEventLogger-406fe599",
            "Runtime": "nodejs16.x",
            "Role": "arn:aws:iam::000000000000:role/9a5ee5c1-6e0f-4d99-bc43-9893f-ScheduledEventLoggerRole-7734425d",
            "Handler": "scheduled-event-logger.scheduledEventLoggerHandler",
            "CodeSize": 1076,
            "Description": "A Lambda function that logs the payload of messages sent to an associated SQS queue.",
            "Timeout": 100,
            "MemorySize": 128,
            "LastModified": "2022-10-08T17:33:42.124+0000",
            "CodeSha256": "dnPKOjcNikOJI6ZdYNej1mAGUAoQBNAj0e0jLRsOX+I=",
            "Version": "$LATEST",
            "VpcConfig": {},
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "RevisionId": "9b7f512f-63cc-4a5d-a3e5-4edca5f4b98a",
            "State": "Active",
            "LastUpdateStatus": "Successful",
            "PackageType": "Zip",
            "Architectures": [
                "x86_64"
            ]
        }
    ]
}

ログを確認。なぜか、Dockerコンテナのログを見る必要がありますが。

$ docker container logs -f localstack_main_lambda_arn_aws_lambda_us-east-1_000000000000_function_9a5ee5c1-6e0f-4d99-bc43-9893f11ca-ScheduledEventLogger-406fe599

AWS Lambda関数が、1分おきに実行されていることが確認できます。

Lambda API listening on port 9001...
START RequestId: 3c77c96f-9269-10e4-ca7f-99624807f505 Version: $LATEST
2022-10-08T17:34:51.178Z        3c77c96f-9269-10e4-ca7f-99624807f505    INFO    trigger lambda!!
2022-10-08T17:34:51.181Z        3c77c96f-9269-10e4-ca7f-99624807f505    INFO    {}
END RequestId: 3c77c96f-9269-10e4-ca7f-99624807f505
REPORT RequestId: 3c77c96f-9269-10e4-ca7f-99624807f505  Init Duration: 7139.57 ms       Duration: 13.90 ms      Billed Duration: 14 ms  Memory Size: 1536 MB    Max Memory Used: 43 MB
START RequestId: e5164470-d09d-1460-3c78-0cbd44fc6891 Version: $LATEST
2022-10-08T17:35:41.847Z        e5164470-d09d-1460-3c78-0cbd44fc6891    INFO    trigger lambda!!
2022-10-08T17:35:41.847Z        e5164470-d09d-1460-3c78-0cbd44fc6891    INFO    {}
END RequestId: e5164470-d09d-1460-3c78-0cbd44fc6891
REPORT RequestId: e5164470-d09d-1460-3c78-0cbd44fc6891  Duration: 3.95 ms       Billed Duration: 4 ms   Memory Size: 1536 MB    Max Memory Used: 44 MB
START RequestId: 9b7762bc-bf4b-1a00-9e31-96ed2f69634f Version: $LATEST
2022-10-08T17:36:41.805Z        9b7762bc-bf4b-1a00-9e31-96ed2f69634f    INFO    trigger lambda!!
2022-10-08T17:36:41.805Z        9b7762bc-bf4b-1a00-9e31-96ed2f69634f    INFO    {}
END RequestId: 9b7762bc-bf4b-1a00-9e31-96ed2f69634f
REPORT RequestId: 9b7762bc-bf4b-1a00-9e31-96ed2f69634f  Duration: 4.04 ms       Billed Duration: 5 ms   Memory Size: 1536 MB    Max Memory Used: 44 MB

なぜか、渡されたイベントの中身が空っぽなのですが…。

このため、代わりに「trigger lambda!!」というメッセージを出力するようにして動作確認とした感じです…。

ちなみに、LocalStack側でも空のイベントを送信していることは検知しているようですが…。

2022-10-08T17:35:41.830  INFO --- [  Thread-294] l.s.a.lambda_executors     : Empty event body specified for invocation of Lambda "arn:aws:lambda:us-east-1:000000000000:function:9a5ee5c1-6e0f-4d99-bc43-9893f11ca-ScheduledEventLogger-406fe599"
2022-10-08T17:35:41.830  INFO --- [  Thread-294] l.s.a.lambda_executors     : Running lambda: arn:aws:lambda:us-east-1:000000000000:function:9a5ee5c1-6e0f-4d99-bc43-9893f11ca-ScheduledEventLogger-406fe599
2022-10-08T17:36:41.788  INFO --- [  Thread-309] l.s.a.lambda_executors     : Empty event body specified for invocation of Lambda "arn:aws:lambda:us-east-1:000000000000:function:9a5ee5c1-6e0f-4d99-bc43-9893f11ca-ScheduledEventLogger-406fe599"
2022-10-08T17:36:41.788  INFO --- [  Thread-309] l.s.a.lambda_executors     : Running lambda: arn:aws:lambda:us-east-1:000000000000:function:9a5ee5c1-6e0f-4d99-bc43-9893f11ca-ScheduledEventLogger-406fe599
2022-10-08T17:37:41.751  INFO --- [  Thread-323] l.s.a.lambda_executors     : Empty event body specified for invocation of Lambda "arn:aws:lambda:us-east-1:000000000000:function:9a5ee5c1-6e0f-4d99-bc43-9893f11ca-ScheduledEventLogger-406fe599"
2022-10-08T17:37:41.751  INFO --- [  Thread-323] l.s.a.lambda_executors     : Running lambda: arn:aws:lambda:us-east-1:000000000000:function:9a5ee5c1-6e0f-4d99-bc43-9893f11ca-ScheduledEventLogger-406fe599

どうなっているんでしょうね?
ちなみに、この事象はAWS SAMテンプレートから生成したプロジェクトをそのまま使っても起こりました…。

まあ、とりあえず動いているので良しとしましょう…。

まとめ

LocalStackで、Amazon EventBridgeを使ったAWS Lambda関数のスケジューリング起動を試してみました。

割とあっさり動いたようで、一部よくわからないところもありましたが…まあいいとしましょう。

動かすこと自体は、けっこうあっさりだったので。