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

时间:2020-10-08 07:24:48

标签: google-cloud-platform terraform

我有这个问题。我正在尝试在network中创建一个subnetworksgcp,并且正在使用模块来实现。

所以我的目录结构如下:

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

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

main.tf中的network看起来像这样:

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

main.tf中的subnetworks看起来像这样:

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

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

# 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_network.kubernetes-vpc.name时,我们可以直接为network的值调用google_compute_subnetwork。但是,既然我正在使用模块,该如何实现呢?

谢谢。

1 个答案:

答案 0 :(得分:4)

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

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

network中使用模块subnetworksmain.tf的地方,从屋顶文件夹(我假设),您可以从模块{{1 }}进入output模块。

示例:

network

如果您想了解有关输出变量的更多信息,可以找到文档here