There's 2 main ways of passing outputs of things around in Terraform.
The first, and oldest, way is to use the remote state feature to fetch outputs in a different state file.
The second, newer, approach is to use your provider's data sources that expose a read only request to your provider to fetch information about a resource.
With this you would use the aws_vpc
and aws_subnet_ids
data sources to retrieve information about the relevant subnet IDs.
An example might look something like that given in the aws_subnet_ids
docs:
variable "vpc" {}
variable "ami" {}
data "aws_vpc" "selected" {
tags {
Name = "${var.vpc}"
}
}
data "aws_subnet_ids" "private" {
vpc_id = "${data.aws_vpc.selected.id}"
tags {
Tier = "Private"
}
}
resource "aws_instance" "app" {
count = "3"
ami = "${var.ami}"
instance_type = "t2.micro"
subnet_id = "${element(data.aws_subnet_ids.private.ids, count.index)}"
}
This would place a single EC2 instance in each of your 3 subnets that are tagged with Tier
= Private
in the VPC with a Name
tag value provided by the vpc
variable.
Obviously you can push this further by using the aws_ami
data source to also fetch the AMI ID you want to use based on some filtering criteria. This also helps to remove some of the more magic variables you might have in your Terraform code otherwise.