使用 Terraform 创建多个新实例

Create multiple new instances with Terraform

我写了一个 Terraform 脚本,它应该从一个模板创建多个服务器实例。我现在已经创建了两个不同的变量文件。

但是当我 运行 脚本时,使用第一个变量文件创建了一个新实例,但是对于第二个,第一个总是被覆盖/更改。我不知道为什么 Terraform 会引用之前新创建的实例。我该如何防止这种情况?

服务器-1.tfvars:

vsphere_user                     = "administrator@vsphere.local"
vsphere_password                 = "#Password"
vsphere_server                   = "vsphere.server"
vsphere_datacenter               = "Datacenter"
vsphere_datastore                = "Storage_1"
vsphere_compute_cluster          = "Cluster"
vsphere_network                  = "Network_1"
vsphere_virtual_machine_template = "Template_Microsoft_Windows_Server_2019_x64_english"
system_name                      = "server-1"
system_cores                     = 2
system_cores_per_socket          = 2
system_memory                    = 2048
system_local_admin_password      = "#Password"
system_ipv4_address              = "172.22.15.11"
system_ipv4_netmask              = 24
system_dns_server_list           = ["172.22.15.101"]
system_ipv4_gateway              = "172.22.15.1"
system_disk1_size                = 75
system_domain_admin_user         = "Administrator"
system_domain_admin_password     = "#Password"

服务器-2.tfvars:

vsphere_user                     = "administrator@vsphere.local"
vsphere_password                 = "#Password"
vsphere_server                   = "vsphere.server"
vsphere_datacenter               = "Datacenter"
vsphere_datastore                = "Storage_1"
vsphere_compute_cluster          = "Cluster"
vsphere_network                  = "Network_1"
vsphere_virtual_machine_template = "Template_Microsoft_Windows_Server_2019_x64_english"
system_name                      = "server-2"
system_cores                     = 2
system_cores_per_socket          = 2
system_memory                    = 2048
system_local_admin_password      = "#Password"
system_ipv4_address              = "172.22.15.12"
system_ipv4_netmask              = 24
system_dns_server_list           = ["172.22.15.101"]
system_ipv4_gateway              = "172.22.15.1"
system_disk1_size                = 75
system_domain_admin_user         = "Administrator"
system_domain_admin_password     = "#Password"

provider.tf:

provider "vsphere" {
  user                 = var.vsphere_user
  password             = var.vsphere_password
  vsphere_server       = var.vsphere_server
  allow_unverified_ssl = true
}

data.tf:

# Data Sources
# Datacenter
data "vsphere_datacenter" "dc" {
  name = var.vsphere_datacenter
}

# Datastore
data "vsphere_datastore" "datastore" {
  name          = var.vsphere_datastore
  datacenter_id = data.vsphere_datacenter.dc.id
}

# Cluster
data "vsphere_compute_cluster" "cluster" {
  name          = var.vsphere_compute_cluster
  datacenter_id = data.vsphere_datacenter.dc.id
}

# Network
data "vsphere_network" "network" {
  name          = var.vsphere_network
  datacenter_id = data.vsphere_datacenter.dc.id
}

# Template
data "vsphere_virtual_machine" "template" {
  name          = var.vsphere_virtual_machine_template
  datacenter_id = data.vsphere_datacenter.dc.id
}

resource.tf:

# Virtual Machine Resource
resource "vsphere_virtual_machine" "server-instance" {
  # System
  firmware  = "efi"
  guest_id  = data.vsphere_virtual_machine.template.guest_id
  scsi_type = data.vsphere_virtual_machine.template.scsi_type

  # VM-Name
  name             = var.system_name
  resource_pool_id = data.vsphere_compute_cluster.cluster.resource_pool_id
  datastore_id     = data.vsphere_datastore.datastore.id

  # CPU
  num_cpus               = var.system_cores
  num_cores_per_socket   = var.system_cores_per_socket
  cpu_hot_add_enabled    = true
  cpu_hot_remove_enabled = true

  # Memory
  memory                 = var.system_memory
  memory_hot_add_enabled = true

  # Network
  network_interface {
    network_id   = data.vsphere_network.network.id
    adapter_type = "e1000e"
  }

  # Storage
  # Drive 0 (C)
  disk {
    label            = "disk0"
    unit_number      = 0
    size             = data.vsphere_virtual_machine.template.disks.0.size
    eagerly_scrub    = data.vsphere_virtual_machine.template.disks.0.eagerly_scrub
    thin_provisioned = data.vsphere_virtual_machine.template.disks.0.thin_provisioned
  }

  # Drive 1 (D)
  disk {
    label            = "disk1"
    unit_number      = 1
    size             = var.system_disk1_size
    eagerly_scrub    = data.vsphere_virtual_machine.template.disks.1.eagerly_scrub
    thin_provisioned = data.vsphere_virtual_machine.template.disks.1.thin_provisioned
  }

  # Template clone and OS settings
  clone {
    template_uuid = data.vsphere_virtual_machine.template.id

    customize {
      windows_options {
        computer_name         = var.system_name
        admin_password        = random_password.password.result
        join_domain           = var.system_domain
        domain_admin_user     = var.system_domain_admin_user
        domain_admin_password = var.system_domain_admin_password
        auto_logon            = true
      }

      network_interface {
        ipv4_address    = var.system_ipv4_address
        ipv4_netmask    = var.system_ipv4_netmask
        dns_server_list = var.system_dns_server_list
      }

      ipv4_gateway = var.system_ipv4_gateway
    }
  }
}

password.tf:

# Import the Random Password Provider
terraform {
  required_providers {
    random = {
      source = "hashicorp/random"
    }
  }
}

resource "random_password" "password" {
  length           = 25
  upper            = true
  lower            = true
  number           = true
  special          = true
  min_upper        = 2
  min_lower        = 2
  min_numeric      = 2
  min_special      = 1
  override_special = "!@#$%&*()-_=+[]{}<>:?"
}

Terraform 的模型是您配置中的每个资源实例都绑定到零个或一个远程对象——如果您还没有创建远程对象则为零,然后在第一次创建对象后绑定一个.

Terraform 模型的另一个重要特征是它是声明性的。您不应该将 terraform apply 理解为“创建所有这些东西”,而应该理解为“采取任何必要的措施使远程系统匹配此配置”。在 first 运行 上,通常会导致许多创建操作,但在随后的 运行 上,您通常会对已经存在的对象进行更改,因为提供者旨在找到更改远程系统以匹配更新配置的破坏性最小的方法。

考虑到这一点,当您使用 vsphere_virtual_machine.server-instance 的参数的不同值重新 运行 Terraform 时,Terraform(和 vsphere 提供商)理解您想要更改您之前创建的现有对象,而不是创建新对象。

为了同时存在多个虚拟机,您必须有多个对应的资源实例,每个虚拟机一个。在 Terraform 的模型中,每个 resource 块可以代表一个或多个资源实例;获得两个资源实例的最直接方法是编写两个 resource 块,因此每个块将声明一个实例:

resource "vsphere_virtual_machine" "server_1" {
  # ...
}

resource "vsphere_virtual_machine" "server_2" {
  # ...
}

但是,如果您的多个实例是系统地创建的,并且您可以使用 Terraform 语言中的表达式来表达,那么您还有一些其他选择。

如果您认为您的所有虚拟机在某种意义上都是彼此的“副本”,并且功能相同,那么您可能会选择使用 the count meta-argument,这会导致 resource块有多个与之关联的资源实例——由 count 表达式给出的数字——除了用特殊符号 count.index 表示的一些细微差异外,所有资源实例都具有基本相同的配置给出当前索引的索引:

resource "vsphere_virtual_machine" "server" {
  count = 2

  # VM-Name
  name             = "${var.system_name}-${count.index}"
  resource_pool_id = data.vsphere_compute_cluster.cluster.resource_pool_id
  datastore_id     = data.vsphere_datastore.datastore.id

  # System
  firmware  = "efi"
  guest_id  = data.vsphere_virtual_machine.template.guest_id
  scsi_type = data.vsphere_virtual_machine.template.scsi_type

  # CPU
  num_cpus               = var.system_cores
  num_cores_per_socket   = var.system_cores_per_socket
  cpu_hot_add_enabled    = true
  cpu_hot_remove_enabled = true

  # Memory
  memory                 = var.system_memory
  memory_hot_add_enabled = true

  # Network
  network_interface {
    network_id   = data.vsphere_network.network.id
    adapter_type = "e1000e"
  }

  # Storage
  # Drive 0 (C)
  disk {
    label            = "disk0"
    unit_number      = 0
    size             = data.vsphere_virtual_machine.template.disks.0.size
    eagerly_scrub    = data.vsphere_virtual_machine.template.disks.0.eagerly_scrub
    thin_provisioned = data.vsphere_virtual_machine.template.disks.0.thin_provisioned
  }

  # Drive 1 (D)
  disk {
    label            = "disk1"
    unit_number      = 1
    size             = var.system_disk1_size
    eagerly_scrub    = data.vsphere_virtual_machine.template.disks.1.eagerly_scrub
    thin_provisioned = data.vsphere_virtual_machine.template.disks.1.thin_provisioned
  }

  # Template clone and OS settings
  clone {
    template_uuid = data.vsphere_virtual_machine.template.id

    customize {
      windows_options {
        computer_name         = var.system_name
        admin_password        = random_password.password.result
        join_domain           = var.system_domain
        domain_admin_user     = var.system_domain_admin_user
        domain_admin_password = var.system_domain_admin_password
        auto_logon            = true
      }

      network_interface {
        ipv4_address    = var.system_ipv4_address
        ipv4_netmask    = var.system_ipv4_netmask
        dns_server_list = var.system_dns_server_list
      }

      ipv4_gateway = var.system_ipv4_gateway
    }
  }
}

以上与您包含的 resource "vsphere_virtual_machine" "server" 相同,只是我在开始时添加了 count = 2 并且我更改了 name 以便它认为 var.system_name 是名称 prefix 而不是整个名称,添加当前索引以创建完整的唯一名称。我想您可能还需要为 system_ipv4_address 遵循类似的策略,可能使用 the cidrhost function 来系统地计算 IP 地址,但为了简单起见,我将在此处省略。

如果我们还更改变量文件,使 var.system_name 只是 "server" 而不是 "server-1" 那么这将声明 两个 资源实例来自单个资源块:

  • vsphere_virtual_machine.server[0]name = "server-0"
  • vsphere_virtual_machine.server[1]name = "server-1"

在您分享的示例中,count 似乎最适合您的情况,因为您的服务器虚拟机在其他方面的配置都相同。但是,如果您需要将每个服务器视为完全独立配置,以便它们都可以有可能不同的参数,那么您还有 the for_each meta-argument 形式的另一个选项。与 count 一样,它从单个资源块声明多个资源实例,但它对映射中的每个元素都这样做,而不仅仅是将整数增加到特定限制。

这种方法确实需要对输入变量采取略微不同的策略,因为我们需要输入是对象映射,其中映射的每个元素代表一个虚拟机:

variable "virtual_machines" {
  type = map(object({
    system_cores            = number
    system_cores_per_socket = number
    system_memory           = number
    system_ipv4_address     = string
    # (and so on, for all of the attributes that vary between
    # your virtual machines)
  }))
}

因为这是定义所有虚拟机的单个变量,您还需要更改 .tfvars 文件以不同方式设置它:

vsphere_user                     = "administrator@vsphere.local"
vsphere_password                 = "#Password"
vsphere_server                   = "vsphere.server"
vsphere_datacenter               = "Datacenter"
vsphere_datastore                = "Storage_1"
vsphere_compute_cluster          = "Cluster"
vsphere_network                  = "Network_1"
vsphere_virtual_machine_template = "Template_Microsoft_Windows_Server_2019_x64_english"

virtual_machines = {
  server-1 = {
    system_cores            = 2
    system_cores_per_socket = 2
    system_memory           = 2048
    system_ipv4_address     = "172.22.15.11"
    # ...
  }
  server-2 = {
    system_cores            = 2
    system_cores_per_socket = 2
    system_memory           = 2048
    system_ipv4_address     = "172.22.15.12"
    # ...
  }
}

设置了 for_eachresource 块看起来像这样:

resource "vsphere_virtual_machine" "server" {
  for_each = var.virtual_machines

  # VM-Name
  name             = each.key
  resource_pool_id = data.vsphere_compute_cluster.cluster.resource_pool_id
  datastore_id     = data.vsphere_datastore.datastore.id

  # System
  firmware  = "efi"
  guest_id  = data.vsphere_virtual_machine.template.guest_id
  scsi_type = data.vsphere_virtual_machine.template.scsi_type

  # CPU
  num_cpus               = each.value.system_cores
  num_cores_per_socket   = each.value.system_cores_per_socket
  cpu_hot_add_enabled    = true
  cpu_hot_remove_enabled = true

  # Memory
  memory                 = each.value.system_memory
  memory_hot_add_enabled = true

  # Network
  network_interface {
    network_id   = data.vsphere_network.network.id
    adapter_type = "e1000e"
  }

  # Storage
  # Drive 0 (C)
  disk {
    label            = "disk0"
    unit_number      = 0
    size             = data.vsphere_virtual_machine.template.disks.0.size
    eagerly_scrub    = data.vsphere_virtual_machine.template.disks.0.eagerly_scrub
    thin_provisioned = data.vsphere_virtual_machine.template.disks.0.thin_provisioned
  }

  # Drive 1 (D)
  disk {
    label            = "disk1"
    unit_number      = 1
    size             = each.value.system_disk1_size
    eagerly_scrub    = data.vsphere_virtual_machine.template.disks.1.eagerly_scrub
    thin_provisioned = data.vsphere_virtual_machine.template.disks.1.thin_provisioned
  }

  # Template clone and OS settings
  clone {
    template_uuid = data.vsphere_virtual_machine.template.id

    customize {
      windows_options {
        computer_name         = each.value.system_name
        admin_password        = random_password.password.result
        join_domain           = each.value.system_domain
        domain_admin_user     = each.value.system_domain_admin_user
        domain_admin_password = each.value.system_domain_admin_password
        auto_logon            = true
      }

      network_interface {
        ipv4_address    = each.value.system_ipv4_address
        ipv4_netmask    = each.value.system_ipv4_netmask
        dns_server_list = each.value.system_dns_server_list
      }

      ipv4_gateway = each.value.system_ipv4_gateway
    }
  }
}

同样,这与您原来的 resource 块基本相同,但我添加了 for_each = var.virtual_machines,将 name 设置为 each.key 以使用地图键作为名称,并将所有其他对变量的引用替换为对 each.value 的属性的引用,它表示映射中当前元素的值。

在这种情况下,此资源块将声明以下资源实例:

  • vsphere_virtual_machine.server["server-0"]name = "server-0"
  • vsphere_virtual_machine.server["server-1"]name = "server-1"

请注意,Terraform 现在使用映射键来标识每个实例,因此如果您编辑与 .tfvars 文件中现有键相关联的值和 运行 terraform plan然后 Terraform 会理解,因为您打算使用该键更新现有对象,但如果您向地图添加一个全新的键,那么 Terraform 会理解,因为您打算创建一个新的虚拟机。随着时间的推移,您可以通过更新、创建和删除虚拟机在 var.virtual_machines.

中的相应条目来更新、创建和删除虚拟机

Terraform 期望您每次 运行 向它提供它负责管理的系统部分的完整状态的描述,因此没有您可以使用的模型只需要求 Terraform 添加一个新的虚拟机,而无需为所有现有虚拟机提供不变的配置。如果您省略现有的,那么 Terraform 会明白您打算销毁它们。