Terraform: correct way to attach AWS managed policies to a role? Ask Question

Terraform: correct way to attach AWS managed policies to a role? Ask Question

I want to attach one of the pre-existing AWS managed roles to a policy, here's my current code:

resource "aws_iam_role_policy_attachment" "sto-readonly-role-policy-attach" {
  role       = "${aws_iam_role.sto-test-role.name}"
  policy_arn = "arn:aws:iam::aws:policy/ReadOnlyAccess"
}

Is there a better way to model the managed policy and then reference it instead of hardcoding the ARN? It just seems like whenever I hardcode ARNs / paths or other stuff like this, I usually find out later there was a better way.

Is there something already existing in Terraform that models managed policies? Or is hardcoding the ARN the "right" way to do it?

ベストアンサー1

The IAM Policy data source is great for this. A data resource is used to describe data or resources that are not actively managed by Terraform, but are referenced by Terraform.

For your example, you would create a data resource for the managed policy as follows:

data "aws_iam_policy" "ReadOnlyAccess" {
  arn = "arn:aws:iam::aws:policy/ReadOnlyAccess"
}

この場合、データ ソースの名前はReadOnlyAccess完全に自由に決められます。管理対象ポリシーの場合、一貫性を保つためにポリシー名と同じ名前を使用しますが、readonly必要に応じて簡単に名前を付けることもできます。

次に、次のように IAM ポリシーをロールにアタッチします。

resource "aws_iam_role_policy_attachment" "sto-readonly-role-policy-attach" {
  role       = "${aws_iam_role.sto-test-role.name}"
  policy_arn = "${data.aws_iam_policy.ReadOnlyAccess.arn}"
}

おすすめ記事