I create ALBs based on a JSON file where I have a variable public which can be yes or no.
As below:
[
{
"service-name": "test1",
"public" : "yes"
},
{
"service-name": "test2",
"public" : "no"
}
]
I then use this JSON to create ALBs, with the snippet below, which works fine.
resource "aws_lb_listener" "lb_listener" {
count = length(var.services)
load_balancer_arn = aws_lb.some_alb[count.index].arn
port = 80
protocol = "HTTP"
default_action {
target_group_arn = aws_lb_target_group.some_target[count.index].arn
type = "forward"
}
}
What I am after is to have a dynamic default_action based on the public variable. I want it to redirect to HTTPS when public==yes and forward to the target_group when public==no.
I tried this:
resource "aws_lb_listener" "lb_listener" {
count = length(var.services)
load_balancer_arn = aws_lb.some-alb[count.index].arn
port = 80
protocol = "HTTP"
//Public ALB redirects to port 443
dynamic "default_action" {
for_each = [
for i in var.services : i
if var.services[i].public == "yes"
]
type = "redirect"
redirect {
port = "443"
protocol = "HTTPS"
status_code = "HTTP_301"
}
}
//Private just forwards to the target group
dynamic "default_action" {
for_each = [
for i in var.services : i
if var.services[i].public == "no"
]
default_action {
target_group_arn = aws_lb_target_group.some_target[count.index].arn
type = "forward"
}
}
}
But I got the error:
At least 1 "default_action" blocks are required.
Blocks of type "redirect" are not expected here.
Will appreciate your help. Thanks!
Based on the comments:
Instead of default_action
, it should be content
.