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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With