CrossAccount IAM Role in AWS

Is there a way I can create crossaccount IAM role in terraform. I dont see any option to mention the other account’s account id in the role creation

Heya dhineshbabuelango,

You absolutely can. This is all done via the assume_role_policy argument to aws_iam_role.

There’s a module on the registry called iam-role-cross-account-trusting that will show you how to do this; this isn’t any kind of endorsement or criticisim of the module, just that it’s got a good example we can look at.

There’s a nested module that does the creation of the assume_role_policy which is in policy.tf.

If we simplify it down to remove the conditional, we get this:

data "aws_iam_policy_document" "cross_account_assume_role_policy" {
  statement {
    effect = "Allow"

    principals {
      type        = "AWS"
      identifiers = var.principal_arns
    }

    actions = ["sts:AssumeRole"]
  }
}

resource "aws_iam_role" "cross_account_assume_role" {
  name               = var.role_name
  assume_role_policy = data.aws_iam_policy_document.cross_account_assume_role_policy.json
}

In this example, var.principal_arns would be the ARN of the account, user or role that you want to grant access, as per the AWS Documentation.

The user or role on the recieving account also needs the ability to run sts:AssumeRole against the IAM role that you have shared across too, as standard IAM permissions.

For more information, you might want to look at the documentation for data.aws_iam_policy_document for a bit of extra information.

Thanks @Gareth for this, Let me test this out :slight_smile: