如何处理依赖于其他模块的地形模块



我有这个问题。我正在尝试在gcp中创建一个networksubnetworks,并且我正在使用模块来做到这一点

所以我的目录结构如下:

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

module中的文件夹,顾名思义,我将模块放在其中。

network内部的main.tf看起来是这样的:

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

subnetworks内部的main.tf看起来是这样的:

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

在正常情况下,当我们为每个资源都有一个单一的地形文件时(当我们不使用模块时(,它看起来像这样:

# 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
...
}

在创建google_compute_subnetwork时,我们可以直接调用google_compute_network.kubernetes-vpc.name来获取network的值。但是现在我使用的是模块,我该如何实现呢?

谢谢。

您可以在network中创建一个outputs.tf文件。

outputs.tf文件中,您可以声明这样的资源。

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

现在,在subnetwork模块中,您可以使用标准变量来接收网络名称的值。

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

在使用main.tf中的模块networksubnetworks的情况下,可以从roof文件夹(我假设(将output变量从模块network传递到subnetwork模块。

示例:

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
}

如果您想了解更多关于输出变量的信息,可以在这里找到文档。

最新更新