How to Create NAT Gateway with Terraform: Simple Guide
To create a
nat_gateway in Terraform, define an aws_nat_gateway resource with a subnet ID and an Elastic IP allocation ID. This setup allows private subnets to access the internet securely through the NAT Gateway.Syntax
The aws_nat_gateway resource requires a subnet_id where the NAT Gateway will be placed and an allocation_id of an Elastic IP to assign a public IP. Optionally, you can add tags for identification.
terraform
resource "aws_eip" "nat_eip" { vpc = true } resource "aws_nat_gateway" "example" { allocation_id = aws_eip.nat_eip.allocation_id subnet_id = aws_subnet.public_subnet.id tags = { Name = "example-nat-gateway" } }
Example
This example creates a NAT Gateway in a public subnet with an Elastic IP. It demonstrates how to link the NAT Gateway to the subnet and allocate a public IP for internet access.
terraform
provider "aws" { region = "us-east-1" } resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" } resource "aws_subnet" "public_subnet" { vpc_id = aws_vpc.main.id cidr_block = "10.0.1.0/24" map_public_ip_on_launch = true } resource "aws_eip" "nat_eip" { vpc = true } resource "aws_nat_gateway" "example" { allocation_id = aws_eip.nat_eip.allocation_id subnet_id = aws_subnet.public_subnet.id tags = { Name = "example-nat-gateway" } }
Output
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
Common Pitfalls
- Not creating or associating an Elastic IP before the NAT Gateway causes errors.
- Placing the NAT Gateway in a private subnet prevents it from accessing the internet.
- Forgetting to enable
map_public_ip_on_launchon the public subnet can block internet access.
terraform
/* Wrong: No Elastic IP resource */ resource "aws_nat_gateway" "wrong" { subnet_id = aws_subnet.public_subnet.id } /* Right: Create Elastic IP and reference it */ resource "aws_eip" "nat_eip" { vpc = true } resource "aws_nat_gateway" "correct" { allocation_id = aws_eip.nat_eip.allocation_id subnet_id = aws_subnet.public_subnet.id }
Quick Reference
Remember these key points when creating a NAT Gateway with Terraform:
- Always create an Elastic IP (
aws_eip) for the NAT Gateway. - Place the NAT Gateway in a public subnet with internet access.
- Use the
allocation_idfrom the Elastic IP in the NAT Gateway resource. - Tag resources for easy identification.
Key Takeaways
Create an Elastic IP before the NAT Gateway and link it via allocation_id.
Place the NAT Gateway in a public subnet with internet access enabled.
Enable map_public_ip_on_launch on the public subnet for proper routing.
Tag your NAT Gateway resource for easier management and identification.