我可以在 CloudFormation 模板中创建 CloudWatch 计划事件吗?

Can I create a CloudWatch scheduled event in CloudFormation template?

我知道我可以通过 AWS 控制台创建计划的 Cloud Watch 事件:

https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/Create-CloudWatch-Events-Scheduled-Rule.html

有没有办法在 Cloud Formation 模板中声明类似的事件?

是的,这是可能的。

AWS::Events::Rule 资源创建一个规则,匹配传入的 Amazon CloudWatch Events (CloudWatch Events) 事件并将它们路由到一个或多个目标进行处理。

这是示例 CloudFormation 代码段:

Type: AWS::Events::Rule
Properties: 
  Description: String
  EventPattern: JSON object
  Name: String
  ScheduleExpression: String
  State: String
  Targets:
    - Target

这里是 official documentation,如果您有更多问题。

是的,@bhalothia 的分享是可能的。请找到一篇能让您深入了解它的文章。

实际实施:

http://marcelog.github.io/articles/serverless_cloudwatch_event_cloudformation_template.html

详细文档:

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html

希望对您有所帮助。

下面是在cloudwatch中创建一个计划事件的例子,它创建了一个规则,每10分钟调用一次指定的Lambda函数。 PermissionForEventsToInvokeLambda 资源授予 EventBridge 调用关联函数的权限。

"ScheduledRule": {
  "Type": "AWS::Events::Rule",
  "Properties": {
    "Description": "ScheduledRule",
    "ScheduleExpression": "rate(10 minutes)",
    "State": "ENABLED",
    "Targets": [{
      "Arn": { "Fn::GetAtt": ["LambdaFunction", "Arn"] },
      "Id": "TargetFunctionV1"
    }]
  }
},
"PermissionForEventsToInvokeLambda": {
  "Type": "AWS::Lambda::Permission",
  "Properties": {
    "FunctionName": { "Ref": "LambdaFunction" },
    "Action": "lambda:InvokeFunction",
    "Principal": "events.amazonaws.com",
    "SourceArn": { "Fn::GetAtt": ["ScheduledRule", "Arn"] }
  }
}

示例引用自AWS官方文档