Skip to content

Instantly share code, notes, and snippets.

@guoqiao
Last active July 31, 2022 22:35
Show Gist options
  • Save guoqiao/b458050c267a1dcef3514ebab0ac0104 to your computer and use it in GitHub Desktop.
Save guoqiao/b458050c267a1dcef3514ebab0ac0104 to your computer and use it in GitHub Desktop.
Use Terraform to create public AWS S3 bucket via policy and disable ACL
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "bucket" {
# change this to your own bucket name
bucket = "my-test-bucket"
# allow to destroy bucket even when not empty
force_destroy = true
}
resource "aws_s3_bucket_public_access_block" "block" {
bucket = aws_s3_bucket.bucket.id
block_public_acls = true # do not allow to create (new) public acls
ignore_public_acls = true # ignore (existing) public acls
block_public_policy = false # do now allow to create (new) public policy
restrict_public_buckets = false # do not allow access to (existing) public buckets (via policy)
}
# this doesn't make object public
# resource "aws_s3_bucket_acl" "acl" {
# bucket = aws_s3_bucket.bucket.id
# acl = "public-read"
# }
resource "aws_s3_bucket_ownership_controls" "ownership" {
bucket = aws_s3_bucket.bucket.id
rule {
# ObjectWriter
# BucketOwnerPreferred
# BucketOwnerEnforced: bucket owner will be object owner, ACLs disabled, only policies work.
object_ownership = "BucketOwnerEnforced"
}
}
resource "aws_s3_bucket_policy" "policy" {
bucket = aws_s3_bucket.bucket.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Sid = "PublicReadGetObject"
Effect = "Allow"
Principal = "*"
Action = ["s3:GetObject"]
Resource = ["${aws_s3_bucket.bucket.arn}/*"]
},
]
})
}
# ref: https://docs.aws.amazon.com/AmazonS3/latest/userguide/acls.html
@guoqiao
Copy link
Author

guoqiao commented Jul 31, 2022

A test script:

> $ cat s3-upload-and-download.sh
#!/bin/bash

# upload a file to s3 bucket with aws cli, and download it with wget, to verify it's public
# usage: ./s3-upload-and-download.sh /path/to/file

set -xue

FILE_PATH=$1
FILE_NAME=$(basename $1)
BUCKET_NAME=my-test-bucket

aws s3 cp $FILE_PATH s3://${BUCKET_NAME}
wget https://${BUCKET_NAME}.s3.amazonaws.com/${FILE_NAME}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment