Search code examples
amazon-web-servicesaws-lambdaamazon-cloudwatchaws-sdk-js

CloudWatch Events scheduled from Lambda function


I've tried to setup scheduling with Amazon CloudWatch Events, which should invoke a Lambda function, from another Lambda I used guide from Sending Events to Amazon CloudWatch Events - AWS SDK for JavaScript.

The problem is, that even after setting CloudWatch Events IAM role

{
                    Sid: 'CloudWatchEventsFullAccess',
                    Effect: 'Allow',
                    Action: ['*'],
                    Resource: '*',
},

and Lambda role to similar one, when I invoke main function

const cloudWatchEvents = new CloudWatchEvents()

        const ruleParams = {
            Name: projectId,
            ScheduleExpression: crontab,
            State: 'ENABLED',
            RoleArn: apiCloudWatchEventsIamRole,
        }

        const targetParams = {
            Rule: projectId,
            Targets: [
                {
                    Arn: apiLongTaskFunctionArn,
                    Id: 'lambdaCloudWatch',
                },
            ],
        }


        cloudWatchEvents.putRule(ruleParams, (err, rule) => {
            if (err) {
                console.log(err)
                return err
            }
            cloudWatchEvents.putTargets(targetParams, (err, data) => {
                if (err) {
                    console.log(err)
                    return (err)
                }
                const eventParams = {
                    Entries: [
                        {
                            DetailType: 'Scheduled Event',
                            Source: 'aws.events',
                            Resources: [rule.RuleArn],
                            Detail: '{}',
                        },
                    ],
                }
                cloudWatchEvents.putEvents(eventParams, (err, data) => {
                    if (err) {
                        console.log(err)
                        return (err)
                    }
                    console.log(data)
                })
            })
        })

i get response from last console.log

{ FailedEntryCount: 1,
      Entries: 
       [ { ErrorCode: 'NotAuthorizedForSourceException',
           ErrorMessage: 'Not authorized for the source.' } ] }

I'm not sure where should I search for answer, as I haven't seen this case documented anywhere on web.


Solution

  • okay, so adding to ruleParams

                EventPattern: JSON.stringify({
                    source: ['sourceName'],
                }),
    

    and setting Entries to

                        Entries: [
                            {
                                DetailType: 'Scheduled Event',
                                Source: 'sourceName',
                                Resources: [rule.RuleArn],
                                Detail: '{}',
                            },
                        ],
    

    solved the issue