9
votes

I'm working on adding resource policy document to S3 bucket.

It works fine when I create a new Bucket:

const newbucket = new s3.Bucket(this, 'newBucket', {
      websiteIndexDocument : 'index.html',
      bucketName : 'NewBucket'
});

newbucket.addToResourcePolicy(new iam.PolicyStatement({
      effect : iam.Effect.ALLOW,
      actions: ['s3:*'],
      resources: [newbucket.arnForObjects('*')],
      principals: [new iam.AnyPrincipal],
    }));

newbucket.addToResourcePolicy(new iam.PolicyStatement({
      effect : iam.Effect.DENY,
      actions: ['s3:*'],
      resources: [newbucket.arnForObjects('*')],
      principals: [new iam.AnyPrincipal],
      conditions : {
        'NotIpAddress' : {
          'aws:SourceIp' : '***.***.***.***'
        }
      }
    }));

But if I try to get a bucket that already exists and add policy document it doesn't work:

const existingbucket = Bucket.fromBucketAttributes(this, 'ImportedBucket',{
      bucketName :'ExistingBucket'
    })

existingbucket.addToResourcePolicy(new iam.PolicyStatement({
      effect : iam.Effect.ALLOW,
      actions: ['s3:*'],
      resources: [existingbucket.arnForObjects('*')],
      principals: [new iam.AnyPrincipal],
    }));

Resource Policy document won't be added.

Furthermore this code deletes existing policy document and make it blank.

Anyone have experience or solution about this issue?

2
Does your CDK stack have permission to modify existing buckets?Jamie
I had similar issue, please refer 60905976 for the solutionsantosh

2 Answers

1
votes

yeah,its possible and i did it using the python cdk. There's a work around here. https://github.com/aws/aws-cdk/issues/6548 The CfnBucketPolicy was used there.

existing_bucket=s3.Bucket.from_bucket_attributes(self, 'ImportedBucket', 
            bucket_arn="arn:aws:s3:::bucket"       
        )

        bucket_policy=iam.PolicyStatement(
            actions=["s3:Get*", "s3:List*"],
            resources=[existing_bucket.arn_for_objects('*')],
            principals=[iam.AccountRootPrincipal()]
        )

        s3.CfnBucketPolicy(self, 'bucketpolicy',
            bucket=existing_bucket.bucket_name,
            policy_document=iam.PolicyDocument(statements=[bucket_policy])
        )
0
votes

I believe you cannot modify the policy of an existing bucket through your CDK App. That is why it works perfectly when you create a new bucket.

If you need to make changes to that bucket's resource policy, I'm afraid you might need to do it manually.