Skip to content

Commit

Permalink
Allow passing in EIPs for the NAT Gateways
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelaferreira committed Dec 7, 2017
1 parent 689db6c commit e60ad2a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
20 changes: 18 additions & 2 deletions main.tf
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
terraform {
required_version = ">= 0.10.13" # introduction of Local Values configuration language feature
}

######
# VPC
######
Expand Down Expand Up @@ -152,16 +156,28 @@ 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
}

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)))))}"
Expand Down
11 changes: 11 additions & 0 deletions variables.tf
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit e60ad2a

Please sign in to comment.