AWS S3 bucket creation with Terraform
AWS S3 is simple storage service which is scalable, high speed, web-based cloud storage service designed for online backup and archiving of data and apps.
“Store and retrieve any amount of data anytime from anywhere”
Steps to create S3 Bucket
Install Terraform: Ensure that Terraform is installed on your machine. You can download it from the official Terraform website and follow the installation instructions for your operating system.
Set Up AWS Credentials: Configure your AWS credentials. This can be done by setting environment variables (
AWS_ACCESS_KEY_ID
andAWS_SECRET_ACCESS_KEY
) or by using the AWS CLI to configure your credentials file.Create a Terraform Configuration File: Create a new directory for your Terraform project and inside it, create a file named
main.tf
. This file will contain your Terraform configuration.Define the Terraform Block: In
main.tf
, start by defining the Terraform block to specify the required providers. This ensures that Terraform uses the correct provider and version.terraform { required_providers { aws = { source = "hashicorp/aws" version = "5.54.1" } } }
Configure the AWS Provider: Specify the AWS provider and the region where you want to create the resources.
provider "aws" { region = "eu-north-1" }
Define the S3 Bucket Resource: Add the resource block to create an S3 bucket. Specify the bucket name in the configuration.
resource "aws_s3_bucket" "demo-bucket" { bucket = "demo-bucket-amit12345" }
Define the S3 Object Resource: After defining the S3 bucket, add a resource block to upload an object to the bucket. Specify the source file and the key (name) for the object in the configuration.
resource "aws_s3_object" "bucket-data" { bucket = aws_s3_bucket.demo-bucket.bucket source = "./myfile.txt" key = "mydata.txt" }
Initialize Terraform: Run
terraform init
in your project directory to initialize Terraform. This command downloads the necessary provider plugins.Plan the Deployment: Use
terraform plan
to see what changes Terraform will make to your infrastructure. This step helps you verify that the configuration is correct.Apply the Configuration: Execute
terraform apply
to create the S3 bucket. Terraform will prompt you to confirm the action before proceeding.Verify the S3 Bucket: After the apply command completes, verify that the S3 bucket has been created in the AWS Management Console under the specified region.