Terraform:创建IAM角色时出错。 MalformedPolicyDocument:已禁止字段资源

时间:2017-06-15 11:03:42

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

我的TF代码给了我一个错误:

  /*
   * Policy: AmazonEC2ReadOnlyAccess
   */
  assume_role_policy = <<EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:Describe*",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "elasticloadbalancing:Describe*",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "cloudwatch:ListMetrics",
                "cloudwatch:GetMetricStatistics",
                "cloudwatch:Describe*"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "autoscaling:Describe*",
            "Resource": "*"
        }
    ]
}
EOF

我从https://console.aws.amazon.com/iam/home?region=us-west-2#/policies/arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess $ jsonEditor

复制并粘贴了该政策
* aws_iam_role.<role name>: Error creating IAM Role <role name>: MalformedPolicyDocument: Has prohibited field Resource
status code: 400, request id: <request id>

不确定为什么说资源被禁止。

3 个答案:

答案 0 :(得分:9)

您需要提及sts:AssumeRole。您可以使用aws_iam_role_policy_attachment直接附加政策,而不是复制现有政策。

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

resource "aws_iam_role_policy_attachment" "ec2-read-only-policy-attachment" {
    role = "${aws_iam_role.ec2_iam_role.name}"
    policy_arn = "arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess"
}

答案 1 :(得分:0)

我在使用角色 arn 时遇到过类似的问题。当我尝试使用 aws_iam_role_policy_attachment 时 - 我收到错误,因为角色名称包含不受支持的字符。

创建如下 aws_iam_role_policy 对我有用的是什么:

resource "aws_iam_role_policy" "api-invoker" {
    provider = <some provider>
    role     = aws_iam_role.api-invoker.id
    policy   = data.aws_iam_policy_document.execute-api.json
}

data "aws_iam_policy_document" "execute-api" {
    statement {
     sid = "all"
     actions = [
       "execute-api:*",
     ]
     resources = [
       "*"
     ]
   }
}

答案 2 :(得分:0)

我在创建策略以从另一个 AWS 账户担任角色时遇到了同样的问题。所以,我在可信实体中添加了另一个 AWS 账户 ID,然后问题就解决了。