2

I'm using Terraform to deploy a lambda that needs to keep secrets in the AWS SecretsManager.

I have the following abbreviated lambda:

Lambda


resource "aws_lambda_function" "thisThing" {
  function_name = "functionName"
  runtime = "python3.8"
  handler = "thisThing.handler"

  role = aws_iam_role.lambda_exec.arn
}

resource "aws_iam_role" "lambda_exec" {
  name = "serverless_lambda"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action = "sts:AssumeRole"
      Effect = "Allow"
      Sid    = ""
      Principal = {
        Service = "lambda.amazonaws.com"
      }
      }
    ]
  })
}

resource "aws_iam_role_policy_attachment" "lambda_policy" {
  role       = aws_iam_role.lambda_exec.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}

Here are the secrets

Secrets

# Secrets

resource "aws_secretsmanager_secret" "SECRET" {
  name = "SECRET"
  recovery_window_in_days = 0
}

resource "aws_secretsmanager_secret_version" "SECRET" {
  secret_id     = "${aws_secretsmanager_secret.SECRET.id}"
  secret_string = "${var.SECRET}"
}

The error I'm getting is:

[ERROR] ClientError: An error occurred (AccessDeniedException) when calling the GetSecretValue operation: User: arn:aws:sts::439791110569:assumed-role/serverless_lambda/thisThing is not authorized to perform: secretsmanager:GetSecretValue on resource: SECRET because no identity-based policy allows the secretsmanager:GetSecretValue action

This is my first time using secrets manager, and I'm not very experienced in AWS, but I think based on the answer here, that I need to add a policy that allows my lambda exec role to have GetSecretValue rights. I've made a few attempts, but my lack of knowledge on how to look up the different policy ARN's is shutting me down.

Here's what I've tried adding (it's wrong, and I know it's wrong.)

resource "aws_iam_role_policy_attachment" "lambda_secretsmanager_role" {
  role = aws_iam_role.lambda_exec.name
  # ? policy_arn = "arn:aws:iam::aws:policy/SecretsManagerGetSecretValue"
}

That's not the correct ARN, but I'm not sure where to look to find the correct ARN.

Marcin
  • 215,873
  • 14
  • 235
  • 294
trueCamelType
  • 2,198
  • 5
  • 39
  • 76

1 Answers1

4

You can add the permission using aws_iam_role_policy:

resource "aws_iam_role_policy" "sm_policy" {
  name = "sm_access_permissions"
  role = aws_iam_role.lambda_exec.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = [
          "secretsmanager:GetSecretValue",
        ]
        Effect   = "Allow"
        Resource = "*"
      },
    ]
  })
}

If you want to follow least privileged permissions, then you can change Resource = "*" into Resource = "<arn-of-the-secret>".

Marcin
  • 215,873
  • 14
  • 235
  • 294