diff --git a/modules/nat-gateways/main.tf b/modules/nat-gateways/main.tf index 8a25886d..aa759eb8 100644 --- a/modules/nat-gateways/main.tf +++ b/modules/nat-gateways/main.tf @@ -9,21 +9,32 @@ * */ +locals { + total_nat_count = var.enable_nat_creation ? var.nat_count : 0 + total_new_nat = var.enable_nat_creation ? (length(var.nat_eip) == 0 ? local.total_nat_count : 0) : 0 + nat_ids = var.enable_nat_creation ? (length(var.nat_eip) == 0 ? aws_eip.nat.*.id : values(data.aws_eip.nat)[*].id) : [] +} + # AWS Managed NAT Gateways resource "aws_eip" "nat" { - count = var.nat_count + count = local.total_new_nat vpc = true } +data "aws_eip" "nat" { + for_each = length(var.nat_eip) != 0 ? toset(var.nat_eip) : toset([]) + public_ip = each.value +} + data "aws_subnet" "public" { count = length(var.public_subnet_ids) id = element(var.public_subnet_ids, count.index) } resource "aws_nat_gateway" "nat" { - count = var.nat_count + count = local.total_nat_count subnet_id = element(data.aws_subnet.public.*.id, count.index) - allocation_id = element(aws_eip.nat.*.id, count.index) + allocation_id = element(local.nat_ids, count.index) tags = merge( { @@ -35,7 +46,7 @@ resource "aws_nat_gateway" "nat" { # Route tables. One per NAT gateway. resource "aws_route_table" "private" { - count = var.nat_count + count = local.total_nat_count vpc_id = var.vpc_id tags = merge( @@ -47,15 +58,15 @@ resource "aws_route_table" "private" { } resource "aws_route" "private_nat_gateway" { - count = var.nat_count - route_table_id = aws_route_table.private[count.index].id - destination_cidr_block = "0.0.0.0/0" - nat_gateway_id = element(aws_nat_gateway.nat.*.id, count.index) + count = local.total_nat_count + route_table_id = aws_route_table.private[count.index].id + destination_cidr_block = "0.0.0.0/0" + nat_gateway_id = element(aws_nat_gateway.nat.*.id, count.index) } +# https://github.com/terraform-providers/terraform-provider-aws/pull/6999 resource "aws_route_table_association" "private-rta" { - count = length(var.private_subnet_ids) + count = var.enable_nat_creation ? length(var.private_subnet_ids) : 0 subnet_id = element(var.private_subnet_ids, count.index) route_table_id = element(aws_route_table.private.*.id, count.index) } - diff --git a/modules/nat-gateways/variables.tf b/modules/nat-gateways/variables.tf index 92cc7edf..c8a85504 100644 --- a/modules/nat-gateways/variables.tf +++ b/modules/nat-gateways/variables.tf @@ -29,3 +29,14 @@ variable "extra_tags" { type = map(string) } +variable "enable_nat_creation" { + default = true + description = "boolean, enable/disable NAT creation" + type = string +} + +variable "nat_eip" { + description = "The public IP of the specific EIP to retrieve. If non empty, this list should have same number of EIP as the number of var.public_subnet_ids." + type = list(string) + default = [] +}