如何使用 Terraform 将资源动态附加到内联策略?

How to dynamically attach a resource to an inline policy using Terraform?

我正在创建内联策略,我想动态附加资源。

这是我的政策:

resource "aws_iam_policy" "lambda_secret_policy" {
  name = "${var.name}-lambda-role"
  description = "grants lambda access to secret manager"
  
  assume_role_policy = <<EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "secretsmanager:GetSecretValue",
            ],
            "Resource": [
                <where I would like to dynamically assign the exampleSecretResource resource>
            ]
        }
    ]
}
EOF
}

这是我要动态附加的资源:

data "aws_secretsmanager_secret" "exampleSecretResource" {
  arn = var.secretArn
}

因此,我使用 data 块获取了 exampleSecretResource,并希望将其附加到上述策略中的资源列表中。这可能是内联的还是我需要使用资源块显式构建策略?

如果我可以内联动态附加,我该怎么做? (我在这里使用的术语正确吗?)

如果我没理解错的话,下面应该是你想要的:

data "aws_secretsmanager_secret" "exampleSecretResource" {
  arn = var.secretArn
}

resource "aws_iam_policy" "lambda_secret_policy" {
  name = "${var.name}-lambda-role"
  description = "grants lambda access to secret manager"
  
  assume_role_policy = <<EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "secretsmanager:GetSecretValue",
            ],
            "Resource": [ 
              "${data.aws_secretsmanager_secret.exampleSecretResource.arn}"
            ]
        }
    ]
}
EOF
}

显然,aws_iam_policy.lambda_secret_policy 必须附加到实际的 lambda 执行角色。我假设您在代码的未显示部分执行此操作。