I am new to terraform and have a few questions. Is there a way in terraform, to use the outputs of a module, in another tf file, WITHOUT having a "main" terraform file, or defining both modules in the same file?
For example, this is a project structure:
project/
├── networking
│ ├── init.tf
│ ├── terraform.tfvars
│ ├── variables.tf
│ └── vpc.tf
├── prd-project-1
│ ├── init.tf
│ ├── instances.tf
│ ├── terraform.tfvars
│ └── variables.tf
├── prd-project-2
│ ├── init.tf
│ ├── instances.tf
│ ├── terraform.tfvars
│ └── variables.tf
├── prd-project-3
│ ├── init.tf
│ ├── instances.tf
│ ├── terraform.tfvars
│ └── variables.tf
├── test
│ ├── init.tf
│ ├── instances.tf
│ ├── terraform.tfvars
│ └── variables.tf
vpc.tf
would create a VPC and subnets.
instances.tf
would create EC2 instances, based on the vpc-id and subnets created previously in vpc.tf
. I want to treat/manage these as two seperate actions. ie. First, I would run terraform to create the vpc and subnets, then later I might run terraform to create instances in prod/test for various projects. In this example, I would have only 1 VPC for test and 1 VPC for prod. I would not want a VPC per project (which I am again assuming TF might create if the vpc.tf
module is referenced in one of the sub-projects).
Is it best practise to manage terraform code in this way? My concern is if eventually there are many projects needing EC2 instances, I don't want all of these in a single huge main.tf
. I am thinking it is safer/cleaner to maintain these all seperately, as long as the vpc outputs can be referenced. I also don't want my terraform plan/applies being slow and checking each and every resource from every project if I am standing up a new project.
The second part of my question is - consider the following code snippet:
module "main-vpc" {
source = "../modules/vpc"
ENV = "prod"
AWS_REGION = var.AWS_REGION
}
module "instances" {
source = "../modules/instances"
ENV = "prod"
VPC_ID = module.main-vpc.vpc_id
PUBLIC_SUBNETS = module.main-vpc.public_subnets
}
Is terraform smart enough to determine that a VPC was already created with an ENV = prod and would not try to recreate it if I called the same "main-vpc" module in another tf file/project?
I've read a few other posts here on stackoverflow, but they all allude that outputs from a module can only be referenced in another module within the same tf file.
Some other posts I've reviewed: