Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I grant permission to API Gateway to invoke lambda functions through CloudFormation?

Tags:

I've been all over the web searching for an answer to this.

Essentially, we're spinning up an API using Swagger, which is awesome and works great, but one thing doesn't work... When we make a call to an Endpoint, we get a 500 error (it's not a 500 error that we're providing either it's one from AWS). The error states "Execution failed due to configuration error: Invalid permissions on Lambda function" (https://youtu.be/H4LM_jw5zzs <- This is a video, from another user, of the error I'm getting).

I've gone down many ratholes, and have found an answer... It involves using the AWS CLI and looks a bit like this:

aws lambda add-permission \ --function-name FUNCTION_NAME \ --statement-id STATEMENT_ID \ --action lambda:InvokeFunction \ --principal apigateway.amazonaws.com \ --source-arn "arn:aws:execute-api:us-east-1:ACCOUNT_ID:API_ID/*/METHOD/ENDPOINT" 

This is great and all, but we are using CloudFormation to spin up everything and we want this to be automated. Is there an easier way to go about this? Is there something in CloudFormation that will give us the resource policy that we need?

I'm hitting a bit of a wall with this, but I've been working on it for a few hours today and it's a bit of a blocker for our API release, so any help would be much appreciated. :)

like image 249
Sam Bantner Avatar asked Oct 06 '16 20:10

Sam Bantner


People also ask

Can API gateway trigger Lambda?

In this blog, we'll write an AWS lambda function which will be triggered by Amazon API Gateway. According to API gateway documentation, AWS API gateway is a fully managed service that makes it easy for developers to create, publish, maintain, monitor and secure APIs.

Does API gateway pass authorization header to Lambda?

For a Lambda authorizer of the REQUEST type, API Gateway passes request parameters to the authorizer Lambda function as part of the event object. The request parameters include headers, path parameters, query string parameters, stage variables, and some of request context variables.


1 Answers

There is a CloudFormation solution to this problem. See the following CloudFormation snippet:

"Permission": {     "Type": "AWS::Lambda::Permission",     "Properties": {         "FunctionName": { "Fn::GetAtt": [ "Lambda", "Arn" ] },         "Action": "lambda:InvokeFunction",         "Principal": "apigateway.amazonaws.com",         "SourceArn": { "Fn::Join": [ "", [             "arn:aws:execute-api:",             { "Ref": "AWS::Region" }, ":",             { "Ref": "AWS::AccountId" }, ":",             { "Ref": "API" },             "/*/*/*"         ] ] }     } } 

This grants API Gateway permissions to launch your Lambda function. Variables in this snippet you need to change are Lambda (line 4) and API (line 11).

like image 170
adamkonrad Avatar answered Oct 16 '22 12:10

adamkonrad