title: Terraform policy attachment to a role name in module
body: <p>I'm trying to create data roles in three environments in AWS using Terraform.
  One is an role in root account. This role can is used to login to AWS and can assume data roles in production and staging. This works fine. This is using a separate module.</p>
  
  <p>I have problems when trying to create the roles in prod and staging from a module.
  My module looks like this main.tf:</p>
  
  <pre><code>resource "aws_iam_role" "this" {
  
    name               = "${var.name}"
    description        = "${format("%s (managed by Terraform)", var.policy_description)}"
    assume_role_policy = "${length(var.custom_principals) == 0 ? data.aws_iam_policy_document.assume_role.json : data.aws_iam_policy_document.assume_role_custom_principals.json}"
  }
  
  resource "aws_iam_policy" "this" {
    name        = "${var.name}"
    description = "${format("%s (managed by Terraform)", var.policy_description)}"
    policy      = "${var.policy}"
  }
  
  data "aws_iam_policy_document" "assume_role" {
    statement {
      actions = ["sts:AssumeRole"]
  
      principals {
        type        = "AWS"
        identifiers = ["arn:aws:iam::${var.account_id}:root"]
      }
    }
  }
  
  data "aws_iam_policy_document" "assume_role_custom_principals" {
    statement {
      actions = ["sts:AssumeRole"]
  
      principals {
        type = "AWS"
  
        identifiers = [
          "${var.custom_principals}",
        ]
      }
    }
  }
  
  resource "aws_iam_role_policy_attachment" "this" {
    role       = "${aws_iam_role.this.name}"
    policy_arn = "${aws_iam_policy.this.arn}"
  }
  </code></pre>
  
  <p>I also have the following in output.tf:</p>
  
  <pre><code>output "role_name" {
     value = "${aws_iam_role.this.name}"
  }
  </code></pre>
  
  <p>Next I try to use the module to create two roles in prod and staging.
  main.tf:</p>
  
  <pre><code>module "data_role" {
    source = "../tf_data_role"
  
    account_id         = "${var.account_id}"
    name               = "data"
    policy_description = "Role for data engineers"
  
    custom_principals = [
      "arn:aws:iam::${var.master_account_id}:root",
    ]
  
    policy = "${data.aws_iam_policy_document.data_access.json}"
  }
  </code></pre>
  
  <p>Then I'm trying to attach a AWS policies like this:</p>
  
  <pre><code>resource "aws_iam_role_policy_attachment" "data_readonly_access" {
    role       = "${module.data_role.role_name}"
    policy_arn = "arn:aws:iam::aws:policy/ReadOnlyAccess"
  }
  
  resource "aws_iam_role_policy_attachment" "data_redshift_full_access" {
    role       = "${module.data_role.role_name}"
    policy_arn = "arn:aws:iam::aws:policy/AmazonRedshiftFullAccess"
  }
  </code></pre>
  
  <p>The problem I encounter here is that when I try to run this module the above two policies are not attached in staging but in root account. How can I fix this to make it attach the policies in staging?</p>