Why is the CloudWatch Events rule that I created using CloudFormation templates or the AWS CLI unable to invoke AWS Lambda?

2 minute read
0

I created an Amazon CloudWatch Events (CloudWatch Events) rule using AWS CloudFormation (CloudFormation) templates or the AWS Command Line Interface (AWS CLI). I tried to invoke an AWS Lambda target, but the target didn't invoke.

Short description

CloudWatch Events rule created using CloudFormation templates or the AWS CLI must explicitly grant CloudWatch Events rule permissions to invoke the Lambda target.

Resolution

You can add the CloudWatch Events rule permissions required to invoke your Lambda target in either the CloudFormation template or the AWS CLI.

Note: If you receive errors when running AWS CLI commands, make sure that you’re using the most recent version of the AWS CLI.

Option 1: Add permissions in the CloudFormation template

Use the AWS::Lambda::Permission resource to add a policy statement to your Lambda function's access policy.

Important: In the CloudFormation template, be sure to:

  • Replace MyLambdaFunction with the logical name of the Lambda function.
  • Replace MyEventRule with the logical name of the event rule.

JSON

"LambdaInvokePermission":
{
  "Type": "AWS::Lambda::Permission",
  "Properties": {
    "FunctionName": {
      "Fn::GetAtt": [
        "MyLambdaFunction",
        "Arn"
      ]
    },
    "Action": "lambda:InvokeFunction",
    "Principal": "events.amazonaws.com",
    "SourceArn": {
      "Fn::GetAtt": [
        "EventRule",
        "Arn"
      ]
    }
  }
}

YAML

LambdaInvokePermission:
  Type: AWS::Lambda::Permission
  Properties:
    FunctionName:
      Fn::GetAtt:
        - MyLambdaFunction
        - Arn
    Action: "lambda:InvokeFunction"
    Principal: "events.amazonaws.com"
    SourceArn:
      Fn::GetAtt:
        - "EventRule"
        - "Arn"

Option 2: Add permissions using the AWS CLI

At a command prompt, enter the following command.

aws lambda add-permission
--statement-id "TrustCloudWatchToInvokeMyLambdaFunction" \
--action "lambda:InvokeFunction" \
--principal "events.amazonaws.com" \
--function-name "arn:aws:lambda:<region>:<account-id>:function:<function-name>"
\
--source-arn "arn:aws:events:<region>:<account-id>:rule/<rule-name>"

Related information

Using AWS Lambda with AWS CloudFormation

AWS OFFICIAL
AWS OFFICIALUpdated a year ago