14

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 2

31

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
} 
0
-1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.