如何使用Terraform定义cloundwatch事件规则来触发StepFunction状态机

waw*_*awa 5 state-machine amazon-web-services terraform aws-step-functions amazon-cloudwatch-events

我已经在 Terraform 中定义了 StepFunction 状态机的创建,现在我想设置一个计时器来每天触发状态机,我认为使用 cloudwatch 事件规则可能是一个不错的选择,我知道如何设置事件规则来触发 Lambda :

resource "aws_cloudwatch_event_rule" "lambda_event_rule" {
  name                = xxx
  schedule_expression = xxx
  description         = xxx
}

resource "aws_cloudwatch_event_target" "lambda_event_target" {
  target_id = xxx
  rule      = aws_cloudwatch_event_rule.lambda_event_rule.name
  arn       = xxx
}

#I must setup the right permissions using 'aws_lambda_permission' 
#see: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_event_target

resource "aws_lambda_permission" "lambda_event_permission" {
  statement_id  = xxx
  action        = "lambda:InvokeFunction"
  function_name = xxx
  principal     = "events.amazonaws.com"
  source_arn    = aws_cloudwatch_event_rule.lambda_event_rule.name
}
Run Code Online (Sandbox Code Playgroud)

但如何设置触发状态机的权限部分?我找不到任何关于它的例子,我错过了什么吗?是因为我们不需要状态机的权限配置吗?有人可以帮忙吗?

以下是到目前为止我使用 cloudwatch 事件规则触发状态机的内容:

resource "aws_cloudwatch_event_rule" "step_function_event_rule" {
  name                = xxx
  schedule_expression = xxx
  description         = xxx
}

resource "aws_cloudwatch_event_target" "step_function_event_target" {
  target_id = xxx
  rule      = aws_cloudwatch_event_rule.step_function_event_rule.name
  arn       = xxx
}


?????What else should I add here?

Run Code Online (Sandbox Code Playgroud)

PS:我发现有人在这里问类似的问题,但还没有答案。

blr*_*blr 3

我不太熟悉 terraform,但它似乎遵循与官方文档类似的模式。对于目标;https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_PutTargets.html >> 请参阅“添加 Step Functions 状态机作为目标”部分

{
    "Rule": "testrule", 
    "Targets": [
           {
        "RoleArn": "arn:aws:iam::123456789012:role/MyRoleToAccessStepFunctions"
        "Arn":"arn:aws:states:us-east-1:123456789012:stateMachine:HelloWorld"
      }
    ]
}
Run Code Online (Sandbox Code Playgroud)

这告诉我您需要传递角色和 arn。因此,以您的示例为例,这就是您可能需要填写的内容

resource "aws_cloudwatch_event_rule" "step_function_event_rule" {
  name                = <something unique>
  schedule_expression = <syntax described in https://docs.aws.amazon.com/eventbridge/latest/userguide/scheduled-events.html>
  description         = <something descriptive>
}

resource "aws_cloudwatch_event_target" "step_function_event_target" {
  target_id = <something unique>
  rule      = aws_cloudwatch_event_rule.step_function_event_rule.name
  arn       = <step function arn>
  role_arn  = <role that allows eventbridge to start execution on your behalf>
}
Run Code Online (Sandbox Code Playgroud)