Terraform:将aws_iam_role与aws_iam_policy相关联

时间:2015-06-24 16:28:02

标签: amazon-web-services amazon-iam terraform

阅读the docs,并且很难看到如何将aws_iam_roleaws_iam_policy相关联。显然有aws_iam_role_policy,但这只允许制作"内联政策"特定角色。

有什么建议吗?

3 个答案:

答案 0 :(得分:4)

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文档页面所示。​​

答案 1 :(得分:0)

我要做的是创建一个角色和一个策略,然后按照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"
}

答案 2 :(得分:-3)

按照以下步骤操作:

步骤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.

希望它有所帮助.......