Introduction
Steps to Create AWS s3 Bucket using CDK V2
Step 1:
- Create a folder on the Local Derive
- Open the folder in VSCode Editor
- Open Terminal
Step 2: Create the app
- Make a directory mys3Cdk (or any other based on our choice)
mkdir mys3Cdk
- Change directory with cd
cd mys3Cdk
- Initialize the app by using cdk init command. Specify the programming language
cdk init app --language typescript
Step 3:
In the lib/mys3_cdk-stack.ts file
- Import the modules/packages (All or specific Construct from the Module) for AWS services being created
import * as lambda from 'aws-cdk-lib/aws-lambda' (example)
Step 4: Define Scope, Logical ID, and Props
- Scope =this
- Logical ID = Logical ID Name (Different from physical Id)
- props – Add the attributes to create the Resources – AWS documentation or Editor code Complete
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
export class Mys3CdkStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const s3DemoBucket= new s3.Bucket(this,'s3demobucket001',{
bucketName:'demosbucket0123',
versioned:true,
publicReadAccess:false
})
}
}
Step 5: Build the app (optional)
Build (compile) after changing your code.
AWS CDK — the Toolkit implements it but a good practice to build manually to catch syntax and type errors.
npm run build
Step 6: Bootstrap (One Time): Deploys the CDK Toolkit staging stack in s3 bucket.
cdk bootstrap
Step 7: Synthesize an AWS CloudFormation template for the app.
cdk synth
Step 8: Deploying the Stack (Deploy the stack using AWS CloudFromation)
cdk deploy
After that stack will created in Cloudformation
Now we will go to s3 and check bucket has been created
Step 9: Modifying the app
The AWS CDK can update deployed resources after we modify our app To see these changes, use the CDK diff command
cdk diff
To examine variances within the existing stack, we are currently implementing some modifications. Presently, the S3 bucket that has been created includes the property publicReadAccess with a value of false. Our next step involves altering the publicReadAccess property to true. Subsequently, we will assess the discrepancies by executing the command cdk diff.
So now our code would look like the below
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
export class Mys3CdkStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const s3DemoBucket= new s3.Bucket(this,'s3demobucket001',{
bucketName:'demosbucket0123',
versioned:true,
publicReadAccess:true
})
}
}
After executing cdk diff command
Step 10: Destroying the app’s resources
cdk destory
After executing cdk destroy command our Mys3CdkStack will be automatically deleted.