[Terraform] How to enable Amazon S3 ACL access with Terraform code
Hello. This is TK from the Canada office. Canada has had a mild winter this year, and for the first time in my life in Canada, it rained on Christmas (it usually snows).
Now, this time I would like to briefly summarize the errors I had trouble solving while building an AWS server using Terraform, and how to resolve them.
Please note that this article is for people who are already using Terraform, so I will omit the prerequisites such as introducing the tool.
assignment
When I was configuring CloudFront and S3 to store its logs, no error occurred during plan, but the following error occurred during apply.
│ Error: creating CloudFront Distribution: InvalidArgument: The S3 bucket that you specified for CloudFront logs does not enable ACL access: XXX-log-bucket.s3.amazonaws.com │ status code: 400, request id: XXXXXXXXXXXXXX │ │ with XXXXX. aws_cloudfront_distribution.cf_distribution, │ on XXX/cloudfront.tf line XX, in resource "aws_cloudfront_distribution" "cf_distribution": │ ........
It seems that ACL access is not enabled for writing logs from CloudFront to the S3 bucket.
This is because S3 public access blocking has been enabled (ACL disabled) as the new default security setting for Amazon S3 since April 2023.
◎ Reference: https://zenn.dev/devcamp/articles/39ce7fd0272926
So, I tried enabling the ACL on the target S3 bucket directly on the AWS console, and the apply passed without any problems, and the logs were now stored in the corresponding bucket.
I wanted to do the same thing with Terraform code, but I couldn't find a way to write it in Terraform after searching, and even when I asked ChatGPT, he only gave me answers that didn't make sense, so I was at a loss. .
Solution
As I researched and tried various things, I looked up the Terraform description that corresponds to the part " ObjectOwnership changes to BucketOwnerEnforced " in the link above, and found something that seemed to correspond to that.
◎ Reference: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_ownership_controls
Let's add this to the S3 configuration file.
// Log bucket object owner setting ACL enable resource "aws_s3_bucket_ownership_controls" "log_ownership_controls" { bucket = aws_s3_bucket.log.id rule { object_ownership = "BucketOwnerPreferred" } }
The content is "BucketOwnerEnforced (ACL disabled)" unless the object_ownership of the rule is specified, so this is explicitly specified as "BucketOwnerPreferred".
Then, apply passed without any problems, the ACL of the target S3 bucket was enabled, and logs were now stored in that bucket as well.
The above is how to enable AWS ACL access with Terraform.
It's pretty simple to do, but it took me a while to find the correct information, so I hope this article helps if someone is in the same situation.
Click here for articles related to Terraform on our blog .
Thank you for reading.