|
| 1 | +# Create a single subnet for the NAT Gateway to live in |
| 2 | +# routed to the outside world |
| 3 | + |
| 4 | +data "aws_vpc" "current" { |
| 5 | + id = var.vpc_id |
| 6 | +} |
| 7 | + |
| 8 | +# Create a subnet in us-east-1a in the |
| 9 | +# CIDR block specified by the inputs |
| 10 | +# So that the CIDR block is different than |
| 11 | +# others in this VPC |
| 12 | +resource "aws_subnet" "mod" { |
| 13 | + count = var.uses_nat_gateway ? 1 : 0 |
| 14 | + availability_zone = var.availability_zone |
| 15 | + cidr_block = cidrsubnet( |
| 16 | + data.aws_vpc.current.cidr_block, |
| 17 | + var.subnet_cidr_newbits, |
| 18 | + var.subnet_cidr_netnum_offset + 1, |
| 19 | + ) |
| 20 | + map_public_ip_on_launch = true |
| 21 | + tags = var.tags |
| 22 | + vpc_id = var.vpc_id |
| 23 | +} |
| 24 | + |
| 25 | + |
| 26 | +# ElasticIP address for use with the NAT Gateway |
| 27 | +resource "aws_eip" "nat-gw-eip" { |
| 28 | + count = var.uses_nat_gateway ? 1 : 0 |
| 29 | + vpc = true |
| 30 | + tags = var.tags |
| 31 | +} |
| 32 | + |
| 33 | +# NAT Gateway in the first (only) subnet |
| 34 | +resource "aws_nat_gateway" "gw" { |
| 35 | + count = var.uses_nat_gateway ? 1 : 0 |
| 36 | + allocation_id = aws_eip.nat-gw-eip[0].id |
| 37 | + subnet_id = aws_subnet.mod[0].id |
| 38 | + |
| 39 | + tags = merge( |
| 40 | + var.tags, |
| 41 | + { |
| 42 | + Name = var.name |
| 43 | + }, |
| 44 | + ) |
| 45 | + depends_on = [var.internet_gateway_id] |
| 46 | +} |
| 47 | + |
| 48 | +resource "aws_route_table" "mod" { |
| 49 | + count = var.uses_nat_gateway ? 1 : 0 |
| 50 | + tags = var.tags |
| 51 | + vpc_id = var.vpc_id |
| 52 | +} |
| 53 | + |
| 54 | +resource "aws_route" "mod" { |
| 55 | + count = var.uses_nat_gateway ? 1 : 0 |
| 56 | + destination_cidr_block = "0.0.0.0/0" |
| 57 | + gateway_id = var.internet_gateway_id |
| 58 | + route_table_id = aws_route_table.mod[0].id |
| 59 | +} |
| 60 | + |
| 61 | +resource "aws_route_table_association" "mod" { |
| 62 | + count = var.uses_nat_gateway ? 1 : 0 |
| 63 | + route_table_id = aws_route_table.mod[0].id |
| 64 | + subnet_id = aws_subnet.mod[0].id |
| 65 | +} |
0 commit comments