How can I give cloudwatch log permission to invoke a lambda?

Viewed 3485

I am using this command to stream log to a lambda function.

aws logs put-subscription-filter --log-group-name $LOG_GROUP_NAME --filter-name $LAMBDA_NAME --filter-pattern '' --destination-arn $LAMBDA_ARN

but got this error:

An error occurred (InvalidParameterException) when calling the PutSubscriptionFilter operation: Could not execute the lambda function. Make sure you have given CloudWatch Logs permission to execute your function.

It seems the log doesn't have permission to invoke my lambda. How can I give the permission? There will be hundreds of log group in my account. I don't want to give permission to each log group one by one. Is there a solution to allow any log to invoke the lambda function?

2 Answers

The AWS docs provide AWS CLI example of how to do it. You would have to adjust the example to your setup:

aws lambda add-permission \
    --function-name "helloworld" \
    --statement-id "helloworld" \
    --principal "logs.region.amazonaws.com" \
    --action "lambda:InvokeFunction" \
    --source-arn "arn:aws:logs:region:123456789123:log-group:TestLambda:*" \
    --source-account "123456789012"

Cloudformation script

LogGroupInvokeLambdaPermission:
  Type: AWS::Lambda::Permission
  Properties:
    FunctionName: !GetAtt YourLambda.Arn
    Action: lambda:InvokeFunction
    Principal: logs.amazonaws.com
    SourceAccount: !Ref 'AWS::AccountId'
    SourceArn: !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${LambdaThatWritesLogs}:*'
Related