使用 CDK 将 IAM 策略添加到 S3 出现错误

时间:2021-03-17 01:12:00

标签: amazon-s3 amazon-iam aws-cdk

我正在尝试使用 CDK 创建 S3 存储桶。 Bucket 已经创建好了。但是,当我尝试添加以下 IAM 策略时,创建失败 - API:s3:PutBucketPolicy Access Denied

TestBucket.addToResourcePolicy(new iam.PolicyStatement({
      actions: [ 's3:*'],
      effect: iam.Effect.DENY,
      principals: [ new iam.AnyPrincipal],
      resources:  [TestBucket.bucketArn+'/*'],
      conditions: {
        "Bool": {
          "aws:SecureTransport": "false"
        }
      },

我运行此代码的用户具有管理员权限。可能是什么问题?

1 个答案:

答案 0 :(得分:0)

示例 CDK 代码以创建 S3 存储桶并将资源策略设置为仅允许 HTTPS。

import * as cdk from "@aws-cdk/core";
import * as s3 from "@aws-cdk/aws-s3";
import * as iam from "@aws-cdk/aws-iam";

export class TestS3Stack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    this.simpleS3();
  }

  simpleS3() {
    const myBucket = new s3.Bucket(this, "my-bucket", {
      bucketName: "my-test-bucket-balu",
      blockPublicAccess: {
        blockPublicAcls: true,
        blockPublicPolicy: true,
        ignorePublicAcls: true,
        restrictPublicBuckets: true,
      },
    });
    myBucket.addToResourcePolicy(
      new iam.PolicyStatement({
        actions: ["s3:*"],
        effect: iam.Effect.DENY,
        principals: [new iam.AnyPrincipal()],
        resources: [myBucket.bucketArn, myBucket.bucketArn + "/*"],
        conditions: {
          Bool: {
            "aws:SecureTransport": "false",
          },
        },
      })
    );
  }
}

除非有 service control policy 阻止管理员用户访问 PutBucketPolicy,否则在创建仅阻止 http 请求的存储桶策略时,我们不会收到错误消息。

我们可以通过尝试从 cli 中放置存储桶策略来检查是否存在权限问题

<块引用>

aws s3api put-bucket-policy --bucket my-test-bucket --policy '{"Version": "2012-10-17","Statement": [{"Effect": "Deny","Principal": "","Action": "s3:","Resource": "arn:aws:s3:::my-test-bucket/*","Condition": {"Bool": {"aws:SecureTransport": "false"}}}]}'