@@ -136,6 +136,50 @@ resource "aws_route_table_association" "private" {
136136 route_table_id = aws_route_table. private . id
137137}
138138
139+ # S3 Bucket for ALB Access Logs
140+
141+ resource "aws_s3_bucket" "alb_access_logs" {
142+ # Only create this bucket if logging is enabled
143+ count = var. enable_alb_access_logs ? 1 : 0
144+
145+ # If a specific name is provided, use it. Otherwise, generate a unique name.
146+ bucket = var. alb_access_logs_bucket_name != " " ? var. alb_access_logs_bucket_name : " ${ var . project_prefix } -${ var . environment } -alb-access-logs-${ random_id . this . hex } "
147+
148+ tags = merge (
149+ var. tags ,
150+ {
151+ Name = " ${ var . project_prefix } -${ var . environment } -alb-access-logs"
152+ }
153+ )
154+ }
155+
156+ # This resource is needed to grant the ALB service permission to write to my S3 bucket.
157+ resource "aws_s3_bucket_policy" "alb_access_logs" {
158+ count = var. enable_alb_access_logs ? 1 : 0
159+ bucket = aws_s3_bucket. alb_access_logs [0 ]. id
160+ policy = data. aws_iam_policy_document . alb_access_logs [0 ]. json
161+ }
162+
163+ # This data source constructs the required IAM policy document.
164+ data "aws_iam_policy_document" "alb_access_logs" {
165+ count = var. enable_alb_access_logs ? 1 : 0
166+
167+ statement {
168+ effect = " Allow"
169+ actions = [" s3:PutObject" ]
170+ resources = [" ${ aws_s3_bucket . alb_access_logs [0 ]. arn } /AWSLogs/AWS-ACCOUNT-ID/*" ] # AWS-ACCOUNT-ID will be interpolated by AWS
171+ principals {
172+ type = " AWS"
173+ identifiers = [" elb-account-id.amazonaws.com" ] # This is a placeholder for the regional ELB service account ID
174+ }
175+ }
176+ }
177+
178+ # Need a random_id to ensure the S3 bucket name is unique if not provided
179+ resource "random_id" "this" {
180+ byte_length = 4
181+ }
182+
139183# Application Load Balancer
140184
141185resource "aws_security_group" "alb" {
@@ -187,6 +231,12 @@ resource "aws_lb" "main" {
187231 # Deletion protection should be enabled via a variable for production.
188232 enable_deletion_protection = var. environment == " prod" ? true : false
189233
234+ access_logs {
235+ bucket = var. enable_alb_access_logs ? aws_s3_bucket. alb_access_logs [0 ]. bucket : null
236+ enabled = var. enable_alb_access_logs
237+ prefix = " alb"
238+ }
239+
190240 tags = merge (
191241 var. tags ,
192242 {
0 commit comments