如何使用位于调用方模块外层的模块的输出?

How can I use the output of a module that is located at outer level of the caller module?

我使用 terraform 已经有一段时间了,我没有遇到任何问题,因为我一直遵循一个简单的结构。 但现在我开始从事另一个似乎不符合最佳实践的项目。

项目结构是这样的:

> root-folder
   > modules
      > cloudfront
      > route53
      > team1
         > service1
            - main.tf
            - variables.tf
            - locals.tf

我想做的是,在 modules>team1>service1>main.tf 文件中使用 modules.cloudfront.some_output_value,如下所示:

module "record" {
  source      = "../../route53"
  zone_id     = var.route53_zone_id
  record_name = local.record_name
  cdn_id       = module.cloudfront.some_output_value   //the question is about this line
}

但是我无法使用它,因为IDE表示没有这样的模块module.cloudfront.

有谁知道为什么我不能使用在外部作用域定义的模块?

Terraform 版本:1.2.0(可能这与基于版本的问题无关,但无论如何。)

无法从内部模块查询外部模块。如果你的外部模块中有任何应该在内部模块中使用的variables/outputs,你必须明确地将它们从外部传递到内部模块。

这取决于您从何处调用 cloudfront 模块。

选项 1

如果您从同一个父级调用两个模块,service1cloudfront,那么您需要在 service1 中定义一个变量并显式传递值:

service1(当然应该分成variables.tfmain.tf

variable "cdn_id" {
  type        = ...
  description = "..."
}

module "record" {
  source       = "../../route53"
  zone_id      = var.route53_zone_id
  record_name  = local.record_name
  cdn_id       = var.cdn_id
}

parent module(例如在根文件夹中)

module "service1" {
  source        = "modules/team1/service1"
  cdn_id        = module.cloudfront.some_output_value
  some_var_name = some_value
  ...
}

module "cloudfront" {
  source        = "modules/cloudfront"
  some_var_name = some_value
  ...
}

选项 2

如果您从 service1 调用它,那么模块在文件层次结构中的位置并不重要。您只需要正确设置源路径:

module "record" {
  source       = "../../route53"
  zone_id      = var.route53_zone_id
  record_name  = local.record_name
  cdn_id       = module.cloudfront.some_output_value
}

module "cloudfront" {
  source        = "../../cloudfront"
  some_var_name = some_value
  ...
}