terraform 和模块中的变量

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

terraform and variables in modules

问题

我有一个位于文件夹 "modules/network/variables.tf" 中的文件:

  1. variable "iam_profile" {
  2. description = "IAM profile"
  3. default = "ec2_profile"
  4. }

而我无法从这个主要的 tf 文件中获取该变量:

  1. module "network" {
  2. source = "./modules/network"
  3. }
  4. output "test1" {
  5. value = "${module.network.iam_profile}" => 错误此对象没有名为 "iam_profile" 的属性
  6. }
  7. output "test2" {
  8. value = "${module.network.var.iam_profile}" => 错误此对象没有名为 "var" 的属性
  9. }

在运行 terraform init 和 apply 后为什么会出现错误,有任何想法吗?

英文:

I have this file in a folder "modules/network/variables.tf" :

  1. variable "iam_profile" {
  2. description = "IAM profile"
  3. default = "ec2_profile"
  4. }

and I can't get the variable from this main tf file :`

  1. module "network" {
  2. source = "./modules/network"
  3. }
  4. output "test1" {
  5. value = "${module.network.iam_profile}" => error : This object does not have an attribute named "iam_profile"
  6. }
  7. output "test2" {
  8. value = "${module.network.var.iam_profile}" => error : This object does not have an attribute named "var"
  9. }

Any idea why I have errors after terraform init and apply?

答案1

得分: 2

根据您实际需要的内容,答案会有所不同。如果模块 network 需要创建一个名为 iam_profile 的东西,那么您也需要在模块中定义一个输出。如果您想从模块中访问一个变量,那是不可能的。要使用您在问题中显示的语法,您需要在模块的 outputs.tf 中执行以下操作:

  1. output "iam_profile" {
  2. value = var.iam_profile
  3. }

然后,在根模块中(即您想要模块输出的代码中),您可以执行以下操作:

  1. module "network" {
  2. source = "./modules/network"
  3. }
  4. output "test1" {
  5. value = module.network.iam_profile
  6. }
英文:

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:

  1. output "iam_profile" {
  2. value = var.iam_profile
  3. }

Then, in the root module (i.e, the code where you want the output of the module), you would do the following:

  1. module "network" {
  2. source = "./modules/network"
  3. }
  4. output "test1" {
  5. value = module.network.iam_profile
  6. }

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:

确定