Network already has an internet gateway

Hello,

I am new with terraform and I am trying to create a VPC with several subnets, inside I am deploying a Kubernetes cluster (6 subnets) and a couple of Virtual Machines (subnet_vpc_in)

I got this error, but I did not create the IG before, I don’t know what I am doing wrong

Error: error attaching EC2 Internet Gateway (igw-0184facc846faf88a): Error attaching internet gateway: InvalidParameterValue: Network vpc-0dfd9a125c6c46c68 already has an internet gateway attached
status code: 400, request id: 7328a5ec-6131-43cf-9d6e-a15a551a87d3

Here is the code for the VPC part

=================================================

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "2.58.0"

  name                 = var.vpc_name1
  cidr                 = var.vpc_cidr
  azs                  = data.aws_availability_zones.available.names
  private_subnets      = [var.subnet_pri1, var.subnet_pri2, var.subnet_pri3]
  public_subnets       = [var.subnet_pub1, var.subnet_pub2, var.subnet_pub3]
  enable_nat_gateway   = true
  single_nat_gateway   = true
  enable_dns_hostnames = true
  manage_default_route_table = true
  default_route_table_tags   = { DefaultRouteTable = true }

  public_subnet_tags = {
"kubernetes.io/cluster/${local.cluster_name}" = "shared"
"kubernetes.io/role/elb"                      = "1"
  }

  private_subnet_tags = {
"kubernetes.io/cluster/${local.cluster_name}" = "shared"
"kubernetes.io/role/internal-elb"             = "1"
  }
}

resource "aws_internet_gateway" "igw" {
  vpc_id = module.vpc.vpc_id

  tags = {
Name =  "${var.vpc_name1}-IGW"
  }
}

resource "aws_route" "route-public" {
  route_table_id         = aws_vpc.vpc-in.default_route_table_id
  destination_cidr_block = "0.0.0.0/0"
  gateway_id             = aws_internet_gateway.igw.id
}

 resource "aws_subnet" "subnet_vpc_in" {
   vpc_id            = module.vpc.vpc_id
   cidr_block        = var.cidr_subnet1_vpc1
   map_public_ip_on_launch  = true
   tags = {
 Name = "dev-subnet-vpc-in"
   }
 }

=================================================

Thanks in advance,

The module "terraform-aws-modules/vpc/aws" automatically creates a
resource "aws_internet_gateway" for you among a lot of other resources. So trying to create your own resource "aws_internet_gateway" fails as you saw. Looks like the input create_igw controls whether or not it’s created.

If you want to add your own tags to it see the input igw_tags. I’m not sure why else you would rather create your own.

Look for the outputs igw_arn or igw_id for the automatically created IGW.

If you wanted to manually create all of the resources you might want to start with resource "aws_vpc" "this" instead of the module.

But terraform-aws-modules/vpc/aws is a really nice, super-flexible module. You might want to look at the docs: Terraform Registry

Disclaimer: I didn’t actually test any of this. I also didn’t notice it was a 2 month old question. :man_shrugging: