LoginSignup
0
1

【AWS】CloudFormationでスケジュール起動するLambda関数を作る

Posted at

目的

コンソール画面から設定もできますが、今回はCloudFormationでスケジュール起動するLambda関数を作ることです。

EventBridge

まずはEventBridgeです。
今回はAWS::Events::Ruleを使います。テンプレートは下記です。

{
  "Type" : "AWS::Events::Rule",
  "Properties" : {
      "Description" : String,
      "EventBusName" : String,
      "EventPattern" : Json,
      "Name" : String,
      "RoleArn" : String,
      "ScheduleExpression" : String,
      "State" : String,
      "Targets" : [ Target, ... ]
    }
}

ScheduleExpressionは下記ページをご参照ください。

トリガー

次は作ったEventをLambdaのトリガーにします。

テンプレートは下記です。

{
  "Type" : "AWS::Lambda::Permission",
  "Properties" : {
      "Action" : String,
      "EventSourceToken" : String,
      "FunctionName" : String,
      "FunctionUrlAuthType" : String,
      "Principal" : String,
      "PrincipalOrgID" : String,
      "SourceAccount" : String,
      "SourceArn" : String
    }
}
  • Action
    Actionlambda:InvokeFunctionにすることで、スケジューラでLambdaを呼び出します。
  • FunctionName
    呼び出し対象のLambda Function名
  • Principal
    関数を呼び出す AWS サービスまたは AWS アカウント。サービスを指定する場合は、SourceArnまたはを使用してSourceAccount、そのサービスを通じて関数を呼び出せるユーザーを制限します。
  • SourceArn
    関数を呼び出す AWS リソースの ARN。ここではEventBridgeスケジュールをさします。

サンプル

完成したcloudformationサンプルは下記です。

{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "{\"createdOn\":\"Windows\",\"createdBy\":\"Amplify\",\"createdWith\":\"7.6.23\",\"stackType\":\"function-Lambda\",\"metadata\":{}}",
  "Parameters": {},
  "LambdaFunction": {},
  "Resources": {
    "TestEventsRule": {
      "Type": "AWS::Events::Rule",
      "Properties": {
        "Name": "Test",
        "ScheduleExpression": "cron(0 18 ? * MON-SAT *)",
        "State": "ENABLED",
        "Targets": [
          {
              "Ref": "LambdaFunction"
          }
        ],
        "EventBusName": "default"
      }
    },
    "LambdaPermission": {
      "Type": "AWS::Lambda::Permission",
      "Properties": {
        "Action": "lambda:InvokeFunction",
        "FunctionName": {
          "Ref": "LambdaFunction"
        },
        "Principal": "events.amazonaws.com",
        "SourceArn": {
          "Fn::GetAtt": [
            "TestEventsRule",
            "Arn"
          ]
        }
      }
    }
  }
}
0
1
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
0
1