Last active
July 31, 2022 22:35
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A test script: