允许 lambda 权限访问 secretsmanager 值

Allow lambda permission to access secretsmanager value

我正在使用 Terraform 部署需要在 AWS SecretsManager 中保密的 lambda。

我有以下缩写的 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"
}

这里有秘密

秘密

# 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}"
}

我得到的错误是:

[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

这是我第一次使用secrets manager,我在AWS方面的经验不是很丰富,但我认为基于答案, that I need to add a policy that allows my lambda exec role to have GetSecretValue权利。我已经尝试了几次,但我对如何查找不同的策略 ARN 缺乏了解,这让我失望了。

这是我尝试添加的内容(这是错误的,我知道这是错误的。)

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

这不是正确的 ARN,但我不确定在哪里可以找到正确的 ARN。

您可以使用 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 = "*"
      },
    ]
  })
}

如果你想遵循最低权限,那么你可以把Resource = "*"改成Resource = "<arn-of-the-secret>"