IAM 策略:MalformedPolicyDocument:策略中的语法错误

IAM policy: MalformedPolicyDocument: Syntax errors in policy

我能够成功 运行 包含以下代码片段的 cloudformation 堆栈,现在我的最终目标是将其移植到 Terraform,但是..

即使在 AWS 控制台中,我也收到格式错误的语法错误。我尝试使用 AWS 控制台的 "Policy Editor" 并单击 "Validate" 按钮对此进行调试,但错误是非特定的。有人知道我做错了什么吗?很奇怪,因为当我部署 cloudformation 堆栈模板时,这个策略似乎起作用了。 (顺便说一句,如果有帮助的话,这是来自 GorillaStack 的 AutoTagging 项目)

此策略包含以下错误:策略中存在语法错误。有关 IAM 策略语法的更多信息,请参阅 AWS IAM 策略。

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "logs:CreateLogGroup",
            "logs:CreateLogStream",
            "logs:PutLogEvents"
          ],
          "Resource": "arn:aws:logs:*:*:*"
        },
        {
          "Effect": "Allow",
          "Action": [
            "s3:GetObject",
            "s3:ListBucket"
          ],
          "Resource": [
            "*"
          ]
        },
        {
          "Effect": "Allow",
          "Action": [
            "cloudformation:DescribeStackResource"
          ],
          "Resource": [
            { "Fn::Join": [ "", [ "arn:aws:cloudformation:", { "Ref" : "AWS::Region" }, ":", { "Ref" : "AWS::AccountId" }, ":stack/autotag/*" ] ] }
          ]
        },
        {
          "Effect": "Allow",
          "Action": [
            "sts:*"
          ],
          "Resource": [
            { "Fn::GetAtt" : [ "AutoTagMasterRole", "Arn" ] }
          ]
        }
      ]
    }

我的 Terraform 配置具有以下资源(包括上面的代码片段)

 resource "aws_iam_role_policy" "AutoTagExecutionPolicy" {
   name = "AutoTagExecutionPolicy"
   role = "${aws_iam_role.AutoTagExecutionRole.id}"

   policy = <<EOF
   <-THE POLICY ABOVE GOES HERE->
 EOF
 }

您需要将 Cloudformation 函数转换为 terraform 脚本中的变量。

data "aws_iam_policy_document" "example" {
  statement {
    sid    = "allow logs"
    effect = "Allow"

    action = [
      "logs:CreateLogGroup",
      "logs:CreateLogStream",
      "logs:PutLogEvents",
    ]

    Resources = [
      "arn:aws:logs:*:*:*",
    ]
  }

  statement {
    sid    = "allow s3"
    effect = "Allow"

    action = [
      "s3:GetObject",
      "s3:ListBucket",
    ]

    resource = [
      "*",
    ]
  }

  statement {
    sid = "allow cfn"

    effect = "Allow"

    action = [
      "cloudformation:DescribeStackResource",
    ]

    resource = [
      "${var.cfn_stack}",
    ]
  }

  statement {
    sid    = "allow sts"
    effect = "Allow"

    action = [
      "sts:*",
    ]

    resource = [
      "${var.AutoTagMasterRole_arn}",
    ]
  }
}

然后

resource "aws_iam_policy" "example" {
  name   = "example_policy"
  path   = "/"
  policy = "${data.aws_iam_policy_document.example.json}"
}

https://www.terraform.io/docs/providers/aws/d/iam_policy_document.html

https://www.terraform.io/docs/configuration/interpolation.html