我因为这个睡不着,所以决定在这里试一试。我在与我的 Terraform 项目相同的主机上部署了 4 个 KVM 客户机。我遵循这两个指南https://titosoft.github.io/kvm/terraform-and-kvm/ https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9但我还是有些迷失。
我想要实现的只是构建 n 台客户机,这些客户机的名称是我在列表中预先定义的,例如 master01、worker01、worker02、worker03。我的池名为 guest_images。qcow2 文件、KVM 客户机和主机名应根据列表命名。
更新
设法解决了我的大部分问题。如果有人遇到同样的问题,这里是代码。最后一个未解决的问题:所有主机名目前都声明“ubuntu”。这应该通过 user_data 修复,但不起作用:user_data =“${data.template_file.user_data.rendered[count.index]}”
有人知道如何修复它吗?
provider "libvirt" {
uri = "qemu:///system"
}
variable "vm_machines" {
description = "Create machines with these names"
type = list(string)
default = ["master01", "worker01", "worker02", "worker03"]
}
# We fetch the latest ubuntu release image from their mirrors
resource "libvirt_volume" "ubuntu" {
name = "${var.vm_machines[count.index]}.qcow2"
count = length(var.vm_machines)
pool = "guest_images"
source = "http://cloud-images.ubuntu.com/releases/bionic/release-20191008/ubuntu-18.04-server-cloudimg-amd64.img"
format = "qcow2"
}
# Create a network for our VMs
resource "libvirt_network" "vm_network" {
name = "vm_network"
addresses = ["10.224.1.0/24"]
dhcp {
enabled = true
}
}
# Use CloudInit to add our ssh-key to the instance
resource "libvirt_cloudinit_disk" "commoninit" {
name = "commoninit.iso"
pool = "guest_images"
user_data = "${data.template_file.user_data.rendered}"
network_config = "${data.template_file.network_config.rendered}"
}
data "template_file" "user_data" {
template = "${file("${path.module}/cloud_init.cfg")}"
}
data "template_file" "network_config" {
template = "${file("${path.module}/network_config.cfg")}"
}
# Create the machine
resource "libvirt_domain" "ubuntu" {
count = length(var.vm_machines)
name = var.vm_machines[count.index]
memory = "8196"
vcpu = 2
cloudinit = "${libvirt_cloudinit_disk.commoninit.id}"
network_interface {
network_id = "${libvirt_network.vm_network.id}"
network_name = "vm_network"
}
# IMPORTANT
# Ubuntu can hang is a isa-serial is not present at boot time.
# If you find your CPU 100% and never is available this is why
console {
type = "pty"
target_port = "0"
target_type = "serial"
}
console {
type = "pty"
target_type = "virtio"
target_port = "1"
}
disk {
volume_id = libvirt_volume.ubuntu[count.index].id
}
graphics {
type = "vnc"
listen_type = "address"
autoport = "true"
}
}