To achieve the desired outcome—using multiple NAT Gateways while reusing the existing EIPs—you’ll need to modify your Terraform configuration to handle the EIPs separately from the terraform-aws-modules/vpc module. Here’s a step-by-step guide:
1. Extract Existing EIPs
You need to retrieve the existing EIPs so they can be referenced outside the terraform-aws-modules/vpc module. Since the module currently manages the EIPs, you need to ensure they are not recreated or modified when you change the configuration. Use the Terraform terraform state commands to reference and extract these EIPs:
terraform state list
Locate the EIPs managed by the module (e.g., something like module.vpc.aws_eip.nat). Then use the terraform state mv command to move the resources out of the module:
terraform state mv 'module.vpc.aws_eip.nat[0]' 'aws_eip.nat_1'
terraform state mv 'module.vpc.aws_eip.nat[1]' 'aws_eip.nat_2'
This will move the resources from the module into your root module so they can be managed independently.
1. Create Standalone EIP Resources
Declare the EIPs explicitly in your Terraform code:
resource "aws_eip" "nat_1" {
id = "eip-xxxxx" # Use the existing EIP ID to avoid recreation
}
resource "aws_eip" "nat_2" {
id = "eip-yyyyy" # Use the existing EIP ID to avoid recreation
}
This ensures that Terraform manages these EIPs independently moving forward.
1. Modify the VPC Module for Multiple NAT Gateways
Update the terraform-aws-modules/vpc module configuration to use multiple NAT Gateways. You can do this by setting one_nat_gateway_per_az = true and passing the EIPs explicitly:
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "x.x.x"
# Other VPC module configurations...
create_eip = false # Prevent the module from creating new EIPs
one_nat_gateway_per_az = true
nat_gateway_eips = [
aws_eip.nat_1.id,
aws_eip.nat_2.id,
# Add more EIPs if needed
]
}
1. Plan and Apply
Run a terraform plan to ensure that your changes don’t recreate or destroy any critical resources, especially the existing EIPs.
terraform plan
Once you’re satisfied, apply the changes:
terraform apply
1. Verify Configuration
After applying the changes, verify that the NAT Gateways are correctly configured in each AZ and that they are using the appropriate EIPs.
Summary
• Use terraform state mv to extract EIPs from the module.
• Define the EIPs as standalone resources.
• Update the terraform-aws-modules/vpc module to disable EIP creation and use nat_gateway_eips to assign the existing EIPs.
• Test and verify the changes.
This approach avoids recreating NAT Gateways or EIPs, minimizes downtime, and ensures a smooth transition to multiple NAT Gateways.