LoginSignup
1
0

More than 3 years have passed since last update.

AWS SAMテンプレート内にStep FunctionsをCloudWatch Eventsで定期実行する定義を追加する

Posted at

はじめに

lambdaを定期的に実行する場合、samテンプレート内にCloudWatch Eventsの定義Eventsとして書けば簡単に定期実行させることができます。

ただ、同様の方法でStep Functionsを定期実行させる方法を調べるのに少し時間がかかったので、まとめておきます。

実行環境

  • macOS Catalina 10.15.7
  • aws-cli 1.18.185
  • sam-cli 1.12.0

やってみる

lambdaの定期実行

まずはじめに、lambdaの定期実行用のsamテンプレートは以下のようになります。

Resources:
  Function:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.6
      Events:
        HelloWorldFunctionRule:
          Type: Schedule
          Properties:
            # 平日朝10時
            Schedule: cron(0 1 ? * MON-FRI *)

Eventsのところに定義を追加しておけば、sam deploy時に上記lambdaを実行できるCloudWatch Eventsルールが作成され、lambdaが定期的に実行されます。

上記定義の場合は、平日の朝10時(JST)に実行されます。

簡単ですね!!

Step Functionsの定期実行

では、Step Functionsではどうなるでしょうか?

まず、samテンプレートにて以下のようにStep Functionsの定義を含めることが可能です。

Resources:
  HelloWorldMachine:
    Type: AWS::Serverless::StateMachine
    Properties:
      DefinitionUri: statemachine/hello-world.asl.json
      DefinitionSubstitutions:
        FunctionArn: arn:aws:lambda:ap-northeast-1:xxxxxxxxxxxx:function:hello-world-lambda-Function
      Role: arn:aws:iam::ap-northeast-1:xxxxxxxxxxxx:role/hello-world-role

しかし、lambdaと同様にEventsを追加してみてもうまくいきません。

そこで色々と調べたところ、Step Functionsの場合は別リソースとしてCloudWatch Eventsを定義するしか無いようです。

3 Ways to Schedule AWS Lambda and Step Functions State Machine Executions (※Defining Scheduled CloudWatch Eventの章)

というわけで、samテンプレートにCloudWatch Eventsの定義を追加しましょう。

Resources:
  HelloWorldMachine:
  .
  .
  .
  HelloWorldRule:
    Type: "AWS::Events::Rule"
    Properties:
      # 平日朝10時
      ScheduleExpression: 'cron(0 1 ? * MON-FRI *)'
      State: "ENABLED"
      Targets:
        -
          Arn: !Ref HelloWorldMachine
          Id: !GetAtt HelloWorldMachine.Name
          RoleArn: arn:aws:iam::ap-northeast-1:xxxxxxxxxxxx:role/hello-world-rule-role

※別リソースになるので、上記Step Functionを実行できるようにするためのrole(hello-world-rule-role)を作成・アタッチしておく必要あります。(または上で紹介した記事のようにsamテンプレート内でroleの定義も追加しましょう。)

これで、samデプロイ時にStep Functionsを定期実行してくれるClouWatch Eventsも同時に作成してくれます!

最後に

ということで、AWS SAM内にStep Functionsを定期実行するCloudWatch Eventsルールを追加することができました!
こうすることで、samテンプレート内に関係するリソースをまとめておけるのが、嬉しいですね

それでは本記事は以上です。
どなたかの参考になれば幸いです!

1
0
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
1
0