Crossaccount IAM role stopped working with terraform

Hello,

Could someone help me understand an issue I encountered when I used Terraform to recreate an IAM role that was originally created manually?

I have two AWS accounts: A (111111111111) and B (222222222222).

Account A has a role named Role_1 with a policy that allows assuming roles located in Account B. Here is the policy from Account A:

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "sts:AssumeRole",
    "Resource": "arn:aws:iam::222222222222:role/Role_2"
  }
}

At the same time, Account B has a role called Role_2 with a trusted entity policy as shown below, which allows Account A to assume this role

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::111111111111:role/Role_1"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

All this functionality worked fine until I attempted to create Role_1 with the same policy using Terraform. Below is the Terraform code that achieves what I described above

resource "aws_iam_policy" "assume_sts_policy" {
  name        = "sts-policy"
  policy      = jsonencode({
    "Version" : "2012-10-17",
    "Statement" : [
      {
        "Effect" : "Allow",
        "Action" : "sts:AssumeRole",
        "Resource" : "arn:aws:iam::111111111111:role/Role_1"
      }
    ]
  })
}

resource "aws_iam_role" "sts_role" {
  name                 = "Role_1"
  assume_role_policy   = data.aws_iam_policy_document.main_role_trusted_entities.json
  managed_policy_arns  = [
    "arn:aws:iam::aws:policy/AmazonS3FullAccess",
    aws_iam_policy.assume_sts_policy.arn
  ]
}

After creation, I started to receive an error

An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:sts::111111111111:role/Role_1 is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::222222222222:role/Role_2

I spent a lot of time until I found a way to fix it. In Account B, I modified the trusted entities policy to look like below, and then it finally worked

{
  "Effect": "Allow",
  "Condition": {
      "StringEquals" : {
          "aws: PrincipalARN": "arn:aws:iam: : 111111111111:role/Role_1"
      }
  },
  "Principal": {
      "AWS": "arn:aws:iam:: 111111111111:root"
  },
    "Action": "sts:AssumeRole"
}

So i had to add :root instead of role name, and a condition that checks PrincipalARN

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.