Skip to content

Commit

Permalink
Add access logging for load-balancer
Browse files Browse the repository at this point in the history
  • Loading branch information
manics committed Feb 6, 2025
1 parent 173b2c0 commit cac6f0f
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
62 changes: 62 additions & 0 deletions ecs-cluster/keycloak.tf
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,62 @@ resource "aws_security_group" "ecs-task-keycloak" {
}
}

# Load balancer logs
resource "aws_s3_bucket" "alb-logs" {
bucket_prefix = "${var.name}-logs-"
}

data "aws_iam_policy_document" "alb-logs" {
statement {
principals {
type = var.loadbalancer-logging-iam-principal.type
identifiers = [var.loadbalancer-logging-iam-principal.identifier]
}
actions = [
"s3:PutObject"
]
resources = [
"${aws_s3_bucket.alb-logs.arn}/access-logs/*"
]
}
}

resource "aws_s3_bucket_policy" "alb-logs" {
bucket = aws_s3_bucket.alb-logs.id
policy = data.aws_iam_policy_document.alb-logs.json
}

resource "aws_s3_bucket_server_side_encryption_configuration" "alb-logs-encryption" {
bucket = aws_s3_bucket.alb-logs.id

rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}

resource "aws_s3_bucket_versioning" "alb-logs" {
bucket = aws_s3_bucket.alb-logs.id
versioning_configuration {
status = "Enabled"
}
}

resource "aws_s3_bucket_lifecycle_configuration" "alb-logs" {
bucket = aws_s3_bucket.alb-logs.id
rule {
id = "delete-access-logs-${var.expire-access-logs-days}-days"
filter {
prefix = "access-logs/"
}
expiration {
days = var.expire-access-logs-days
}
status = "Enabled"
}
}

# Load balancer

resource "aws_lb" "keycloak" {
Expand All @@ -96,6 +152,12 @@ resource "aws_lb" "keycloak" {
enable_deletion_protection = true

preserve_host_header = true

access_logs {
bucket = aws_s3_bucket.alb-logs.id
prefix = "access-logs"
enabled = true
}
}

resource "aws_alb_target_group" "keycloak" {
Expand Down
18 changes: 18 additions & 0 deletions ecs-cluster/variables.tf
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,24 @@ variable "desired-count" {
default = 1
}

variable "loadbalancer-logging-iam-principal" {
type = map(string)
description = "IAM principal type and identifier for the elastic load balancer logger. This is complicated, see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/enable-access-logging.html#attach-bucket-policy"

# For eu-west-2 this is a hard-coded AWS account ID belonging to AWS
# and not Service: logdelivery.elasticloadbalancing.amazonaws.com
default = {
type = "AWS"
identifier = "arn:aws:iam::652711504416:root"
}
}

variable "expire-access-logs-days" {
type = number
description = "Automatically delete access logs after this number of days"
default = 3653
}

variable "default-tags" {
type = map(any)
default = {
Expand Down

0 comments on commit cac6f0f

Please sign in to comment.