Terraform how to get IP address of aws_lb

More elegent solution using only HCL in Terraform :

data "aws_network_interface" "lb" {
  for_each = var.subnets

  filter {
    name   = "description"
    values = ["ELB ${aws_lb.example_lb.arn_suffix}"]
  }

  filter {
    name   = "subnet-id"
    values = [each.value]
  }
}

resource "aws_security_group" "lb_sg" {
  vpc_id = var.vpc_id

  ingress {
    from_port   = 0
    to_port     = 0
    protocol    = "tcp"
    cidr_blocks = formatlist("%s/32", [for eni in data.aws_network_interface.lb : eni.private_ip])
    description = "Allow connection from NLB"
  }
}

Source : https://github.com/terraform-providers/terraform-provider-aws/issues/3007

Hope this helps.


The solution from @user1297406 leads to an exeption. data.aws_network_interface.lb is tuple with 2 elements. Correct syntax is:

data "aws_network_interface" "lb" {
count = length(var.vpc_private_subnets)

  filter {
    name   = "description"
    values = ["ELB ${aws_alb.lb.arn_suffix}"]
  }
  filter {
    name   = "subnet-id"
    values = [var.vpc_private_subnets[count.index]]
  }
}


resource "aws_security_group_rule" "lb_sg" {
  from_port         = 0
  protocol          = "TCP"
  to_port           = 0
  type              = "ingress"
  cidr_blocks = formatlist("%s/32", data.aws_network_interface.lb.*.private_ip)
}