shiv455
shiv455

Reputation: 7784

add CloudwatchEvent dynamically in AWS Lambda code

I have a Lambda function triggered by S3 file Put event.Now once the lambda is triggered i want to attach cloudwatch event(cron) to the same lambda in the code.Is it possible?

Upvotes: 0

Views: 1001

Answers (2)

abiydv
abiydv

Reputation: 621

You need to do 2 things to accomplish this

  1. Add a target(lambda) in the cloudwatch rule (cron)
  2. Add permission in lambda to allow the rule to invoke the lambda

I don't have an exact code sample to give you, but the below snippets will have to be included in your function to achieve this -

import boto3

event_client = boto3.client('events')
event_response = event_client.put_targets(
    Rule=RULENAME,
    Targets=[{
            'Id': 'A_UNIQUE_STRING',
            'Arn': 'ARN_LAMBDA'
        }]
)

lambda_client = boto3.client('lambda')
lambda_response = lambda_client.add_permission(
    FunctionName="LAMBDA_NAME",
    StatementId="A_UNIQUE_STRING",
    Action="lambda:InvokeFunction",
    Principal="events.amazonaws.com",
    SourceArn="ARN_RULE"
)

ARN_LAMBDA should be something like - arn:aws:lambda:<aws-region>:<aws-account-number>:function:<lambda-name>

ARN_RULE should be something like - arn:aws:events:<aws-region>:<aws-account-number>:rule/<rule-name>

A_UNIQUE_STRING - you can generate something in your code which is meaningful and unique or just a random string.

You can refer the guides in the boto3 documentation of lambda and cloudwatch events for more details - http://boto3.readthedocs.io/en/latest/reference/services/lambda.html#Lambda.Client.add_permission http://boto3.readthedocs.io/en/latest/reference/services/events.html#CloudWatchEvents.Client.put_targets

Upvotes: 1

Ashan
Ashan

Reputation: 19705

This should be possible for non-streaming triggers but you need to handle the two different event types in code.

On the other hand it would be better to use two seperate Lambdas since you will be only paying for the usage.

Upvotes: 0

Related Questions