How to deal with terraform modules that depends on other modules

Viewed 449

I have this problem. I am trying to create a network and subnetworks in gcp and I am using modules to do so.

So my directory structure looks like below:

modules
  network
     main.tf
     variables.tf
  subnetworks
     main.tf
     variables.tf
main.tf
terraform.tfvars
variables.tf

The folders inside the module where I have put the modules as the name suggests.

And main.tf inside the network looks like this:

# module to create the subnet
resource "google_compute_network" "network" {
  name                    = var.network_name
  auto_create_subnetworks = "false"
}

And the main.tf inside the subnetworks looks like this:

resource "google_compute_subnetwork" "public-subnetwork" {
  network          = // how to refer the network name here?
  ...
}

in normal scenarios when we have a one single terraform file for every resource (when we don't use modules), it would look like this:

# create vpc
resource "google_compute_network" "kubernetes-vpc" {
  name                    = "kubernetes-vpc"
  auto_create_subnetworks = "false"
}

resource "google_compute_subnetwork" "master-sub" {
  network       = google_compute_network.kubernetes-vpc.name
  ...
}

We can directly call the google_compute_network.kubernetes-vpc.name for the value of network when creating the google_compute_subnetwork. But now since I am using modules, how can I achieve this?

Thanks.

1 Answers

You can create a outputs.tf file in the network.

Inside the outputs.tf file you can declare a resource like this.

output "google_compute_network_name" {
  description = "The name of the network"
  value       = google_compute_network.network.name
}

Now inside the subnetwork module you can use a standard variable to receive the value of the network name.

resource "google_compute_subnetwork" "public-subnetwork" {
  // receive network name as variable
  network          = var.network_name
  ...
}

And where you use the modules network and subnetworks in main.tf, from the roof folder (I assume) you can pass the output variable from module network to the subnetwork module.

Example:

module "root_network" {
 source = "./modules/network"
}

module "subnetwork" {
 source = "./modules/subnetworks"
 // input variable for subnetwork from the output of the network
 network_name = module.root_network.google_compute_network_name
}

If you want to read more about output variables you can find the documentation here.

Related