英文:
terraform and variables in modules
问题
我有一个位于文件夹 "modules/network/variables.tf" 中的文件:
variable "iam_profile" {
description = "IAM profile"
default = "ec2_profile"
}
而我无法从这个主要的 tf 文件中获取该变量:
module "network" {
source = "./modules/network"
}
output "test1" {
value = "${module.network.iam_profile}" => 错误:此对象没有名为 "iam_profile" 的属性
}
output "test2" {
value = "${module.network.var.iam_profile}" => 错误:此对象没有名为 "var" 的属性
}
在运行 terraform init 和 apply 后为什么会出现错误,有任何想法吗?
英文:
I have this file in a folder "modules/network/variables.tf" :
variable "iam_profile" {
description = "IAM profile"
default = "ec2_profile"
}
and I can't get the variable from this main tf file :`
module "network" {
source = "./modules/network"
}
output "test1" {
value = "${module.network.iam_profile}" => error : This object does not have an attribute named "iam_profile"
}
output "test2" {
value = "${module.network.var.iam_profile}" => error : This object does not have an attribute named "var"
}
Any idea why I have errors after terraform init and apply?
答案1
得分: 2
根据您实际需要的内容,答案会有所不同。如果模块 network
需要创建一个名为 iam_profile
的东西,那么您也需要在模块中定义一个输出。如果您想从模块中访问一个变量,那是不可能的。要使用您在问题中显示的语法,您需要在模块的 outputs.tf
中执行以下操作:
output "iam_profile" {
value = var.iam_profile
}
然后,在根模块中(即您想要模块输出的代码中),您可以执行以下操作:
module "network" {
source = "./modules/network"
}
output "test1" {
value = module.network.iam_profile
}
英文:
Depending on what you really need/want, the answer will be different. If something called iam_profile
needs to be created by the module network
, then you need to have an output defined in the module as well. If you want to access a variable from the module, that is not possible. To use the syntax you have shown in the question, you need to do the following in the outputs.tf
of the module:
output "iam_profile" {
value = var.iam_profile
}
Then, in the root module (i.e, the code where you want the output of the module), you would do the following:
module "network" {
source = "./modules/network"
}
output "test1" {
value = module.network.iam_profile
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论