我可以使用 terraform 添加开箱即用的 aws_iam_policy (SecurityAudit)、帐户 ID 和外部 ID 到 aws_iam_role 吗?

Can I add an out of the box aws_iam_policy (SecurityAudit), an account id and an external id to an aws_iam_role using terraform?

我正在设置云安全,我需要:

  1. Select 可信实体类型 > 另一个 AWS 账户
  2. 账户 ID:xxxxxxxxxx
  3. 外部 ID:xxxxxxxxxx
  4. 附加 SecurityAudit 策略(已在 AWS 中)

我不确定如何添加已存在的策略或在何处添加 ID。我似乎无法从 terraform 文档中找出解决方案。

../Core/iam_roles.tf

# BEGIN 'foo'
resource "aws_iam_role" "foo" {
  name               = "${terraform.workspace}_Foo"
  path               = "/"
  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "automation.amazonaws.com",
          "events.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "foo" {
  policy_arn = "${aws_iam_policy.security_audit.arn}"
  role = "${aws_iam_role.foo.name}"
}

如有任何帮助,我们将不胜感激!

如果您要附加帐户中已存在的政策,我会使用数据源来查询它。您必须知道 ARN 才能使用 IAM 策略数据源,因此它与直接在 aws_iam_role_policy_attachment 资源中指定 ARN 没有太大区别,除了它允许 terraform plan 命令验证策略在 运行 apply,为您多一份保障。数据源还为您提供了 more information 有关您需要的资源。

data "aws_iam_policy" "security_audit" {
  arn = "arn:aws:iam::${var.target_account_id}:policy/SecurityAudit"
}


# BEGIN 'foo'
resource "aws_iam_role" "foo" {
  name               = "${terraform.workspace}_Foo"
  path               = "/"
  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "automation.amazonaws.com",
          "events.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    },
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::${var.other_aws_account_id}:role/your_role_name_and_path_here"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "foo" {
  policy_arn = "${data.aws_iam_policy.security_audit.arn}"
  role = "${aws_iam_role.foo.name}"
}
`# BEGIN 'Foo'
resource "aws_iam_role" "foo" {
  name = "${terraform.workspace}_Foo"
  path = "/"

  assume_role_policy = <<EOF
{
 "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::INSERT_ACCOUNT_NUMBER:root"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": {
          "sts:ExternalId": "INSERT_EXTERNAL_ID"
        }
      }
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "foo" {
  policy_arn = "arn:aws:iam::aws:policy/SecurityAudit"
  role       = "${aws_iam_role.foo.name}"
}

resource "aws_iam_instance_profile" "foo" {
  name = "${terraform.workspace}_Foo"
  role = "${aws_iam_role.foo.name}"
}

# END
`