0
votes

Instead of using the aws console to simply attach a couple of pre-existing policies to a pre-existing role, I need to do it via Terraform within a module for a specific system that requires the perms.

I am not having much luck doing it though?

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 <-- Referencing the role and policy data that's already present within the account

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
}

Probably something really simple here, but why do I get the following from a 'plan' result?

Error: Reference to undeclared resource on cn_cpm_iam.tf line 3, in resource "aws_iam_role_policy_attachment" "Sources": 3: role = aws_iam_role.masterrole.name A managed resource "aws_iam_role" "masterrole" has not been declared in the root module.

Error: Reference to undeclared resource on cn_cpm_iam.tf line 4, in resource "aws_iam_role_policy_attachment" "Sources": 4: policy_arn = aws_iam_policy.cpmpolicies.arn A managed resource "aws_iam_policy" "policies" has not been declared in the root module.

1

1 Answers

2
votes

When referencing data sources in terraform you need to prefix them with data.. So try using

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

But as you already know the name and the ARN you can just use them without querying the data sources:

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

Let me know if i am missing something here ;)