Home > Back-end >  Terraform nat gateway AWS
Terraform nat gateway AWS

Time:11-28

I am trying to create nat gateway from terraform by using AWS as provider but subnet_id in resource aws_nat_gateway always gives me error. I am trying to assign public subnet in subnet_id on resource "aws_nat_gateway" "sample_nat_gateway" from variables.tf file but failing in doing so and need support if someone can assist ?

Below is my vpc.tf file of vpc module

 resource "aws_subnet" "public-subnet" {
  for_each = var.prefix
 
  availability_zone_id = each.value["az"]
  cidr_block = each.value["cidr"]
  vpc_id     = aws_vpc.sample_vpc.id     
  tags = {
    Name = "${var.name}-${each.value["az"]}"
 }
}
resource "aws_nat_gateway" "sample_nat_gateway" {
  allocation_id = aws_eip.sample_eip.id
  subnet_id      = ""
  tags = {
    Name = "${var.name}-sample-nat-gateway"
    Environment = var.environment
}
  depends_on = [aws_internet_gateway.sample_igw]
}

variables.tf

variable "prefix" {
   type = map
   default = {
      sub-1 = {
         az = "use2-az1"
         cidr = "10.0.1.0/16"
      }
      sub-2 = {
         az = "use2-az2"
         cidr = "10.0.2.0/24"
      }
   }
}

CodePudding user response:

Subent's can't be empty You have to provide valid subnet id where the NAT is going to be placed. For example:

resource "aws_nat_gateway" "sample_nat_gateway" {
  allocation_id = aws_eip.sample_eip.id

  subnet_id      = aws_subnet.public-subnet["sub-1"].id

  tags = {
    Name = "${var.name}-sample-nat-gateway"
    Environment = var.environment
}
  depends_on = [aws_internet_gateway.sample_igw]
}

where aws_subnet.example is one of the public subnets in your VPC.

  • Related