我有一个terraform的module a,它创建了一个text文件,我需要在另一个module b中使用这个文本文件,我使用locals来提取文本文件的内容,如下所示,在module b中
locals {
ports = split("\n", file("ports.txt") )
}但是terraform希望这个文件在开始时出现,抛出错误如下所示
Invalid value for "path" parameter: no file exists at
path/ports.txt; this function works only with files
that are distributed as part of the configuration source code, so if this file
will be created by a resource in this configuration you must instead obtain
this result from an attribute of that resource.我在这里错过了什么?如能对此提供任何帮助,将不胜感激。有depends_on给locals吗,我该怎么做?
发布于 2021-06-01 02:17:20
使用模块块从其他模块中调用模块。大多数参数对应于模块定义的输入变量。要引用来自一个模块的值,需要在该模块中声明输出,然后可以从其他模块调用输出值。
例如,我认为模块a中有一个文本文件。
模块a中的.tf文件
output "textfile" {
value = file("D:\\Terraform\\modules\\a\\ports.txt")
}模块b中的.tf文件
variable "externalFile" {
}
locals {
ports = split("\n", var.externalFile)
}
# output "b_test" {
# value = local.ports
# }根模块中的.tf文件
module "a" {
source = "./modules/a"
}
module "b" {
source = "./modules/b"
externalFile = module.a.textfile
depends_on = [module.a]
}
# output "module_b_output" {
# value = module.b.b_test
# }要获得更多参考,您可以阅读https://www.terraform.io/docs/language/modules/syntax.html#accessing-module-output-values
发布于 2021-06-02 01:55:54
正如错误消息报告的那样,file函数仅用于磁盘上作为配置一部分的文件,而不是应用阶段动态生成的文件。
我通常建议避免将文件写入本地磁盘,作为Terraform配置的一部分,因为Terraform的主要假设之一是,您使用Terraform管理的任何对象都会在一次运行到下一次运行期间保持不变,但如果您总是在同一台计算机上的同一目录中运行Terraform,或者使用其他更复杂的方法(例如网络文件系统),则只有在本地文件中运行Terraform。但是,由于您没有提到为什么要将文件写入磁盘,我将假设这是一个困难的要求,并就如何编写文件提出建议,尽管我认为这是最后的手段。
The hashicorp/local provider包括一个名为local_file的数据源,它将以类似于更典型的数据源可能从远程API端点读取文件的方式从磁盘读取文件。特别是,它将尊重在其配置中反映的任何依赖项,并在需要时将文件的读取推迟到应用步骤。
您可以在模块之间协调这一点,然后通过使返回文件名的输出值也取决于负责创建文件的任何资源。例如,如果文件是使用附加到aws_instance资源的提供程序创建的,那么您可以在模块中编写类似的内容:
output "filename" {
value = "D:\\Terraform\\modules\\a\\ports.txt"
depends_on = [aws_instance.example]
}然后,您可以将该值从一个模块传递到另一个模块,这将带着对aws_instance.example的隐式依赖,以确保文件实际上是首先创建的:
module "a" {
source = "./modules/a"
}
module "b" {
source = "./modules/b"
filename = module.a.filename
}最后,在模块中声明输入变量,并将其用作local_file数据资源配置的一部分:
variable "filename" {
type = string
}
data "local_file" "example" {
filename = var.filename
}在第二个模块的其他地方,您可以使用data.local_file.example.content获取该文件的内容。
注意,除了在depends_on块中显式的output "filename"之外,依赖关系还会自动传播。一个模块封装自己的行为是一个很好的实践,这样在调用者使用它时,输出值所需的一切都已经发生了,因为在默认情况下,您的其他配置只会得到正确的行为,而不需要任何额外的depends_on注释。
但是,如果有任何方法可以直接从第一个模块返回ports.txt文件中的数据,而不将其写入磁盘,我建议将其作为一种更健壮和不太复杂的方法。
https://stackoverflow.com/questions/67776525
复制相似问题