Trying to attach a security group based on a feature flag [TF13]

Hey all,

I know this gruntwork community is filled with terraform pros so I did have a syntax question to ask. In our current use case, we pass a variable that will add a certain security group for our clients. Some have it, most do it. We ended up using a feature flag:

data "aws_security_group" "custom_sg" {
  count = var.enable_custom_sg ? 1 : 0
  tags = {
    Usage = "custom_sg"

My question is, how can I add this security group to an AWS LB or not add it depending on the feature flag? We are currently getting around this by doing a element(concat(),0). However the issue that I am running into is that every terragrunt plan wants to add the security group of " ", this is because it will always add the first element of the concat, and the default is set to “”. It was a workaround, but if anyone has any better ways to solve this I am all ears…

resource "aws_lb" "loadbalancer" {
  name               = "lb-${var.name_prefix}"
  internal           = false
  load_balancer_type = "application"
  # add comment
  security_groups    = concat(["${}", "${var.lb_security_group}", element(concat(data.aws_security_group.custom_sg.*.id, [""]), 0)], "${data.aws_security_groups.sg2.ids}")
  subnets            = "${data.aws_subnet_ids.selected_subnet.ids}"
  idle_timeout       = 180
  enable_cross_zone_load_balancing = true

Any help would be greatly appreciated!

Assuming you’re in the same module, and have access to var.enable_custom_sg where you create the aws_lb resource, you could try this for better readability.

Here I’m using a ternary split across lines. When you use the ternary this way, you must use () to wrap the statement.

security_groups = (
    ? [...list security groups here...]
    : [...list security groups here...]

You may be able to avoid concat by trying this.