The issue is creating a Terraform resource using a for_each and then passing one of it’s value into a dynamic variable.
Input data –
lb_rules = tolist([
{
"host" = "dest-1.example.uk"
"name" = "redirect-host"
"path" = "/"
"path_pattern" = tolist([
"",
])
host_header" = tolist([
"origin-1.example.uk",
])
"port" = "#{port}"
"priority" = 5
"protocol" = "#{protocol}"
"status_code" = "HTTP_301"
"type" = "dev"
},
{
"host" = "dest-2.example.uk"
"name" = "redirect-all"
"path" = "/"
"path_pattern" = tolist([
"/*",
])
host_header" = tolist([
"origin-2.example.uk",
])
"port" = "#{port}"
"priority" = 100
"protocol" = "#{protocol}"
"status_code" = "HTTP_301"
"type" = "stage"
}
])
And then feed that data into the following resource –
resource "aws_lb_listener_rule" "redirect" {
for_each = { for r in var.lb_rules : r.name => r }
listener_arn = aws_lb_listener.default.arn
priority = each.value.priority
action {
type = "redirect"
redirect {
protocol = each.value.protocol
host = each.value.host
port = each.value.port
path = each.value.path
status_code = each.value.status_code
}
}
condition {
dynamic "host_header" {
for_each = each.value.host_header
content {
values = host_header.value.*.host_header
}
}
}
tags = {
Name = each.value.name
}
}
The above works without the dynamic variable.
The error for the dynamic variable is
Can't access attributes on a primitive-typed value (string).
Is there anything obvious missing ?
2
Answers
Thank you anhhq, I had to tweak your idea and this is the final work solution -
If the value origin_host_header doesn't exist, it is passed in as null, therefore the dynamic var is not created.
Try: