如何在Terraform中创建角色

时间:2018-10-19 06:32:49

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

我想用terraform创建aws_iam_role,但是运行terraform apply后,我收到以下错误消息: aws_iam_role.role: Error Updating IAM Role (edb_eb_role) Assume Role Policy: MalformedPolicyDocument: Has prohibited field Resource

那是我的政策:

resource "aws_iam_role" "role" {
name = "edb_eb_role"

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

我错了什么?我还尝试仅对校长进行此操作,但随后我收到一条消息,即“校长”也不受禁止?

1 个答案:

答案 0 :(得分:3)

Assume_role_policy不接受aws策略json文件。因此,上面的代码不起作用。
有关aws_iam_role中的accept_role_policy的详细说明,请参见此thread。 / p>

如下所示更新代码并执行。

variable policy_arn{
    default = "arn:aws:iam::aws:policy/service-role/AWSLambdaRole"
}
resource "aws_iam_role" "edb_role" {
name = "edb_role"

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


resource "aws_iam_role_policy_attachment" "test-attach" {
    role       = "${aws_iam_role.edb_role.name}"
    policy_arn = "${var.policy_arn}"
}

output "role" {
  value = "${aws_iam_role.edb_role.name}"
}

在这里,我们使用的是IAM的“策略”部分中的AWSLambdaRole策略。

  • 使用aws_iam_role_policy_attach
  • 向角色添加多个策略
  • 使用aws提供的默认策略,如上所示。要创建新策略,请参阅文档here