Matt W
Matt W

Reputation: 12434

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

I am creating an inline policy and I want to dynamically attach a resource.

Here is my policy:

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
}

And here is the resource I'd like to dynamically attach:

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

So, I have acquired the exampleSecretResource using a data block and would like to attach it to the list of resources in the above policy. Is that possible inline or do I need to build the policy explicitly using resource blocks?

If I can attach dynamically, inline, how would I do that? (Am I using the correct term here?)

Upvotes: 1

Views: 798

Answers (1)

Marcin
Marcin

Reputation: 239000

If I understand correctly, the following should do what you wish:

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
}

Obviously, aws_iam_policy.lambda_secret_policy must be attached to an actual lambda execution role. I assume that you are doing this in not-shown parts of your code.

Upvotes: 2

Related Questions