terraform 和模块中的变量

huangapple go评论59阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2023年7月3日 19:56:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76604512.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定