Ravindra BagaleCourses & study guides Track your progress

Labs · DevOps

Lab: Create a Private S3 Bucket with Terraform with Public Access Blocked, Encryption, Versioning, a Lifecycle Rule and a TLS-Only Policy

Beginner30 minTerraform 1.6+ · AWS CLI v2 · An AWS account

Course: DevOps · Chapter 44: Terraform AWS Guides EC2 RDS S3 Security Groups IAM ALB and Auto Scaling · Lesson: 44.3 How to create a secure S3 bucket with Terraform

Lesson 44.3 explains every resource; this lab runs it and proves versioning works.

Chala mitrano! Ek chukicha click ani bucket public. Aaj pratyek safety setting code madhe, review sobat.

Suppose we are…

Suppose we are on an Instagram-style media team that stores uploaded profile pictures in S3. One wrong click in the console can make a bucket public, and old versions of files pile up forever. In AWS provider 5.x every bucket setting is its own resource, so each safety setting is visible in review. This guide builds a private, encrypted, versioned bucket with a cleanup rule and a policy that refuses plain HTTP.

Goal of this lab

By the end you will have:

  • A bucket with all four public-access blocks on, encryption and versioning.
  • Two versions of the same file listed.
  • Everything destroyed.

What you need

  • Terraform 1.6 or newer (terraform version).
  • AWS CLI v2 signed in to your own AWS account with an IAM user or SSO role that may create these resources (aws sts get-caller-identity works). Never use the root user, and never paste access keys into .tf files.
  • Region Mumbai (ap-south-1) is used; change region if you prefer another.
  • 30 minutes.

Cost and cleanup

An S3 bucket with a few small files costs almost nothing. Small charges are possible even on the free tier. Finish the lab in one sitting and always run the Clean up part at the end.

Part 1: Create the project files

  1. Create the folder:

    mkdir s3-guide && cd s3-guide
    

    What you should see: after the next steps, this layout:

    s3-guide/
    ├── versions.tf
    ├── variables.tf
    ├── main.tf
    └── outputs.tf
    
  2. Create versions.tf:

    versions.tf

    terraform {
      required_version = ">= 1.6"
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 5.0"
        }
      }
    }
    
    provider "aws" {
      region = var.region
    }
    
  3. Create variables.tf:

    variables.tf

    variable "region" {
      type    = string
      default = "ap-south-1"
    }
    
  4. Create main.tf:

    main.tf

    resource "aws_s3_bucket" "assets" {
      bucket_prefix = "guide-assets-"
      force_destroy = true
    }
    
    resource "aws_s3_bucket_versioning" "assets" {
      bucket = aws_s3_bucket.assets.id
      versioning_configuration {
        status = "Enabled"
      }
    }
    
    resource "aws_s3_bucket_server_side_encryption_configuration" "assets" {
      bucket = aws_s3_bucket.assets.id
      rule {
        apply_server_side_encryption_by_default {
          sse_algorithm = "AES256"
        }
      }
    }
    
    resource "aws_s3_bucket_public_access_block" "assets" {
      bucket                  = aws_s3_bucket.assets.id
      block_public_acls       = true
      block_public_policy     = true
      ignore_public_acls      = true
      restrict_public_buckets = true
    }
    
    resource "aws_s3_bucket_lifecycle_configuration" "assets" {
      bucket = aws_s3_bucket.assets.id
      rule {
        id     = "tidy"
        status = "Enabled"
        filter {}
        noncurrent_version_expiration {
          noncurrent_days = 30
        }
        abort_incomplete_multipart_upload {
          days_after_initiation = 7
        }
      }
      depends_on = [aws_s3_bucket_versioning.assets]
    }
    
    data "aws_iam_policy_document" "tls_only" {
      statement {
        sid     = "DenyInsecureTransport"
        effect  = "Deny"
        actions = ["s3:*"]
        resources = [
          aws_s3_bucket.assets.arn,
          "${aws_s3_bucket.assets.arn}/*",
        ]
        principals {
          type        = "*"
          identifiers = ["*"]
        }
        condition {
          test     = "Bool"
          variable = "aws:SecureTransport"
          values   = ["false"]
        }
      }
    }
    
    resource "aws_s3_bucket_policy" "assets" {
      bucket     = aws_s3_bucket.assets.id
      policy     = data.aws_iam_policy_document.tls_only.json
      depends_on = [aws_s3_bucket_public_access_block.assets]
    }
    
  5. Create outputs.tf:

    outputs.tf

    output "bucket_name" {
      value = aws_s3_bucket.assets.bucket
    }
    

Part 2: Init, check and plan

  1. Download the AWS provider:

    terraform init
    

    What you should see: Terraform has been successfully initialized!

  2. Format and validate:

    terraform fmt
    terraform validate
    

    What you should see: Success! The configuration is valid.

  3. Plan and read the counts:

    terraform plan
    

    What you should see: Plan: 6 to add, 0 to change, 0 to destroy.

Part 3: Apply and test

  1. Apply and type yes:

    terraform apply
    
  2. Upload a test file twice and list its versions:

    B=$(terraform output -raw bucket_name)
    echo hi > a.txt && aws s3 cp a.txt s3://$B/
    echo hello > a.txt && aws s3 cp a.txt s3://$B/
    aws s3api list-object-versions --bucket $B --prefix a.txt --query "Versions[].[VersionId,IsLatest]"
    

    What you should see: two version ids, one marked true (latest).

  3. Prove public access is blocked:

    aws s3api get-public-access-block --bucket $B
    

    What you should see: all four settings true.

Clean up: destroy everything

  1. Delete everything this lab created. Type yes when asked:

    terraform destroy
    

    What you should see: Destroy complete! Resources: 6 destroyed. (force_destroy empties the versioned bucket in this lab).

Ravindra Bagale's Tip

Use bucket_prefix in labs and modules. Bucket names are global across all AWS accounts, and a fixed name will clash sooner or later.

Common mistakes

MistakeWhat happensFix
Error: creating S3 Bucket (my-bucket): BucketAlreadyExistsApply stopsBucketAlreadyExists means a fixed name is taken somewhere in the world; use bucket_prefix. AccessDenied on the policy means the policy you wrote would make the bucket public; keep the Deny-only TLS policy, or remove the Allow to "*".
Leaving force_destroy = true on a real data bucketOne destroy deletes all dataUse it only in labs
Skipping terraform planSurprise changes or deletesAlways read the plan counts before apply

Self-check checklist

0 of 4 done

Try-at-home challenge

Try adding a bucket policy statement that allows s3:GetObject to "*" and apply. Read the AccessDenied error and explain which setting blocked it. Then remove the statement.

Samajla ka? Private by default, every setting in review. Aata pudhe jaauya load balancer.