如何使用AWS CDK添加S3 BucketPolicy?

16

我想将这个CloudFormation代码段翻译成CDK:

Type: AWS::S3::BucketPolicy
Properties:
  Bucket:
    Ref: S3BucketImageUploadBuffer
  PolicyDocument:
    Version: "2012-10-17"
    Statement:
      Action:
        - s3:PutObject
        - s3:PutObjectAcl
      Effect: Allow
      Resource:
        - ...

看这里的文档,我并没有找到提供策略文件本身的方法。

4个回答

28

这是一个来自工作中的 CDK Stack 的示例:

   artifactBucket.addToResourcePolicy(
      new PolicyStatement({
        resources: [
          this.pipeline.artifactBucket.arnForObjects("*"), 
          this.pipeline.artifactBucket.bucketArn],
        ],
        actions: ["s3:List*", "s3:Get*"],
        principals: [new ArnPrincipal(this.deploymentRole.roleArn)]
      })
    );

4
不要被 IBucket 所迷惑,因为 aws-cdk 不允许您添加策略。 - Townsheriff

17

在 @Thomas Wagner 的回答基础上,这是我完成此操作的方式。我试图将存储桶限制为给定的 IP 范围:

import * as cdk from '@aws-cdk/core';
import * as s3 from '@aws-cdk/aws-s3';
import * as s3Deployment from '@aws-cdk/aws-s3-deployment';
import * as iam from '@aws-cdk/aws-iam';

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

    // Bucket where frontend site goes.
    const mySiteBucket = new s3.Bucket(this, 'mySiteBucket', {
      websiteIndexDocument: "index.html"
    });

    let ipLimitPolicy = new iam.PolicyStatement({
      actions: ['s3:Get*', 's3:List*'],
      resources: [mySiteBucket.arnForObjects('*')],
      principals: [new iam.AnyPrincipal()]
    });
    ipLimitPolicy.addCondition('IpAddress', {
      "aws:SourceIp": ['1.2.3.4/22']
    });
    // Allow connections from my CIDR
    mySiteBucket.addToResourcePolicy(ipLimitPolicy);


    // Deploy assets
    const mySiteDeploy = new s3Deployment.BucketDeployment(this, 'deployAdminSite', {
      sources: [s3Deployment.Source.asset("./mysite")],
      destinationBucket: mySiteBucket
    });

  }
}

我能够使用 s3.arnForObjects()iam.AnyPrincipal() 这些辅助函数,而不是直接指定 ARN 或 Principal。

我想部署到 Bucket 的资源存储在项目目录的根目录中,名为 mysite 的目录中,并通过调用 s3Deployment.BucketDeployment 引用。当然,这可以是您的构建过程可以访问的任何目录。


6

CDK 的做法与众不同。据我所知,你应该使用 bucket.addToResourcePolicy,如此文档所述 这里


4

根据原始问题,@thomas-wagner的回答是正确的。

如果有人想知道如何在不创建依赖于存储桶的情况下为CloudFront Distribution创建存储桶策略,则需要使用L1构造函数CfnBucketPolicy(以下是一个大概的C#示例):

    IOriginAccessIdentity originAccessIdentity = new OriginAccessIdentity(this, "origin-access-identity", new OriginAccessIdentityProps
    {
        Comment = "Origin Access Identity",
    });

    PolicyStatement bucketAccessPolicy = new PolicyStatement(new PolicyStatementProps
    {
        Effect = Effect.ALLOW,
        Principals = new[]
        {
            originAccessIdentity.GrantPrincipal
        },
        Actions = new[]
        {
            "s3:GetObject",
        },
        Resources = new[]
        {
            Props.OriginBucket.ArnForObjects("*"),
        }
    });

    _ = new CfnBucketPolicy(this, $"bucket-policy", new CfnBucketPolicyProps
    {
        Bucket = Props.OriginBucket.BucketName,
        PolicyDocument = new PolicyDocument(new PolicyDocumentProps
        {
            Statements = new[]
            {
                bucketAccessPolicy,
            },
        }),
    });

其中Props.OriginBucketIBucket实例(一个存储桶)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接