Terraform:将 AWS 托管策略附加到角色的正确方法? [英] Terraform: correct way to attach AWS managed policies to a role?

查看:25
本文介绍了Terraform:将 AWS 托管策略附加到角色的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将预先存在的 AWS 托管角色之一附加到策略中,这是我当前的代码:

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

是否有更好的方法来对托管策略进行建模然后引用它而不是硬编码 ARN?似乎每当我对 ARN/路径或其他类似的东西进行硬编码时,我通常会在以后发现有更好的方法.

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.

Terraform 中是否已经存在对托管策略进行建模的东西?还是对 ARN 进行硬编码是正确"的做法?

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

推荐答案

IAM 政策数据源 非常适合这一点.数据资源用于描述未被 Terraform 主动管理但被 Terraform 引用的数据或资源.

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.

The name of the data source, ReadOnlyAccess in this case, is entirely up to you. For managed policies I use the same name as the policy name for the sake of consistency, but you could just as easily name it readonly if that suits you.

然后,您将 IAM 策略附加到您的角色,如下所示:

You would then attach the IAM policy to your role as follows:

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

这篇关于Terraform:将 AWS 托管策略附加到角色的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆