LoginSignup
2
2

EventBridge Schedulerを用いてLambdaを定期実行するCloudFormationテンプレート

Last updated at Posted at 2023-12-23

はじめに

この記事は ZOZO Advent Calendar 2023 カレンダーVol.2の24日目の記事です。

Lambdaを定期実行を行いたい場合のCloudFormationのサンプルの紹介です。
EC2の定期起動・停止のサンプル1はあったのですが、Lambdaの定期実行のCloudFormationサンプルが意外となかったので紹介します。

EventBridge Scheduler vs Event Bridge Rule

AWSの何らかのサービスを定期実行する場合、以前ではよくEvent Bridge Ruleが使われていました。
しかし、2022年11月にEventBridgeからスケジュールに特化したEventBridge Schedulerがリリースされ、こちらの機能を用いてもスケジュール実行が可能になりました。

それぞれの違いについては下記の記事が分かりやすかったです。

今後はイベントドリブンなものは EventBridge Rule、スケジュールドリブンなものは EventBridge Scheduler という明確な棲み分けのもと、それぞれが独自に進化すると思います。

タイムゾーン指定できるのもありがたいですね。
今回はEventBridge Schedulerを用いたCloudFormationテンプレートのサンプルを紹介します。

CloudFormationサンプル

AWSTemplateFormatVersion: "2010-09-09"

Parameters:
  Environment:
    Type: String
    AllowedValues: ["dev", "prd"]

Resources:
  # --------------------------------------- #
  # Lambda
  # --------------------------------------- #
  SampleLambda:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Sub "${Environment}-sample-function"
      Code:
        ZipFile: |
          def lambda_handler():
            print("hello")
      Handler: main.lambda_handler
      Runtime: python3.10
      Role: !GetAtt SampleLambdaRole.Arn
      Architectures:
        - arm64
      Timeout: 60
      MemorySize: 128


  # --------------------------------------- #
  # EventBridge Scheduler
  # --------------------------------------- #
  SampleEventBridgeScheduler:
    Type: AWS::Scheduler::Schedule
    Properties:
      Name: !Sub "${Environment}-sample-event-bridge-scheduler"
      Description: "Sample EventBridge Scheduler"
      ScheduleExpression: "cron(0 13 ? * WED *)"
      ScheduleExpressionTimezone: "Asia/Tokyo"
      FlexibleTimeWindow:
        Mode: "OFF"
      Target:
        Arn: !GetAtt SampleLambda.Arn
        RoleArn: !GetAtt SampleEventBridgeSchedulerRole.Arn

  # --------------------------------------- #
  # IAM Role
  # --------------------------------------- #
  SampleEventBridgeSchedulerRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "${Environment}-sample-event-bridge-schedule-role"
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: scheduler.amazonaws.com
            Action: "sts:AssumeRole"
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaRole

  SampleLambdaRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "${Environment}-sample-lambda-role"
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: "sts:AssumeRole"
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaRole
        - arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess

上記のCloudFormationを適用すると、日本時間、毎週水曜13時にLambdaの関数を定期実行してくれます。

今回は、単純なLambdaの実行ですが、実行時にパラメータを渡したりできるので、下記の公式ドキュメントを一読するのお勧めします。

  1. https://dev.classmethod.jp/articles/cloudformation-template-eventbridge-scheduler-ec2-start-stop/

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2