简体   繁体   中英

How to create secrets manager secret resource policy that references the secret itself using Terraform?

I'm trying to create a terraform script that creates an AWS secrets manager secret with a resource based policy that grants an IAM role permissions to secretsmanager:GetSecretValue on that specific secret.

I'm currently running into Terraform cycle issue between the secrets manager secret and the IAM policy document. Here's what my code looks like:

resource "aws_secretsmanager_secret" "this" {
  name = "mySecret"    
  policy = data.aws_iam_policy_document.this.json
}

data "aws_iam_policy_document" "this" {
  statement {
    sid = "ReadPermissions"
    principals {
      type = "aws"
      identifiers = [data.aws_iam_role.this.arn]
    }
    actions = ["secretsmanager:GetSecretValue"]
    resources = [aws_secretsmanager_secret.this.arn]
  }
}

data "aws_iam_role" "this" {
  name = "myRole"
}

What's the best way to resolve this?

You can try to use aws_secretsmanager_secret_policy, it can create a resource policy instead of IAM policy.

Example:

resource "aws_secretsmanager_secret" "example" {
  name = "example"
}

resource "aws_secretsmanager_secret_policy" "example" {
  secret_arn = aws_secretsmanager_secret.example.arn

  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "EnableAnotherAWSAccountToReadTheSecret",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:root"
      },
      "Action": "secretsmanager:GetSecretValue",
      "Resource": "*"
    }
  ]
}
POLICY
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM