amazon-web-servicesaws-cdkaws-policies

Attaching a json policy to a s3 bucket with CDK and typescript


I have a policy statement which I can add to my bucket:

const statement = new PolicyStatement({
    effect: Effect.ALLOW,
    principals: '*',
    actions: ["s3:GetObject"],
    resources: [`${bucket.bucketArn}/*`],
});

mybucket.addToResourcePolicy(statement);

However, I have a policy document which contains multiple statements:

 const policy = new PolicyDocument({
      statements: [// many statements ]
})

How can I attached this to my bucket?


Solution

  • You could pass the policy document to a CfnBucketPolicy construct:

    const cfnBucketPolicy = new s3.CfnBucketPolicy(this, 'MyCfnBucketPolicy', {
      bucket: bucket.bucketName,
      policyDocument: policy
    });
    

    Or apply each statement individually with addToResourcePolicy, as @jarmod suggets in the comments:

    declare const myStatements: iam.PolicyStatement[];
    myStatements.forEach(bucket.addToResourcePolicy)