1
votes

Question

How to attach the assumable role with the lambda invocations to an API Gateway API or all methods?

Create an API Gateway API for AWS Lambda Functions tells to attach an IAM policy to invoke Lambda:

This means that, at minimum, you must attach the following IAM policy to an IAM role for API Gateway to assume the policy.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "lambda:InvokeFunction",
            "Resource": "*"
        }
    ]
}      

An API Gateway assumable role is an IAM role with the following trusted relationship:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "apigateway.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}       

Research

It looks lambda_permission can attach per method basis but not sure if there is a way to be able to invoke any method "*".

Update

Api Gateway can't invoke Lambda function tells a way to attach from UI per method/function.

enter image description here


enter image description here

2

2 Answers

0
votes

As in Specify Lambda permissions for API Gateway REST API, set source_arn to the execution_arn of the API should do.

resource "aws_lambda_permission" "apigw" {
  statement_id  = "AllowAPIGatewayInvoke"
  action        = "lambda:InvokeFunction"
  function_name = "${aws_lambda_function.example.arn}"
  principal     = "apigateway.amazonaws.com"

  #--------------------------------------------------------------------------------
  # Per deployment
  #--------------------------------------------------------------------------------
  # The /*/*  grants access from any method on any resource within the deployment.
  # source_arn = "${aws_api_gateway_deployment.test.execution_arn}/*/*"

  #--------------------------------------------------------------------------------
  # Per API
  #--------------------------------------------------------------------------------
  # The /*/*/* part allows invocation from any stage, method and resource path
  # within API Gateway REST API.
  source_arn    = "${aws_api_gateway_rest_api.example.execution_arn}/*/*/*"
}
0
votes
resource "aws_api_gateway_rest_api" "api_gw" {
      name = "your-api-gw-name"
      description = "your api gateway description"
}

data "aws_caller_identity" "current" {}

resource "aws_lambda_permission" "lambda_permission" {
  statement_id  = "AllowExecutionFromAPIGateway"
  action        = "lambda:InvokeFunction"

  #your lambda function ARN
  function_name = "arn:aws:lambda:${var.aws_region}:${data.aws_caller_identity.current.account_id}:function:lambda-function-name"   
  principal     = "apigateway.amazonaws.com"
  source_arn = "arn:aws:execute-api:${var.aws_region}:${data.aws_caller_identity.current.account_id}:${aws_api_gateway_rest_api.api_gw.id}/*/POST/"
}

note:- declare aws_region variable in your variable.tf file with your region value.