From 460264000e817ab2fe163ef0c93da2c563fa1673 Mon Sep 17 00:00:00 2001 From: tomarnebra <160740012+tomarnebra@users.noreply.github.com> Date: Tue, 14 May 2024 16:12:54 +0200 Subject: [PATCH] Implement loadbalancer stickiness (#18) * Add support for activating stickiness in the loadbalancer --- main.tf | 25 +++++++++++++++++++++++-- variables.tf | 16 ++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/main.tf b/main.tf index e148e67..ef24862 100644 --- a/main.tf +++ b/main.tf @@ -238,6 +238,16 @@ resource "aws_lb_target_group" "service" { } } + dynamic "stickiness" { + for_each = var.lb_stickiness[*] + content { + type = var.lb_stickiness.type + enabled = var.lb_stickiness.enabled + cookie_duration = var.lb_stickiness.cookie_duration + cookie_name = var.lb_stickiness.cookie_name + } + } + # NOTE: TF is unable to destroy a target group while a listener is attached, # therefor we have to create a new one before destroying the old. This also means # we have to let it have a random name, and then tag it with the desired name. @@ -257,8 +267,19 @@ resource "aws_lb_listener_rule" "service" { listener_arn = each.value.listener_arn action { - type = "forward" - target_group_arn = aws_lb_target_group.service[each.key].arn + type = "forward" + forward { + target_group { + arn = aws_lb_target_group.service[each.key].arn + } + dynamic "stickiness" { + for_each = var.lb_stickiness.enabled ? [1] : [] + content { + enabled = true + duration = var.lb_stickiness.cookie_duration + } + } + } } dynamic "condition" { diff --git a/variables.tf b/variables.tf index 384394e..9718a7c 100644 --- a/variables.tf +++ b/variables.tf @@ -252,3 +252,19 @@ variable "custom_metrics" { })) default = [] } + +variable "lb_stickiness" { + description = "Bind a user's session to a specific target" + nullable = false + type = object({ + type = string + enabled = optional(bool, null) + cookie_duration = optional(number, null) + cookie_name = optional(string, null) + }) + default = { + type = "lb_cookie" + enabled = false + cookie_duration = 86400 # 24h in seconds + } +} \ No newline at end of file