如果创建了虚拟机,如何使用terraform在inventory.ini.tmpl中写入虚拟机的名称和ip?

如果创建了虚拟机,如何使用terraform在inventory.ini.tmpl中写入虚拟机的名称和ip?,terraform,Terraform,虚拟机是使用terraform版本13.5创建的 虚拟机有变量名_b(我很感兴趣) 创建虚拟机的主代码 resource "vcd_vapp_vm" "b" { count = var.create_b == "true" ? 1 : 0 name = "b" } 如果我不想创建虚拟机: create_b = "false" 如果创建了虚拟机,则必须将

虚拟机是使用terraform版本13.5创建的

虚拟机有变量名_b(我很感兴趣)

创建虚拟机的主代码

resource "vcd_vapp_vm" "b" {
  count         = var.create_b == "true" ? 1 : 0
  name          = "b"
}
如果我不想创建虚拟机:

create_b = "false"
如果创建了虚拟机,则必须将其名称记录在inventory.ini中

resource "local_file" "AnsibleInventory" {
 content = templatefile("inventory.ini.tmpl",
 {
  name_b                = vcd_vapp_vm.b.name,
 }
 )
 filename = "inventory.ini"
}

如何避免错误

Error: Missing resource instance key

  on outputs.tf line 12, in resource "local_file" "AnsibleInventory":
  13:   name_b      = vcd_vapp_vm.b.name,

Because vcd_vapp_vm.b has "count" set, its attributes must be accessed
on specific instances.

For example, to correlate with indices of a referring resource, use:
    vcd_vapp_vm.b[count.index]
我尝试将[count.index]添加到资源中

resource "local_file" "AnsibleInventory" {
 content = templatefile("inventory.ini.tmpl",
 {
  name_b                = vcd_vapp_vm.b[count.index].name,
  
 }
 )
 filename = "inventory.ini"
}
错误:

Error: Reference to "count" in non-counted context

  on outputs.tf line 12, in resource "local_file" "AnsibleInventory":
  13:   name_b                = vcd_vapp_vm.b[count.index].name,

The "count" object can only be used in "module", "resource", and "data"
blocks, and only when the "count" argument is set.
我尝试添加check特殊变量

resource "local_file" "AnsibleInventory" {
 content = templatefile("inventory.ini.tmpl",
 {
  name_b                = var.create_b ? vcd_vapp_vm.b.name : null,
  
 }
 )
 filename = "inventory.ini"
}
错误

试一试

错误


Terraform不会以本机方式输出到文件


你想完成什么?为什么要将这些变量值写入文件?

谢谢您的回答!尝试在问题中添加示例。
  on outputs.tf line 12, in resource "local_file" "AnsibleInventory":

  13:   name_b                = var.create_b ? vcd_vapp_vm.b.name : null,

Because vcd_vapp_vm.b has "count" set, its attributes must be accessed
on specific instances.

For example, to correlate with indices of a referring resource, use:
    vcd_vapp_vm.b[count.index]
resource "local_file" "AnsibleInventory" {
 content = templatefile("inventory.ini.tmpl",
 {
  name_b = try(vcd_vapp_vm.b.name, null)
 }
 )
 filename = "inventory.ini"
}
Error: Missing resource instance key

  on outputs.tf line 12, in resource "local_file" "AnsibleInventory":
  13:   name_b = try(vcd_vapp_vm.b.name, null)

Because vcd_vapp_vm.b has "count" set, its attributes must be accessed
on specific instances.

For example, to correlate with indices of a referring resource, use:
    vcd_vapp_vm.b[count.index]