Open In App

How to Create AWS S3 Bucket Using Terraform?

Last Updated : 25 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

S3 stands for Simple Storage Service. S3 buckets are cloud storage services by Amazon Web Service. It is used to store objects, It consists of data in any format like documents, images, videos, and application code. These are highly scalable.

Prerequisite:

Step 1: Open the cmd if you are in Windows and configure aws using the aws configure command.

aws configure
aws configure

Step 2: After that open a code editor(vs code) and make a file called provider.tf

.tf is the file extension for the terraform file. This file will store the information about the cloud provider, version, and region for the s3 bucket. Use the following code to set the provider, version, and region.

 terraform {
required_providers{
aws={
source = "hashicorp/aws"
version = "4.33.0"
}
}
}

provider "aws"{
#configuration options
region = "us-east-1"
}
provider.tf file and terraform init command

After this open terminal where this file is located and type terraform init to initialize terraform. The Terraform init command prepares the working directory for use with Terraform. It initialises the backend, any child module installation and any plugin installation.

Step 3: Now we have defied our provider.Let's create S3 bucket , make a file called main.tf in the same directory where provider.tf file is located. In this file we have define the resource , bucket name. The bucket name should be unique , here the bucket name is "my-s3-test-bucket02" . Here is the following code :

# Bucket creation
resource "aws_s3_bucket" "my_s3_bucket"{
bucket = "my-s3-test-bucket02"

tags = {
Name = "My bucket"
Enviroment ="Dev"
}
}
main.tf  file and terraform plan command

After this run terraform plan command.The plan command determines the deltas between the current configuration and prior state data.

Step 4: Now you have to run terraform apply command to create a S3 bucket in AWS.

terraform apply
terraform apply command

This command will start create S3 bucket in aws console. After few minutes the bucket has been created.

Step 5 : To confirm that your S3 bucket has been created, head over to the AWS management console then go to S3 then Buckets. You will see that our bucket "my-s3-test-bucket02" has been created.

aws bucket creation

Step 6: If you’d like to clean up this S3 bucket you can run the command terraform destroy in the terminal.

terraform destroy
terrafrom destroy

Similar Reads