Last updated: Jan 26, 2024
Reading timeยท3 min
Bucket policies are used to grant permissions to an S3 bucket.
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.
Let's look at an example of both. We will start with the addToResourcePolicy
method first.
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 CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // ๐ create the s3 bucket const bucket1 = new s3.Bucket(this, 'bucket-id-1', { removalPolicy: cdk.RemovalPolicy.DESTROY, }); // ๐ `addToResourcePolicy` creates a Bucket Policy automatically bucket1.addToResourcePolicy( new iam.PolicyStatement({ effect: iam.Effect.ALLOW, principals: [new iam.ServicePrincipal('lambda.amazonaws.com')], actions: ['s3:GetObject'], resources: [`${bucket1.bucketArn}/*`], }), ); // ๐ access the bucket policy bucket1.policy?.document.addStatements( new iam.PolicyStatement({ effect: iam.Effect.ALLOW, principals: [new iam.ServicePrincipal('lambda.amazonaws.com')], actions: ['s3:GetBucketTagging'], resources: [bucket1.bucketArn], }), ); } }
Let's go over what we did in the code sample:
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.After I've run the npx aws-cdk deploy
command, we can see that the bucket
policy has been attached.
Let's look at an example, where we use the explicit approach - by
instantiating the BucketPolicy
class to achieve the same result.
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 CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // ... rest // ๐ create the s3 bucket const bucket2 = new s3.Bucket(this, 'bucket-id-2', { removalPolicy: cdk.RemovalPolicy.DESTROY, }); // ๐ create the bucket policy const bucketPolicy = new s3.BucketPolicy(this, 'bucket-policy-id-2', { bucket: bucket2, }); // ๐ add policy statements ot the bucket policy bucketPolicy.document.addStatements( new iam.PolicyStatement({ effect: iam.Effect.ALLOW, principals: [new iam.ServicePrincipal('lambda.amazonaws.com')], actions: ['s3:GetObject'], resources: [`${bucket2.bucketArn}/*`], }), ); } }
Let's go over the code snippet.
BucketPolicy
class.lambda
service to get objects from the bucket.Let's run the deploy
command:
npx aws-cdk deploy
If we take a look at the S3 management console, we can see that the bucket policy has been attached successfully.