我有这个问题。我正在尝试在gcp
中创建一个network
和subnetworks
,并且我正在使用模块来做到这一点
所以我的目录结构如下:
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
中的模块network
和subnetworks
的情况下,可以从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
}
如果您想了解更多关于输出变量的信息,可以在这里找到文档。