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?
There are 2 ways to create a bucket policy in AWS CDK:The approach with the addToResourcePolicy method is implicit - once we add a policy statement to the bucket, CDK automatically creates a bucket policy for us. The second approach is explicit and a bit easier for the reader of our code to understand.
To create or edit a bucket policyIn the Buckets list, choose the name of the bucket that you want to create a bucket policy for or whose bucket policy you want to edit. Choose Permissions. Under Bucket policy, choose Edit. This opens the Edit bucket policy page.
Multiple IAM policies can be attached to the same IAM user. In one of the policies, let's say the user is given access to a S3 Bucket and in another policy the user is denied to the same S3 Bucket.
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])
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With