Day 67 - AWS S3 Bucket Creation and Management

Day 67 - AWS S3 Bucket Creation and Management

AWS S3 Bucket

Amazon S3 (Simple Storage Service) is an object storage service that offers industry-leading scalability, data availability, security, and performance. It can be used for a variety of use cases, such as storing and retrieving data, hosting static websites, and more.

In this task, you will learn how to create and manage S3 buckets in AWS.

Create an S3 bucket using Terraform.

terraform.tf

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

providers.tf

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

s3.tf

resource "aws_s3_bucket" "devops_bucket" {
  bucket = "devopsbucketday67"

  versioning {
    enabled = true
  }
}

Use a unique name for the S3 bucket and make sure you provide access to the S3 bucket for the IAM User

Navigate to the AWS Management Console and open the S3 service

Configure the bucket to allow public read access.

Create a file named public_access.tf. This will hold the configuration to grant public access to your bucket

resource "aws_s3_bucket_public_access_block" "example" {
  bucket                     = aws_s3_bucket.devops_bucket.id
  block_public_acls          = false
  block_public_policy        = false
  ignore_public_acls         = false
  restrict_public_buckets    = false
}

resource "aws_s3_bucket_acl" "bucket_acl" {
  bucket = aws_s3_bucket.devops_bucket.id
  acl    = "public-read"
}
  • Open the AWS Management Console and navigate to the S3 service.

  • Find your bucket, devopsbucketday67, and select it.

  • Choose the "Permissions" tab > Object ownership > Edit

  • Check "ACL enabled" and select "Bucket owner preferred".

  • Click on Save changes

Now use terraform commands after creating public_access.tf

Create an S3 bucket policy that allows read-only access to a specific IAM user or role.

Iam.tf

resource "aws_s3_bucket_policy" "bucket_policy" {
  bucket = aws_s3_bucket.devops_bucket.id
  policy = data.aws_iam_policy_document.allow_read_only_access.json
}

data "aws_iam_policy_document" "allow_read_only_access" {
  statement {
    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::455425213083:user/terraform"]
    }

    actions = [
      "s3:GetObject",
      "s3:ListBucket",
    ]

    resources = [
      aws_s3_bucket.devops_bucket.arn,
      "${aws_s3_bucket.devops_bucket.arn}/*",
    ]
  }
}

Make sure to replace "arn:aws:iam::455425213083:user/terraform" with the identifier of the IAM user or role you want to grant read-only access

Now go back to IAM and check the USERs polices

Enable versioning on the S3 bucket.

resource "aws_s3_bucket" "devops_bucket" {
  bucket = "devopsbucketday67"

  versioning {
    enabled = true
  }
}

Resources

Terraform S3 bucket resource

Good luck and happy learning!