目的
コンソール画面から設定もできますが、今回は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
Action
をlambda: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"
]
}
}
}
}
}