Updating IAM role's trust relationship

922 Views Asked by At

In Terraform, I am creating an IAM role through an external module using:

module "test_role" {
  source = "terraform.abc/work-role/aws"
  name   = "test_role"
}

This module creates an IAM role 'test_role' with the following trust relationship:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::1234567890:original"
      },
      "Action": [
        "sts:TagSession",
        "sts:AssumeRoleWithWebIdentity"
      ]
    }
  ]
}

I want add another statement to the trust relationship of this same role, so that it looks like:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::1234567890:original"
      },
      "Action": [
        "sts:TagSession",
        "sts:AssumeRoleWithWebIdentity"
      ]
    },
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::0987654321:role/qa-admin"
      },
      "Action": [
        "sts:TagSession",
        "sts:AssumeRoleWithWebIdentity"
      ]
    }
  ]
}

How can I do this in Terraform?

When I make a aws_iam_policy_document and attach it to the role using aws_iam_role_policy_attachment, it is being added to Permissions policies and not Trust relationships. What am I doing wrong?

1

There are 1 best solutions below

3
Ermiya Eskandary On

Setting the trust policy for an IAM role is done via the assume_role_policy argument for the aws_iam_role resource.

Various examples of how to use it are provided by Terraform but here's one way to do it in your case:

resource "aws_iam_role" "test_role" {
  name               = "test_role"
  assume_role_policy = data.aws_iam_policy_document.test_trust_policy.json
}

data "aws_iam_policy_document" "test_trust_policy" {
  statement {
    actions = ["sts:TagSession", "sts:AssumeRoleWithWebIdentity"]

    principals {
      type        = "Federated"
      identifiers = ["arn:aws:iam::1234567890:original"]
    }
  }

  statement {
    actions = ["sts:TagSession", "sts:AssumeRoleWithWebIdentity"]

    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::0987654321:role/qa-admin"]
    }
  }
}