我不太清楚如何在我的模块中添加一个配置"remote-exec“部分,我希望它从项目目录中复制配置脚本并执行它们。但是当我添加这个模块时,我似乎不能让它以VM实例为目标,因为它有多个网卡,所以我只想以主卡为目标。
我已经使用它通过Terraform在一个本地vSphere实例上部署了一个Linux。
provider "vsphere" {
  user           = var.vsphere_user
  password       = var.vsphere_password
  vsphere_server = var.vsphere_server
  # If you have a self-signed cert
  allow_unverified_ssl = true
}这是示例Linux部署脚本,概述了网络部分,它允许将多个网卡配置到一个虚拟机
resource "vsphere_virtual_machine" "Linux" {
  count      = var.is_windows_image ? 0 : var.instances
  depends_on = [var.vm_depends_on]
  name       = "%{if var.vmnameliteral != ""}${var.vmnameliteral}%{else}${var.vmname}${count.index + 1}${var.vmnamesuffix}%{endif}"
........
  dynamic "network_interface" {
    for_each = keys(var.network) #data.vsphere_network.network[*].id #other option
    content {
      network_id   = data.vsphere_network.network[network_interface.key].id
      adapter_type = var.network_type != null ? var.network_type[network_interface.key] : data.vsphere_virtual_machine.template.network_interface_types[0]
    }
  }
........
    //Copy the file to execute
    provisioner "file" {
      source      = var.provisioner_file_source // eg ./scripts/*
      destination = var.provisioner_file_destination // eg /tmp/filename
      connection {
          type     = "ssh" // for Linux its SSH 
          user     = var.provisioner_ssh_username
          password = var.provisioner_ssh_password
          host     = self.vsphere_virtual_machine.Linux.*.guest_ip_address
        }
      }  
    //Run the script
    provisioner "remote-exec" {
      inline = [
        "chmod +x ${var.provisioner_file_destination}",
        "${var.provisioner_file_destination} args",
      ]
    
      connection {
        type     = "ssh" // for Linux its SSH 
        user     = var.provisioner_ssh_username
        password = var.provisioner_ssh_password
        host     = self.vsphere_virtual_machine.Linux.*.guest_ip_address
      }
    }
 }
} // end of resource "vsphere_virtual_machine" "Linux"所以我尝试了一下self。reference,但到目前为止,self.vsphere_virtual_machine.Linux.*.guest_ip_address只显示了整个来宾IP数组?
有没有人能给我指出正确的方向,或者甚至是terraform模块的好指南?
发布于 2021-04-28 10:51:10
我注意到的第一个问题是vsphere_virtual_machine资源没有属性guest_ip_address,它是guest_ip_addresses。这确实返回了一个列表,所以您需要弄清楚如何从列表中选择您想要的IP。我不确定在vSphere中排序是否是可预测的。如果我没记错的话,它不是。
最简单的方法可能是使用default_ip_address,因为它返回单个地址并为“最有可能”的场景选择ip。
看起来您还将主机设置为多宿主。这增加了额外的复杂性。如果default_ip_address不能满足您的需求,您将需要使用一些更复杂的表达式来查找您的IP。也许您可以使用sort函数,这样可以更好地预测排序。您也可以使用for循环“找到”IP。
关于构建模块,如果上面的代码在模块中,我建议的第一件事是避免使用count。在下面的文本中解释了这一点的原因。Hashicorp在他们的网站上有很多很好的文档。此外,gruntwork的员工还开发了一个blog series,并将其写成了一本名为Terraform Up and Running的书。我建议你看看这个。
https://stackoverflow.com/questions/67272588
复制相似问题