The aws_lb
resource has a subnet_mapping
block which allows you to specify an Elastic IP per subnet that the network load balancer exists in.
An absolutely minimal example looks something like this:
resource "aws_eip" "lb" {
vpc = true
}
resource "aws_lb" "network" {
name = "test-lb-tf"
load_balancer_type = "network"
subnet_mapping {
subnet_id = "${var.subnet_id}"
allocation_id = "${aws_eip.lb.id}"
}
}
Obviously you'll probably want to run the load balancer in multiple subnets so you'd probably use something like this:
variable "vpc" {}
data "aws_vpc" "selected" {
tags {
Name = "${var.vpc}"
}
}
data "aws_subnet_ids" "public" {
vpc_id = "${data.aws_vpc.selected.id}"
tags {
Tier = "public"
}
}
resource "aws_eip" "lb" {
count = "${length(data.aws_subnet_ids.public)}"
vpc = true
}
resource "aws_lb" "network" {
name = "test-lb-tf"
internal = false
load_balancer_type = "network"
subnet_mapping {
subnet_id = "${data.aws_subnet_ids.public.ids[0]}"
allocation_id = "${aws_eip.lb.id[0]}"
}
subnet_mapping {
subnet_id = "${data.aws_subnet_ids.public.ids[1]}"
allocation_id = "${aws_eip.lb.id[1]}"
}
subnet_mapping {
subnet_id = "${data.aws_subnet_ids.public.ids[2]}"
allocation_id = "${aws_eip.lb.id[2]}"
}
}
The above assumes you have tagged your VPC with a Name
tag and your subnets with a Tier
tag that in this case uses public
as the value for any external facing subnets. It then creates an elastic IP address for each of the public subnets a network load balancer in each of the public subnets, attaching an elastic IP for each of them.