How to get the default vpc id with terraform

Viewed 6496

I am trying to get the vpc_id of default vpc in my aws account using terraform

This is what I tried but it gives an error

Error: Invalid data source

this is what I tried:

data "aws_default_vpc" "default" {

}


# vpc
resource "aws_vpc" "kubernetes-vpc" {
  cidr_block = "${var.vpc_cidr_block}"
  enable_dns_hostnames = true

  tags = {
    Name = "kubernetes-vpc"
  }
}
2 Answers

The aws_default_vpc is indeed not a valid data source. But the aws_vpc data source does have a boolean default you can use to choose the default vpc:

data "aws_vpc" "default" {
  default = true
} 

For completeness, I'll add that an aws_default_vpc resource exists that also manages the default VPC and implements the resource life-cycle without really creating the VPC* but would make changes in the resource like changing tags (and that includes its name).

* Unless you forcefully destroy the default VPC

From the docs:

This is an advanced resource and has special caveats to be aware of when using it. Please read this document in its entirety before using this resource.

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/default_vpc

This

resource "aws_default_vpc" "default" {
}

will do.

I think this is convenient for terraform projects managing a whole AWS account, but I would advise against using it whenever multiple terraform projects are deployed in a single organization account. You should better stay with @blokje5's answer in that case.

Related