Add policy to existing bucket - AWS CDK
Bucket policies are used to grant permissions to an S3 bucket.
There are 2 ways to create a bucket policy in AWS CDK:
- instantiate the BucketPolicy class.
- use the addToResourcePolicy method on an instance of the Bucket class.
Approach - 1
Let's look at an example, where we use the explicit approach - by instantiating the BucketPolicy class to achieve the same result.import * as cdk from 'aws-cdk-lib';import * as iam from 'aws-cdk-lib/aws-iam';import * as s3 from 'aws-cdk-lib/aws-s3';
export class CdkExampleStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props);
// create the s3 bucket const sampleBucket = new s3.Bucket(this, 'sample-bucket', { removalPolicy: cdk.RemovalPolicy.DESTROY, });
// create the bucket policy const bucketPolicy = new s3.BucketPolicy(this, 'sample-bucket-policy', { bucket: sampleBucket, // S3 bucket created earlier });
// add policy statements to the bucket policy bucketPolicy.document.addStatements( new iam.PolicyStatement({ effect: iam.Effect.ALLOW, principals: [new iam.ServicePrincipal('lambda.amazonaws.com')], actions: ['s3:GetObject'], resources: [`${sampleBucket.bucketArn}/*`], }) ); }}
We added a policy statement to the S3 bucket policy. The statement allows the lambda service to get objects from the bucket.
Approach - 2
We used the addToResourcePolicy method on the bucket instance passing it a policy statement as the only parameter. A bucket policy was automatically created for us by CDK once we added a policy statement.
import * as iam from 'aws-cdk-lib/aws-iam';import * as s3 from 'aws-cdk-lib/aws-s3';import * as cdk from 'aws-cdk-lib';export class CdkExampleStack extends cdk.Stack {constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {super(scope, id, props);// create the s3 bucketconst sampleBucket = new s3.Bucket(this, 'sample-bucket', {removalPolicy: cdk.RemovalPolicy.DESTROY,});// `addToResourcePolicy` creates a Bucket Policy automaticallysampleBucket.addToResourcePolicy(new iam.PolicyStatement({effect: iam.Effect.ALLOW,principals: [new iam.ServicePrincipal('lambda.amazonaws.com')],actions: ['s3:GetObject'],resources: [`${sampleBucket.bucketArn}/*`],}),);// access the bucket policysampleBucket.policy?.document.addStatements(new iam.PolicyStatement({effect: iam.Effect.ALLOW,principals: [new iam.ServicePrincipal('lambda.amazonaws.com')],actions: ['s3:GetBucketTagging'],resources: [sampleBucket.bucketArn],}),);}
No comments:
Post a Comment
If you have any doubts, Please let me know