使用KVM和Terraform对虚拟机进行详细配置设定
的是
在之前的文章中,我们介绍了如何使用terraform来操作KVM。本次我们将更加详细地讨论虚拟机的规划部署。
件所有可能项
请以符合以下要求的方式描述HCL。
-
- 使用libvirt-provider
-
- 使用cloud-image
-
- 使用cloud-init
网络设置
用户设置
VNC设置
太长不看
provider "libvirt" {
uri = "qemu+ssh://shoma@172.24.20.3/system"
}
resource "libvirt_volume" "os-image" {
count = 5
name = "${format("terraform-vm%02d.qcow2", count.index + 1)}"
# source = "/home/shoma/terraform/ubuntu1new.qcow2"
source = "https://cloud-images.ubuntu.com/releases/23.04/release-20230714/ubuntu-23.04-server-cloudimg-amd64.img"
format = "qcow2"
}
resource "libvirt_cloudinit_disk" "cloudinit_terraform-vm" {
count = 5
name = "${format("terraform-vm%02d.iso", count.index + 1)}"
pool = "default"
user_data = <<EOF
#cloud-config
hostname: "${format("terraform-vm%02d.qcow2", count.index + 1)}"
user: tmcit
password: tmcit
chpasswd: { expire: False }
ssh_pwauth: True
EOF
network_config = <<EOF
version: 2
ethernets:
ens3:
addresses:
- "${format("172.24.20.20%d/24", count.index + 1)}"
gateway4: 172.24.20.254
nameservers:
addresses: [172.24.2.51]
EOF
}
resource "libvirt_domain" "terraform-vm" {
count = 5
name = "${format("ubuntu-terraform%02d", count.index + 1)}"
memory = 2048
vcpu = 2
disk { volume_id = libvirt_volume.os-image[count.index].id }
cloudinit = libvirt_cloudinit_disk.cloudinit_terraform-vm[count.index].id
cpu {
mode = "host-passthrough"
}
network_interface {
bridge = "bridge1"
}
console {
type = "pty"
target_port = "0"
}
graphics {
type = "vnc"
listen_type = "address"
autoport = "true"
}
}
进行VNC连接
graphics {
type = "vnc"
listen_type = "address"
autoport = "true"
}
}

Cloud-init的应用
resource "libvirt_cloudinit_disk" "cloudinit_terraform-vm" {
count = 5
name = "${format("terraform-vm%02d.iso", count.index + 1)}"
pool = "default"
user_data = <<EOF
#cloud-config
hostname: "${format("terraform-vm%02d.qcow2", count.index + 1)}"
user: tmcit
password: tmcit
chpasswd: { expire: False }
ssh_pwauth: True
EOF
network_config = <<EOF
version: 2
ethernets:
ens3:
addresses:
- "${format("172.24.20.20%d/24", count.index + 1)}"
gateway4: 172.24.20.254
nameservers:
addresses: [172.24.2.51]
EOF
}
虚拟机规格的设定
resource "libvirt_domain" "terraform-vm" {
count = 5
name = "${format("ubuntu-terraform%02d", count.index + 1)}"
memory = 2048
vcpu = 2
disk { volume_id = libvirt_volume.os-image[count.index].id }
cloudinit = libvirt_cloudinit_disk.cloudinit_terraform-vm[count.index].id
cpu {
mode = "host-passthrough"
}
network_interface {
bridge = "bridge1"
}
console {
type = "pty"
target_port = "0"
}
graphics {
type = "vnc"
listen_type = "address"
autoport = "true"
}
}
当实行
会生成有以下IP地址的5台VM。
内存:2048
vCPU:2
-
- 172.24.20.201
-
- 172.24.20.202
-
- 172.24.20.203
-
- 172.24.20.204
- 172.24.20.205