Terraform:将先前存在的AWS策略附加到先前存在的AWS角色

时间:2020-11-09 22:19:10

标签: amazon-web-services terraform amazon-iam terraform-provider-aws policy

我不是使用aws控制台简单地将几个预先存在的策略附加到预先存在的角色上,而是需要通过Terraform在模块中针对需要烫发的特定系统执行此操作。

我没有那么幸运吗?

variables.tf
variable "masterrole" {
  description = "role already present within the cn-tio-tooling-acc"
  default = "arn:aws-cn:iam::12345678910:role/Master"
}
variable "policies" {
  description = "policies already present within the cn-tio-tooling-acc"
  default = "arn:aws-cn:iam::12345678910:policy/Source-1,arn:aws-cn:iam::351767606935:policy/Source-2"
}

data.tf <-引用帐户中已经存在的角色和策略数据

data "aws_iam_role" "masterrole" {
  name = "Master"
}

data "aws_iam_policy" "policies" {
  arn = var.policies
}

IAM.tf

resource "aws_iam_role_policy_attachment" "Sources" {
  role       = aws_iam_role.masterrole.name
  policy_arn = aws_iam_policy.policies.arn
}

这里可能很简单,但是为什么我要从“计划”结果中得出以下结论?

错误:对未声明资源的引用 在资源“ aws_iam_role_policy_attachment”“源”中的cn_cpm_iam.tf第3行上: 3:角色= aws_iam_role.masterrole.name 尚未在托管资源中声明托管资源“ aws_iam_role”“ masterrole” 根模块。

错误:对未声明资源的引用 在资源“ aws_iam_role_policy_attachment”“源”中的cn_cpm_iam.tf第4行上: 4:policy_arn = aws_iam_policy.cpmpolicies.arn 尚未在托管资源中声明托管资源“ aws_iam_policy”“ policies” 根模块。

1 个答案:

答案 0 :(得分:2)

在以Terraform引用数据源时,需要在其前面加上data.。因此,尝试使用

resource "aws_iam_role_policy_attachment" "Sources" {
  role       = data.aws_iam_role.masterrole.name
  policy_arn = data.aws_iam_policy.policies.arn
}

但是您已经知道名称和ARN,您可以直接使用它们而无需查询数据源:

resource "aws_iam_role_policy_attachment" "Sources" {
  role       = "Master"
  policy_arn = var.policies
}

让我知道我是否在这里错过了什么;)

相关问题