Search code examples
amazon-web-servicesterraformterraform-provider-aws

Terraform policy document generated as json


I am trying to create a iam role with terraform. Instead of providing the role with inline JSON I am trying to create it using terraform and then attach it to the role. I am following the documentation given here and somehow it does not seem to work.

Can someone help?

provider "aws" {
    region = "eu-west-1"
    profile = "admin"
  
}

data "aws_caller_identity" "current" {}

locals {
  account_id = data.aws_caller_identity.current.account_id
}

output "account_id" {
    value = local.account_id  
}

resource "aws_iam_role" "github_actions_role" {
  name = "GitHubActionsRole"
  assume_role_policy = resource.aws_iam_policy.trust
}

resource "aws_iam_policy" "trust" {
    name = "trust_policy"
    path = "/"
    policy = data.aws_iam_policy_document.assume_role_policy.json
  
}

data "aws_iam_policy_document" "assume_role_policy" {
    statement {
      actions = ["sts:AssumeRoleWithWebIdentity"]

      principals {
        type = "Federated"
        identifiers = ["arn:aws:iam::${local.account_id}:oidc-provider/token.actions.githubusercontent.com"]
      }

      condition {
        test = "StringEquals"
        variable = "token.actions.githubusercontent.com:aud"
        values = [ "sts.amazonaws.com" ]
      }

      condition {
        test = "StringEquals"
        variable = "token.actions.githubusercontent.com:sub"
        values = [ "repo:Parthiva/*" ]
      }

    }
}

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


resource "aws_iam_role_policy_attachment" "github_actions_role_policy_attach" {
   role       = "${aws_iam_role.github_actions_role.name}"
   policy_arn = "${data.aws_iam_policy.admin_policy.arn}"
}

After running terraform plan the following was the error

│ Error: Incorrect attribute value type
│
│   on gh-actions-role.tf line 22, in resource "aws_iam_role" "github_actions_role":
│   22:   assume_role_policy = resource.aws_iam_policy.trust
│     ├────────────────
│     │ resource.aws_iam_policy.trust is object with 10 attributes
│

Solution

  • You can't use aws_iam_policy to create assume_role_policy. From docs:

    The assume_role_policy is very similar to but slightly different than a standard IAM policy and cannot use an aws_iam_policy resource. However, it can use an aws_iam_policy_document data source. See the example above of how this works.

    Instead you must use data source (not resource) aws_iam_policy_document.