Enabling Access Logs for AWS ELB (ALB) with Terraform



This content originally appeared on DEV Community and was authored by Atsushi Suzuki

While attempting to enable access logs for an Application Load Balancer (ALB) in AWS, I encountered a permissions error due to insufficient S3 bucket permissions. The error highlighted the need for proper bucket policy settings, which I had initially overlooked.

│ Error: modifying ELBv2 Load Balancer (arn:aws:elasticloadbalancing:ap-northeast-1:************:loadbalancer/app/alb-prod/fbbd3f2304ff9285) attributes: InvalidConfigurationRequest: Access Denied for bucket: logs-prod. Please check S3 bucket permission

Upon reviewing the official documentation, I realized that I had missed configuring the bucket policy.

Official AWS Documentation on Enabling Access Logging

Here’s how I resolved the error using Terraform, which might be helpful if you encounter a similar issue.

S3 Bucket Setup

I used the bucket name logs-prod and the prefix alb/alb-prod. The number 582318560864 represents the AWS account ID for ELB in the Tokyo region. Replace <account-id> with your own AWS account ID.

resource "aws_s3_bucket" "logs_prod" {
  bucket = "logs-prod"

  tags = {
    Environment = "prod"
  }
}

resource "aws_s3_bucket_policy" "logs_prod_policy" {
  bucket = aws_s3_bucket.logs_prod.id

  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::582318560864:root"
      },
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::logs-prod/alb/alb-prod/AWSLogs/<account-id>/*"
    }
  ]
}
POLICY
}

ALB Configuration

I added an access_logs block to the ALB setup to enable logging, specify the bucket name, and set the prefix.

resource "aws_lb" "alb_prod" {
  name                       = "alb-prod"
  internal                   = false
  load balancer_type         = "application"
  security_groups            = [var.security_group_elb_sg_id]
  subnets                    = [var.subnet_public_1a_id, var.subnet_public_1c_id]
  enable_deletion_protection = true
  preserve_host_header       = true

  access_logs {
    enabled  = true
    bucket  = "logs-prod"
    prefix  = "alb/alb-prod"
  }

  tags = {
    Environment = "prod"
  }
}

By applying these settings, I ensured correct and secure logging from the ALB to the specified S3 bucket.


This content originally appeared on DEV Community and was authored by Atsushi Suzuki