Search code examples
amazon-web-servicesterraformamazon-kms

Terraform - aws_kms_key throwing MalformedPolicyDocumentException


I'm implementing some AWS security policies for our customer accounts. I plan on deploying those through Terraform and thus using aws_kms_key resource to create some KMS keys for CloudTrail encryption. Here is how my code looks:

resource "aws_kms_key" "trail" {
  description         = "KMS Key for CloudTrails encryption"
  enable_key_rotation = true

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Id": "key-consolepolicy-3",
  "Statement": [
    {
      "Sid": "Enable IAM User Permissions",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"
      },
      "Action": "kms:*",
      "Resource": "*"
    },
    {
      "Sid": "Allow access for Key Administrators",
      "Effect": "Allow",
      "Principal": "*",
      "Condition": {
          "StringNotLike": {
              "aws:userid": [
                  "${element(split(":", data.aws_caller_identity.current.user_id), 0)}:*"
              ]
          }
      },
      "Action": [
        "kms:Create*",
        "kms:Describe*",
        "kms:Enable*",
        "kms:List*",
        "kms:Put*",
        "kms:Update*",
        "kms:Revoke*",
        "kms:Disable*",
        "kms:Get*",
        "kms:Delete*",
        "kms:TagResource",
        "kms:UntagResource",
        "kms:ScheduleKeyDeletion",
        "kms:CancelKeyDeletion"
      ],
      "Resource": "*"
    },
    {
      "Sid": "Allow use of the key",
      "Effect": "Allow",
      "Principal": "*",
      "Condition": {
          "StringNotLike": {
              "aws:userid": [
                  "${element(split(":", data.aws_caller_identity.current.user_id), 0)}:*"
              ]
          }
      },
      "Action": [
        "kms:Encrypt",
        "kms:Decrypt",
        "kms:ReEncrypt*",
        "kms:GenerateDataKey*",
        "kms:DescribeKey"
      ],
      "Resource": "*"
    },
    {
      "Sid": "Allow attachment of persistent resources",
      "Effect": "Allow",
      "Principal": "*",
      "Condition": {
          "StringNotLike": {
              "aws:userid": [
                  "${element(split(":", data.aws_caller_identity.current.user_id), 0)}:*"
              ]
          }
      },
      "Action": [
        "kms:CreateGrant",
        "kms:ListGrants",
        "kms:RevokeGrant"
      ],
      "Resource": "*",
      "Condition": {
        "Bool": {
          "kms:GrantIsForAWSResource": "true"
        }
      }
    }
  ]
}
EOF
}

But that throws..

aws_kms_key.trail: MalformedPolicyDocumentException: status code: 400, request id: a1e22d67-327f-11e8-8db1-195a2ed24241

when applied. Can somebody please help?

Thank you in advance.


Solution

  • The final statement has the Condition key duplicated. If you want multiple conditions, create it within one.