タケユー・ウェブ日報

Ruby on Rails や Flutter といったWeb・モバイルアプリ技術を武器にお客様のビジネス立ち上げを支援する、タケユー・ウェブ株式会社の技術ブログです。

CloudFormation で CloudWatch Events + Lambda による定期実行タスクを作成する

AWSで定期的な処理を行いたいときは、CloudWatch Events を使い、 Lambda ファンクションの実行をスケジューリングすることで行います。

docs.aws.amazon.com

設定画面

f:id:uzuki05:20200501172633p:plain
CloudWatch Events のルール

f:id:uzuki05:20200501172808p:plain
Lambdaファンクションの実行権限設定

CloudFormation テンプレート

f:id:uzuki05:20200501163233p:plain

Parameters:
  ScheduleExpression:
    Type: String
  Enabled:
    Type: String
    Default: "false"
    AllowedValues:
      - "true"
      - "false"
Conditions:
  isEnabled: !Equals [!Ref Enabled, "true"]
Resources:
  # 実行したい Lambda Function
  Function:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: |+
          exports.handler = (event, context, callback) => {
            console.log('LogScheduledEvent');
            console.log('Received event:', JSON.stringify(event, null, 2));
            callback(null, 'Finished');
          };
      Handler: index.handler
      Role: !GetAtt LambdaExecutionRole.Arn
      Runtime: "nodejs10.x"
      MemorySize: 128
      Timeout: 60

  # ScheduleExpression で指定したスケジュールで、 Function を実行する
  Rule:
    Type: AWS::Events::Rule
    Properties:
      ScheduleExpression: !Ref ScheduleExpression
      State: !If [isEnabled, "ENABLED", "DISABLED"]
      Targets:
        - Id: Lambda
          Arn: !GetAtt Function.Arn

  # スケジュールイベントからのLambda実行を許可
  LambdaPermission:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:InvokeFunction
      FunctionName: !Ref Function
      Principal: events.amazonaws.com
      SourceArn: !GetAtt Rule.Arn
  
  # Lambda の実行ロール
  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - "sts:AssumeRole"
      Path: /
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"