Bootstrap FreeKB - Amazon Web Services (AWS) - List Virtual Private Clouds (VPC) using Terraform
Amazon Web Services (AWS) - List Virtual Private Clouds (VPC) using Terraform


Let's say you have two Amazon Web Services (AWS) Virtual Private Clouds (VPC), one name default, the other named my-vpc.

 

There are two similar modules that can be used to return Virtual Private Clouds.

  • aws_vpc - Return a single Virtual Private Cloud
  • aws_vpcs (this article) - Return one or more Virtual Private Clouds

Let's say you have the following files on your Terraform server.

├── required_providers.tf
├── virtual_private_clouds (directory)
│   ├── data.tf
│   ├── outputs.tf
│   ├── provider.tf
│   ├── resources.tf

 

required_providers.tf will almost always have this.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
    }
  }
}

 

Let's say provider.tf has the following. In this example, the "default" profile in /home/username/.aws/config and /home/username/.aws/credentials is being used. This assumes you have setup Terraform as described in Amazon Web Services (AWS) - Getting Started with Terraform.

provider "aws" {
  alias   = "default"
  profile = "default"
  region  = "default"
}

 

And modules.tf could have something like this.

module "virtual_private_clouds" {
  source = "./virtual_private_clouds"
}

 

Let's say data.tf in your virtual_private_clouds module has the following. This will fetch all of your Virtual Private Clouds.

data "aws_vpcs" "my-vpcs" {}

 

And here is how you can limit the results to only contain the Virtual Private Clouds that have a certain tag Name (my-vpc in this example).

data "aws_vpcs" "my-vpcs" {
  tags = {
    Name = "my-vpc"
  }
}

 

And outputs.tf in your virtual_private_clouds module may have something like this.

output "my_vpcs" {
  value = data.aws_vpcs.my-vpcs
}

 

And outputs.tf in the same directory as your main root module may have something like this.

output "vpcs" {
  value = module.virtual_private_clouds.my_vpcs
}

 

The terraform refresh command can be used, and something like this could be returned.

~]$ terraform refresh
Outputs:

vpcs = {
  "filter" = toset(null) /* of object */
  "id" = "us-east-2"
  "ids" = tolist([
    "vpc-0123456feb3abcde9",
  ])
  "tags" = tomap(null) /* of string */
  "timeouts" = null /* object */
}

 

 

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 51839c in the box below so that we can be sure you are a human.