I'm working on a terraform module which creates a load balancer amongst other resources. I would like to attach a security group to the load balancer, but only if a a certain variable is equal to "all" OR "gw".
I currently have a count argument in place for the security group itself:
resource "aws_security_group" "akamai_sg" {
count = var.domain_name_suffix == "all" || var.domain_name_suffix == "gw" ? 1 : 0
name = "akamai-pl-sg"
description = "Manage access from Akamai to ${var.environment} alb"
vpc_id = var.vpc_id
tags = merge(var.common_tags, tomap({ "Name" = "akamai-pl-sg" }))
revoke_rules_on_delete = true
}
This means that the security group will only be created if the domain_name_suffix is set to "all" or "gw".
I would like this same functionality for attaching this security group to the ALB. However, I still want to create the ALB regardless of this variable, it is just the security group attachment which I want to be dependent.
Currently I have this configuration for my ALB:
resource "aws_lb" "internal" {
name = "${var.environment}-${var.domain_name_suffix}"
internal = true
load_balancer_type = "application"
security_groups = [aws_security_group.alb_sg.id, aws_security_group.akamai_sg.id]
subnets = var.alb_subnets
idle_timeout = var.alb_idle_timeout
tags = var.common_tags
drop_invalid_header_fields = true
dynamic "access_logs" {
for_each = var.alb_access_logging_enabled == true ? [var.alb_access_logging_enabled] : []
content {
bucket = var.alb_access_logging_bucket
enabled = true
prefix = "internal"
}
}
}
However, this results in an error: "Error: Missing resource instance key on .terraform/modules/comm_common/alb.tf line 5, in resource "aws_lb" "internal": 5: security_groups = [aws_security_group.alb_sg.id, aws_security_group.akamai_sg.id] Because aws_security_group.alb_sg has "count" set, its attributes must be accessed on specific instances. For example, to correlate with indices of a referring resource, use: aws_security_group.alb_sg[count.index]"
When I add in this [count.index] to the ALB security group reference, I still get the same error.
CodePudding user response:
Could you try the same condition in security_groups field as well? but the value would be a list with two items if condition is true and with one item if condition is false?
resource "aws_lb" "internal" {
name = "${var.environment}-${var.domain_name_suffix}"
internal = true
load_balancer_type = "application"
security_groups = var.domain_name_suffix == "all" || var.domain_name_suffix == "gw" ? [aws_security_group.alb_sg.id, aws_security_group.akamai_sg.id] : [aws_security_group.alb_sg.id]
subnets = var.alb_subnets
idle_timeout = var.alb_idle_timeout
...
}