DEV Community

Sibelius Seraphini for Woovi

Posted on

Creating a S3 bucket using Terraform

S3 is the de facto and most well-known solution for object storage.
Object storage allows you to store files in a specific bucket and key.

When your application is small, you just need to manage a few S3 buckets, and you can manage them using the AWS UI.

The problem is how to reproduce the same S3 bucket configuration over and over again, and from staging to production.
Each S3 bucket has specific needs.

It is also hard to see how all the S3 buckets are configured or how to change some configurations.

S3 using Terraform

Terraform enables you to declare your infrastructure as code.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 4.0"
    }
  }
  required_version = ">= 1.0"
}

provider "aws" {
  region = "us-east-1"
}

# Create S3 bucket for Terraform state
resource "aws_s3_bucket" "mybucket" {
  bucket = "mybucket"

  force_destroy = false

  tags = {
    Name        = "mybucket"
    Environment = "dev"
    ManagedBy   = "terraform"
  }
}

# Enable versioning (so you can roll back state if needed)
resource "aws_s3_bucket_versioning" "versioning" {
  bucket = aws_s3_bucket.mybucket.id

  versioning_configuration {
    status = "Enabled"
  }
}

# Enable server-side encryption by default
resource "aws_s3_bucket_server_side_encryption_configuration" "sse" {
  bucket = aws_s3_bucket.mybucket.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}

# Block public access
resource "aws_s3_bucket_public_access_block" "block" {
  bucket = aws_s3_bucket.mybucket.id

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}
Enter fullscreen mode Exit fullscreen mode

You just need to type

terraform init
terraform apply
Enter fullscreen mode Exit fullscreen mode

And your S3 bucket is created.

If you modify your Terraform file and run terraform apply , it will show what changed and only apply the modifications.

In Conclusion

Using Terraform to provision your infrastructure can help you go from simple S3 buckets to very complex applications.


Woovi
Woovi is a fintech platform revolutionizing how businesses and developers handle payments in Brazil. Built with a developer-first mindset, Woovi simplifies integration with instant payment methods like Pix, enabling companies to receive payments seamlessly and automate financial workflows.

If you want to work with us, we are hiring!

Top comments (0)