【问题标题】:How to deal with terraform modules that depends on other modules如何处理依赖于其他模块的 terraform 模块
【发布时间】:2021-01-23 05:07:18
【问题描述】:

我有这个问题。我正在尝试在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?
  ...
}

在正常情况下,当我们为每个资源都有一个单一的 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_subnetwork时直接调用google_compute_network.kubernetes-vpc.name获取network的值。但是现在我使用的是模块,我该如何实现呢?

谢谢。

【问题讨论】:

    标签: google-cloud-platform terraform


    【解决方案1】:

    您可以在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,则可以从屋顶文件夹(我假设)将 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
    }
    

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

    【讨论】:

    • 谢谢network模块里面的outputs.tf,为什么要单独放一个文件呢?我们在network 模块中的main.tf 中使用它,对吗?我认为将 outputs.tf 放在单独的文件中是行不通的。
    • 通常最好的做法是将模块导出的变量放在单独的 output.tf 文件中,以便清楚地了解模块创建的哪些内部资源打算供其他外部资源使用模块。希望这会有所帮助。
    • 谢谢。还有一个小问题,我如何对后端terraform 文件执行相同的操作,在该文件中我尝试设置一个远程存储桶来存储状态。我需要将其作为与root 目录中的main.tf 分开的文件。可能吗?如果是这样,当我们应用terraform apply时,terraform如何知道先执行带有后端配置的文件,然后再执行main.tf创建资源?
    • 您好,我相信您不能在backend 声明中使用变量或插值。 terraform workspaces 可能对您有所帮助,您可以在此处找到文档 terraform.io/docs/state/workspaces.html
    猜你喜欢
    • 2020-02-05
    • 2020-03-17
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2019-11-04
    • 2019-12-13
    相关资源
    最近更新 更多