Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add trigger to an AWS Lambda function using AWS CLI?

Any way of doing this using AWS CLI? Adding trigger using AWS Management Console

like image 286
Stein-Tore Erdal Avatar asked Aug 28 '16 10:08

Stein-Tore Erdal


2 Answers

I was able to add SNS trigger for lambda using below AWS CLI

aws lambda add-permission \
  --function-name {{LAMBDA-FUNCTION-NAME}} \
  --statement-id {{UNIQUE-ID}} \
  --action "lambda:InvokeFunction" \
  --principal sns.amazonaws.com \
  --source-arn arn:aws:sns:us-east-1:77889900:{{SNS-TOPIC-ARN}}

The SNS topic can also be from other region.
Hope this helps.

like image 84
user1292364 Avatar answered Oct 07 '22 15:10

user1292364


As @user1292364 mentioned we need to use add-permission to the lambda.

Only issue with it is that you need to make sure that lambda to sns subscription is added also. Otherwise this error will occur

A subscription for arn:aws:lambda:eu-west-1:276xxxxxx:function:HourlyLambdaFunction on the topic HourlyLambdaFunction could not be found.

I would prefer to use it over AWS CLI in this way:

#!/usr/bin/env bash

# Add Lambda to SNS as subscription
aws sns subscribe \
    --topic-arn arn:aws:sns:eu-west-1:276xxxxxx:HourlyLambdaFunction \
    --protocol lambda \
    --notification-endpoint arn:aws:lambda:eu-west-1:276xxxxxx:function:HourlyLambdaFunction

# Give permissions to Lambda to access that subscription i.e. Add it through triggers
aws lambda add-permission \
    --function-name HourlyLambdaFunction \
    --statement-id 276xxxxxx\
    --action "lambda:InvokeFunction" \
    --principal sns.amazonaws.com \
    --source-arn arn:aws:sns:eu-west-1:276xxxxxx:HourlyLambdaFunction

# Send message to publish and trigger lamda
aws sns publish \
    --topic-arn arn:aws:sns:eu-west-1:276xxxxxx:HourlyLambdaFunction \
    --subject "HourlyLambdaFunction" \
    --message "{datawarehouse:banana_wh, database:banana_db, schema:banana. query:'select count(*) from banana.banana_loads;'}"

ps: \ in the code is new line for bash script (if anyone wonders)

Logs of the lambda function can be found on Cloudwatch

like image 29
Gunay Anach Avatar answered Oct 07 '22 15:10

Gunay Anach