Two AWS Lambda functions with two IAM Roles

Viewed 409

I have two AWS Lambda functions. One should have access to Lambda policy and the other should have access to Lambda policy and SQS.

I'm trying to create the IAM roles so by default they have access to the Lambda policy and then for the second IA Role I try to attach the SQS policy.

I'm using the following HCL:

resource "aws_sqs_queue" "sqs" {
  name = "lambda-feeding-queue"
}

resource "aws_lambda_event_source_mapping" "sqs" {
  event_source_arn = aws_sqs_queue.sqs.arn
  function_name = aws_lambda_function.example.arn
  enabled = true
  batch_size = 1
}

resource "aws_lambda_function" "example" {
  function_name = "ServerlessExampleBook"

  s3_bucket = "lambda"
  s3_key = "mn/v1.0.0/lambda-1.0.0-all.jar"

  handler = "dk.fitfit.handler.BookRequestHandler"
  runtime = "java8"

  memory_size = 256

  role = aws_iam_role.example.arn
}

resource "aws_lambda_function" "event" {
  function_name = "ServerlessExampleEvent"

  s3_bucket = "lambda"
  s3_key = "mn/v1.0.0/lambda-1.0.0-all.jar"

  handler = "dk.fitfit.handler.EventRequestHandler"
  runtime = "java8"

  memory_size = 256

  role = aws_iam_role.event.arn
}

resource "aws_iam_role" "example" {
  name = "serverless_example_lambda"
  assume_role_policy = data.aws_iam_policy_document.lambda.json
}

data "aws_iam_policy_document" "lambda" {
  statement {
    effect = "Allow"

    actions = [
      "sts:AssumeRole",
    ]

    principals {
      identifiers = [
        "lambda.amazonaws.com"]
      type = "Service"
    }
  }
}

resource "aws_iam_role" "event" {
  name = "serverless_example_lambda_event"
  assume_role_policy = data.aws_iam_policy_document.lambda.json
}

resource "aws_iam_role_policy_attachment" "sqs" {
  role = aws_iam_role.event.name
  policy_arn = aws_iam_policy.sqs.arn
}

resource "aws_iam_policy" "sqs" {
  policy = data.aws_iam_policy_document.sqs.json
}

data "aws_iam_policy_document" "sqs" {
  statement {
    effect = "Allow"
    resources = [aws_sqs_queue.sqs.arn]

    actions = [
      "sqs:ReceiveMessage",
      "sqs:DeleteMessage",
      "sqs:GetQueueAttributes",
    ]
  }
}

But it doesn't like the SQS policy is picked up because I'm getting the following error:

Error: Error creating Lambda event source mapping: InvalidParameterValueException: The provided execution role does not have permissions to call ReceiveMessage on SQS { RespMetadata: { StatusCode: 400, RequestID: "4971c72f-a2f3-40c2-9d55-fd892b27586b" }, Message_: "The provided execution role does not have permissions to call ReceiveMessage on SQS", Type: "User" }

1 Answers

Based on the comments.

The issue was due to mistake in aws_lambda_event_source_mapping. Instead of

function_name = aws_lambda_function.example.arn

it should be

function_name = aws_lambda_function.event.arn
Related