Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the VPC id and subnets id values which were created from one Terraform plan to in another Terraform plan

I have created the VPC, subnets and security groups in one Terraform plan (let's call this Plan A). It executed well and the state is stored in the remote S3 backend as well.

Now I have a new Terraform plan (let's call this Plan B) where I need to launch an EC2 instance. For this I need to fetch the VPC, subnet ids from the Plan A Terraform output.

Is there a recommended way to do this?

like image 300
Anjankumar H N Avatar asked Aug 29 '18 09:08

Anjankumar H N


People also ask

How do I use existing VPC ID in terraform?

Just create a variables file that holds your existing resource ids that you need for your new resources, and then you can then reference the ones you need.


1 Answers

If you created your Plan A vpc and subnet with a unique tag (e.g: Name) you can fetch them easily using the following example:

data "aws_vpc" "selected" {
  filter {
    name = "tag:Name"
    values = ["my_vpc_name"]
  }
}

data "aws_subnet" "selected" {
  filter {
    name = "tag:Name"
    values = ["my_subnet_name"]
  }
}

resource "aws_security_group" "sg" {
  vpc_id = data.aws_vpc.selected.id
  ...
}

resource "aws_instance" "instance" {
  vpc_security_group_ids = [ aws_security_group.sg.id ]
  subnet_id              = data.aws_subnet.selected.id
  ...
}

Note: It's easy to modify your old resources to include the Name tag (or any tag)

like image 171
ofirule Avatar answered Sep 29 '22 07:09

ofirule