为什么此AWS CloudFormation脚本会引发“策略包含具有一个或多个无效主体的语句”错误?

时间:2019-08-28 06:43:29

标签: amazon-web-services amazon-s3 amazon-cloudformation aws-kms

我正在尝试:

  1. 创建CMK
  2. 创建一个需要/强制使用该存储桶的新存储桶 CMK

代码来自here

AWSTemplateFormatVersion: 2010-09-09
Description: Example template with Customer Master Key and S3 bucket

Resources:
Bucket:
    Type: "AWS::S3::Bucket"
    DeletionPolicy: Retain
    Properties:
    BucketEncryption:
        ServerSideEncryptionConfiguration:
        - ServerSideEncryptionByDefault:
            KMSMasterKeyID: !Sub "arn:aws:kms:${AWS::Region}:${AWS::AccountId}:${CMKAlias}"
            SSEAlgorithm: "aws:kms"

CMKAlias:
    Type: "AWS::KMS::Alias"
    Properties:
    AliasName: "alias/test/cmk"
    TargetKeyId: !Ref CMK

CMK:
    Type: "AWS::KMS::Key"
    Properties:
    Description: "My CMK"
    Enabled: True
    EnableKeyRotation: true
    KeyPolicy:
        Version: "2012-10-17"
        Statement:
        - Sid: "Allow root IAM"
            Effect: "Allow"
            Principal:
            AWS: !Sub "arn:aws:iam::${AWS::AccountId}:user/root"
            Action:
            - "kms:*"
            Resource: "*"

Outputs:
CMKId:
    Value: !Ref CMK
CMKArn:
    Value: !GetAtt CMK.Arn
CMKAliasArn:
    Value: !Sub "arn:aws:kms:${AWS::Region}:${AWS::AccountId}:${CMKAlias}"
Bucket:
    Value: !Ref Bucket

错误是:

The following resource(s) failed to create: [CMK]. . Rollback requested by user.

Policy contains a statement with one or more invalid principals. 
(Service: AWSKMS; Status Code: 400;
Error Code: MalformedPolicyDocumentException;
Request ID: zzzzzz-zzzzz-zzzzz)

我相信问题出在这一行:

AWS: !Sub "arn:aws:iam::${AWS::AccountId}:user/root"

我从intrinsic-function-reference-sub看到!Sub是替换值的函数,并且从pseudo-parameter-reference看到$ {AWS :: AccountId}是有效的伪参数,所以我不明白为什么那条线失败了。

我从how-to-generate-the-aws-root-account-arn-in-cloudformation看到,这在YAML中被认为是有效的方式:

!Sub arn:aws:iam::${AWS::AccountId}:root

1 个答案:

答案 0 :(得分:1)

您的缩进不正确。

尝试以下操作:

KeyPolicy:
    Version: "2012-10-17"
    Statement:
      - Sid: "Allow root IAM"
        Effect: "Allow"
        Principal:
        AWS: !Sub "arn:aws:iam::${AWS::AccountId}:user/root"
        Action:
          - "kms:*"
        Resource: "*"