diff --git a/main.tf b/main.tf index 6a8a9c942..fa3ac9f3a 100644 --- a/main.tf +++ b/main.tf @@ -1,3 +1,7 @@ +terraform { + required_version = ">= 0.10.13" # introduction of Local Values configuration language feature +} + ###### # VPC ###### @@ -152,8 +156,20 @@ resource "aws_elasticache_subnet_group" "elasticache" { ############## # NAT Gateway ############## +# Workaround for interpolation not being able to "short-circuit" the evaluation of the conditional branch that doesn't end up being used +# Source: https://github.com/hashicorp/terraform/issues/11566#issuecomment-289417805 +# +# The logical expression would be +# +# nat_gateway_ips = var.reuse_nat_ips ? var.external_nat_ip_ids : aws_eip.nat.*.id +# +# but then when count of aws_eip.nat.*.id is zero, this would throw a resource not found error on aws_eip.nat.*.id. +locals { + nat_gateway_ips = "${split(",", (var.reuse_nat_ips ? join(",", var.external_nat_ip_ids) : join(",", aws_eip.nat.*.id)))}" +} + resource "aws_eip" "nat" { - count = "${var.enable_nat_gateway ? (var.single_nat_gateway ? 1 : length(var.azs)) : 0}" + count = "${(var.enable_nat_gateway && !var.reuse_nat_ips) ? (var.single_nat_gateway ? 1 : length(var.azs)) : 0}" vpc = true } @@ -161,7 +177,7 @@ resource "aws_eip" "nat" { resource "aws_nat_gateway" "this" { count = "${var.enable_nat_gateway ? (var.single_nat_gateway ? 1 : length(var.azs)) : 0}" - allocation_id = "${element(aws_eip.nat.*.id, (var.single_nat_gateway ? 0 : count.index))}" + allocation_id = "${element(local.nat_gateway_ips, (var.single_nat_gateway ? 0 : count.index))}" subnet_id = "${element(aws_subnet.public.*.id, (var.single_nat_gateway ? 0 : count.index))}" tags = "${merge(var.tags, map("Name", format("%s-%s", var.name, element(var.azs, (var.single_nat_gateway ? 0 : count.index)))))}" diff --git a/variables.tf b/variables.tf index b3ca52a68..7148bb839 100644 --- a/variables.tf +++ b/variables.tf @@ -65,6 +65,17 @@ variable "single_nat_gateway" { default = false } +variable "reuse_nat_ips" { + description = "Should be true if you don't want EIPs to be created for your NAT Gateways and will instead pass them in via the 'external_nat_ip_ids' variable" + default = false +} + +variable "external_nat_ip_ids" { + description = "List of EIP IDs to be assigned to the NAT Gateways (used in combination with reuse_nat_ips)" + type = "list" + default = [] +} + variable "enable_dynamodb_endpoint" { description = "Should be true if you want to provision a DynamoDB endpoint to the VPC" default = false