Search code examples
amazon-web-servicesaws-lambdaterraformterraform-provider-aws

AWS Terraform EventBridge schedule policy


I am trying to deploy an AWS EventBridge schedule and attach all relevant policies for it with the following terraform configuration.

upd: Solution:

resource "aws_iam_role" "eventbridge_role" {
  name = "EventBridgeRoleForStepFunctions"

  assume_role_policy = jsonencode({
    "Version" = "2012-10-17",
    "Statement" = [
      {
        "Effect"    = "Allow",
        "Principal" = {
          "Service" = "scheduler.amazonaws.com"
        },
        "Action"    = "sts:AssumeRole"
      }
    ]
  })
}

resource "aws_iam_policy" "eventbridge_invoke_stepfunctions_policy" {
  name        = "EventBridgeInvokeStepFunctionsPolicy"
  path        = "/"
  description = "Allow EventBridge to invoke Step Functions"

  policy = jsonencode({
    Version = "2012-10-17",
    Statement = [
      {
        Effect   = "Allow",
        Action   = "states:StartExecution",
        Resource = aws_sfn_state_machine.MySandboxStateMachine.arn
      }
    ]
  })
}

resource "aws_iam_policy_attachment" "eventbridge_role_policy_attachment" {
  name = "StepFunctionPolicyAttachment"
  policy_arn = aws_iam_policy.eventbridge_invoke_stepfunctions_policy.arn
  roles = [aws_iam_role.eventbridge_role.name]
}

resource "aws_scheduler_schedule" "every_five_minutes" {
  name       = "every-five-minutes"
  group_name = "default"

  flexible_time_window {
    mode = "OFF"
  }

  schedule_expression = "cron(0/5 * * * ? *)"

  target {
    arn      = aws_sfn_state_machine.MySandboxStateMachine.arn
    role_arn = aws_iam_role.eventbridge_role.arn
  }
}
Creating Amazon EventBridge Scheduler Schedule (every-five-minutes): operation error Scheduler: CreateSchedule, https response error StatusCode: 400, RequestID: a3a7f4fa-b96e-4107-a041-2cd339e266c7, ValidationException: The execution role you provide must allow AWS EventBridge Scheduler to assume the role.

What would be the fix for properly attaching the policy, since I bet I am following Terraform's AWS guidelines.


Solution

  • You need to use the correct service name in the assume role policy. In this case, it is (docs):

    "scheduler.amazonaws.com"
    

    So, you need to change the code to the following:

    resource "aws_iam_role" "eventbridge_role" {
      name = "EventBridgeRoleForStepFunctions"
    
      assume_role_policy = jsonencode({
        "Version" = "2012-10-17",
        "Statement" = [
          {
            "Effect"    = "Allow",
            "Principal" = {
              "Service" = "scheduler.amazonaws.com"
            },
            "Action"    = "sts:AssumeRole"
          }
        ]
      })
    }