Terraform:将 aws_iam_role 与 aws_iam_policy 相关联

Terraform: associate an aws_iam_role with an aws_iam_policy

通读 the docs 并且很难理解如何将 aws_iam_roleaws_iam_policy 关联起来。显然有 aws_iam_role_policy,但这只允许为特定角色制作 "inline policies"。

有什么建议吗?

按照以下步骤操作:

步骤 1) 创建要与 aws 角色关联的策略。

步骤 2) 创建 aws 角色如下:

i. Set role name.

ii. Set role type according to your preference.

iii. Attach the policy which you have created in step1.

iv. Review and create the role.

希望对您有所帮助......

The aws_iam_policy_attachment resource 允许在 IAM 策略和各种其他 IAM 对象之间创建连接。

例如:

resource "aws_iam_role" "foo" {
    name = "example-role"
}

resource "aws_iam_policy" "foo" {
    name = "example-policy"
    description = "An example policy"
    policy = "..."
}

resource "aws_iam_policy_attachment" "foo" {
    name = "example-attachment"
    policy_arn = "${aws_iam_policy.foo.arn}"
    roles = ["${aws_iam_role.foo.name}"]
}

策略也可以附加到用户和组,如 Terraform 文档页面所示。​​

我必须做的是创建一个角色和一个策略,然后按照 Martin Atkins 的回答所示附加它们。

resource "aws_iam_role" "context-builder-role" {
  name = "context-builder-role-${terraform.workspace}"

  assume_role_policy = <<EOF
{
     "Version": "2012-10-17",
     "Statement": [
       {
         "Action": "sts:AssumeRole",
         "Principal": {
         "Service": "lambda.amazonaws.com"
       },
         "Effect": "Allow",
         "Sid": ""
       }
     ]
}
EOF
}

resource "aws_iam_policy" "arm_cfs_sqs_queue_policy" {

  name = "starmine-inline-policy-${terraform.workspace}"

  policy = <<EOF
{
   "Version": "2012-10-17",
   "Statement": [
       {
           "Effect": "Allow",
           "Action": [
               "logs:CreateLogGroup",
               "logs:CreateLogStream",
               "logs:PutLogEvents"
           ],
           "Resource": "arn:aws:logs:*:*:*"
       },
       {
           "Action": [
               "sqs:SendMessage",
               "sqs:GetQueueUrl",
               "sqs:DeleteMessage"
           ],
           "Effect": "Allow",
           "Resource": "arn:aws:sqs:*"
       }
   ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "inline-policy-attach" {
  role       = aws_iam_role.context-builder-role.name
  policy_arn = aws_iam_policy.arm_cfs_sqs_queue_policy.arn
}

您还可以使用策略 ARN 将 AWS 策略附加到角色:

resource "aws_iam_role_policy_attachment" "s3-read-only-attach" {
  role       = aws_iam_role.context-builder-role.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess"
}