Error with Nat -terraform
Published: 2022-12-27 14:23:24

Hi,
I got this error:

> │ Error: waiting for EC2 NAT Gateway (nat-00520960bc233b49d) create: unexpected state 'failed', wanted target 'available'. last error: Resource.AlreadyAssociated: Elastic IP address [eipalloc-0c1463e1df14b0c78] is already associated
│ 
│   with module.lsk_instance.aws_nat_gateway.nat,
│   on ../modules/webserver/main.tf line 183, in resource "aws_nat_gateway" "nat":
│  183: resource "aws_nat_gateway" "nat" {
│ 
╵
and this is my code:
```
terraform {
  required_version = ">= 0.12"
}



# module "foobar" {
  
# }

# resource "aws_subnet" "webserver" {
#   vpc_id = var.vpc_id
#   cidr_block = var.cidr_block
# }

# resource "aws_instance" "webserver_west" {
#   ami = var.ami
#   instance_type = var.instance_type
#   subnet_id = aws_subnet.webserver.id

#   tags = {
#     Name = "${var.webserver_name} webserver"
#   }
# }

# resource "aws_instance" "webserver" {
#   ami = var.ami
#   instance_type = var.instance_type
#   subnet_id = aws_subnet.webserver.id

#   tags = {
#     Name = "${var.webserver_name} webserver"
#   }
# }



# -------------------------
# 2. Create Internet Geway
resource "aws_internet_gateway" "gw" {
  vpc_id = var.vpc_id

  tags = {
    Name = "main"
  }
}

/* Routing table for private subnet */
resource "aws_route_table" "private_rt" {
  vpc_id = var.vpc_id
  tags = {
    Name        = "private-route-table"
  }
}

# 3. Create Custom Route Table

resource "aws_route_table" "public_rt" {
  vpc_id = var.vpc_id

  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.gw.id
  }

  route {
    ipv6_cidr_block        = "::/0"
    gateway_id = aws_internet_gateway.gw.id
  }

  tags = {
    Name = "Prod"
  }
}

# 4. Create a Subnet

resource "aws_subnet" "public_subnet" {
  vpc_id = var.vpc_id
  # cidr_block = var.subnet_prefix
  cidr_block = "10.0.0.0/24"
  availability_zone ="us-east-1a"
  tags = {
    Name = "public_subnet"
  }
}

resource "aws_subnet" "private_subnet" {
  vpc_id = var.vpc_id
  # cidr_block = var.subnet_prefix_1
  availability_zone ="us-east-1b"
  cidr_block = "10.0.66.0/24"
  tags = {
    Name = "private_subnet"
  }
}

resource "aws_route" "public_internet_gateway" {
  route_table_id         = "${aws_route_table.public_rt.id}"
  destination_cidr_block = "0.0.0.0/0"
  gateway_id             = "${aws_internet_gateway.gw.id}"
}

resource "aws_route" "private_nat_gateway" {
  route_table_id         = "${aws_route_table.private_rt.id}"
  destination_cidr_block = "0.0.0.0/0"
  nat_gateway_id         = "${aws_nat_gateway.nat.id}"
}

# 5. Assosiate subnet with Route Table

resource "aws_route_table_association" "public" {
  subnet_id  = aws_subnet.public_subnet.id
  route_table_id = aws_route_table.public_rt.id
}

resource "aws_route_table_association" "private" {
  subnet_id  = aws_subnet.private_subnet.id
  route_table_id = aws_route_table.private_rt.id
}

# 6. Create Security Group to allow port 22,80,443

resource "aws_security_group" "allow_web" {
  name        = "allow_tls"
  description = "Allow TLS inbound traffic"
  vpc_id      = var.vpc_id

  ingress {
    description      = "HTTPS"
    from_port        = 443
    to_port          = 443
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
    # ipv6_cidr_blocks = aws_vpc.prod_vpc.ipv6_cidr_block
  }
  ingress {
    description      = "HTTP"
    from_port        = 80
    to_port          = 80
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
    # ipv6_cidr_blocks = aws_vpc.prod_vpc.ipv6_cidr_block
  }
  ingress {
    description      = "SSH"
    from_port        = 2
    to_port          = 2
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
    # ipv6_cidr_blocks = aws_vpc.prod_vpc.ipv6_cidr_block
  }

  egress {
    from_port        = 0
    to_port          = 0
    protocol         = "-1"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }

  tags = {
    Name = "allow_web"
  }
}

# 7. Create a Network Interface with an ip in the subnet that was created in step 4

resource "aws_network_interface" "web-server-nic" {
  subnet_id       = aws_subnet.private_subnet.id
  private_ips     = ["10.0.66.50"]
  security_groups = [aws_security_group.allow_web.id]
}
# 8. Assign an elastic ip to the network interface created in step 7

resource "aws_eip" "one" {
  vpc                       = true
  network_interface         = aws_network_interface.web-server-nic.id
  # associate_with_private_ip = "10.0.66.50"
  depends_on = [aws_internet_gateway.gw]
}

resource "aws_nat_gateway" "nat" {
  allocation_id = "${aws_eip.one.id}"
  subnet_id     = "${element(aws_subnet.public_subnet.*.id, 0)}"
  depends_on    = [aws_internet_gateway.gw]
  tags = {
    Name        = "nat"
  }
}

/* Public subnet */
# resource "aws_subnet" "public_subnet" {
#   vpc_id                  = "${var.vpc_id.id}"
#   count                   = "${length(var.public_subnets_cidr)}"
#   cidr_block              = "${element(var.public_subnets_cidr,   count.index)}"
#   availability_zone       = "${element(var.availability_zone,   count.index)}"
#   map_public_ip_on_launch = true
#   tags = {
#     Name        = "public-subnet"
#   }
# }

# resource "aws_subnet" "private_subnet" {
#   vpc_id                  = "${var.vpc_id.id}"
#   count                   = "${length(var.private_subnets_cidr)}"
#   cidr_block              = "${element(var.private_subnets_cidr,   count.index)}"
#   availability_zone       = "${element(var.availability_zone,   count.index)}"
#   map_public_ip_on_launch = true
#   tags = {
#     Name        = "private-subnet"
#   }
# }






# 9. Create Ubuntu server and install/enable apache2

resource "aws_instance" "web-server-instance" {
  ami = var.ami
  instance_type = var.instance_type
  availability_zone = var.availability_zone
  # key_name = "main-key"
  key_name = var.key_name

  network_interface {
    network_interface_id = aws_network_interface.web-server-nic.id
    device_index         = 0
  }

  user_data = <<-EOF
              #!bin/bash
              sudo apt update -y
              sudo apt install apache -y
              sudo systemctl start apache2
              sudo bash -c 'echo your very first server > /var/www/html/index.html'
              EOF
  tags = {
    Name = "web-server"
  }


}

# ecr

resource "aws_ecr_repository" "ecr" {
  # name = "ecr-repo-name"
  name = var.ecr_name
  # image_tag_mutability = "MUTABLE"
  image_tag_mutability = var.mutability

  image_scanning_configuration {
    scan_on_push = true
  }
}

resource "aws_ecs_task_definition" "task_definition" {
  container_definitions    = "${data.template_file.task_definition_json.rendered}"                                       
  family                   = "openapi-task-defination"                                                                     
  network_mode             = "awsvpc"                                                                                     
  memory                   = "2048"
  cpu                      = "1024"
  requires_compatibilities = ["EC2"]                                                                                       
} 

data "template_file" "task_definition_json" {
  template = "${file("./task_definition.json")}"
}

resource "aws_ecs_cluster" "cluster" {
  # name = "ecs-devl-cluster"
  name = var.ecs_name
}

resource "aws_ecs_service" "service" {
  cluster                = "${aws_ecs_cluster.cluster.id}"                                 # ecs cluster id
  desired_count          = 1                                                         # no of task running
  launch_type            = "EC2"                                                     # Cluster type ECS OR FARGATE
  name                   = "openapi-service"                                         # Name of service
  task_definition        = "${aws_ecs_task_definition.task_definition.arn}"        # Attaching Task to service
  load_balancer {
    container_name       = "openapi-ecs-container"                                  #"container_${var.component}_${var.environment}"
    container_port       = "8080"
    #target_group_arn     = "${aws_lb_target_group.lb_target_group.arn}"         # attaching load_balancer target group to ecs
 }
  network_configuration {
   # security_groups       = ["sg-01849003c4f9203ca"] #CHANGE THIS
    subnets               = ["${var.subnet_prefix_1}", "${var.subnet_prefix}"]  ## Enter the private subnet id
    assign_public_ip      = "false"
  }
  depends_on              = ["aws_lb_listener.lb_listener"]
}

resource "aws_instance" "ec2_instance" {
  ami                    = var.ami
  subnet_id              =  aws_subnet.public_subnet.id #CHANGE THIS
  instance_type          = var.instance_type
  # iam_instance_profile   = "ecsInstanceRole" #CHANGE THIS
  vpc_security_group_ids = [aws_security_group.allow_web.id] #CHANGE THIS
  key_name               = var.key_name #CHANGE THIS
  ebs_optimized          = "false"
  source_dest_check      = "false"
  lifecycle {
    ignore_changes         = ["ami", "user_data", "subnet_id", "key_name", "ebs_optimized", "private_ip"]
  }
}

resource "aws_lb" "loadbalancer" {
  # internal            = "${var.internal}"  # internal = true else false
  name                = "openapi-alb-name"
  # subnets             = ["10.0.66.2" , "10.0.66.6"] # enter the private subnet 
  # security_groups     = ["sg-01849003c4f9203ca"] #CHANGE THIS
}


resource "aws_lb_target_group" "lb_target_group" {
  name        = "openapi-target-alb-name"
  port        = "80"
  protocol    = "HTTP"
  vpc_id      = var.vpc_id # CHNAGE THIS
  target_type = "ip"


#STEP 1 - ECS task Running
  health_check {
    healthy_threshold   = "3"
    interval            = "10"
    port                = "8080"
    path                = "/index.html"
    protocol            = "HTTP"
    unhealthy_threshold = "3"
  }
}

resource "aws_lb_listener" "lb_listener" {
  default_action {
    target_group_arn = "${aws_lb_target_group.lb_target_group.id}"
    type             = "forward"
  }

  #certificate_arn   = "arn:aws:acm:us-east-1:689019322137:certificate/9fcdad0a-7350-476c-b7bd-3a530cf03090"
  load_balancer_arn = "${aws_lb.loadbalancer.arn}"
  port              = "80"
  protocol          = "HTTP"
}
```
if anyone knows what the problem is
it'll help me a lot
thanks!