我尝试使用KVM的Terraform入门(libvirt提供者)

目标

作为毕业研究的一部分,我们需要制作一个能够最终实现Kubernetes自动集群构建的解决方案。我们计划使用terraform进行配置管理。

安装

以下仅供参考

 

$ sudo apt-get -y update && sudo apt-get install -y gnupg software-properties-common
wget -O- https://apt.releases.hashicorp.com/gpg | \
gpg --dearmor | \
sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg
gpg --no-default-keyring \
--keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg \
--fingerprint
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \
https://apt.releases.hashicorp.com $(lsb_release -cs) main" | \
sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update
sudo apt-get -y install terraform

更改/etc/libvirt/qemu.conf的设置

将security_driver更改为”none”。
重新启动libvirt可以使用以下命令。

sudo systemd restart libvirt-bin

确认

$ terraform -v
Terraform v1.5.0
on linux_amd64

安装libvirt-provider

terraform {
  required_providers {
    libvirt = {
      source = "dmacvicar/libvirt"
      version = "0.7.1"
    }
  }
}

如果要操作的目标位于另一台主机上。

provider "libvirt" {
  uri = "qemu+ssh://shoma@172.24.20.3/system"
}

組成文件的最小組成

provider "libvirt" {
  uri = "qemu+ssh://shoma@172.24.20.3/system"
}

resource "libvirt_volume" "os-image" {
  name = "terraform-disk.qcow2"
  source = "https://cloud-images.ubuntu.com/bionic/current/bionic-server-cloudimg-amd64.img"
  format = "qcow2"
}

resource "libvirt_domain" "domain-testvm" {
  name = "ubuntu-terraform"
  memory = 2048
  vcpu = 2

  disk { volume_id = libvirt_volume.os-image.id }

  network_interface {
    network_name = "default"
  }

  console {
    type = "pty"
    target_port = "0"
  }

  graphics {
    type = "spice"
    listen_type = "address"
    autoport = "true"
  }
}

确认

root@r620-shoma-001:/home/shoma/terraform# virsh list
 Id    Name                    State
----------------------------------------
223   ubuntu-terraform-1      running

创建多个虚拟机

provider "libvirt" {
  uri = "qemu+ssh://shoma@172.24.20.3/system"
}

resource "libvirt_volume" "os-image" {
  count = 3
  name   = "${format("terraform-vm%02d.qcow2", count.index + 1)}"
  source = "https://cloud-images.ubuntu.com/bionic/current/bionic-server-cloudimg-amd64.img"
  format = "qcow2"
}

resource "libvirt_domain" "terraform-vm" {
  count = 3
  name = "${format("ubuntu-terraform%02d", count.index + 1)}"
  memory = 2048
  vcpu = 2

  disk { volume_id = libvirt_volume.os-image[count.index].id }

  network_interface {
    network_name = "default"
  }

  console {
    type = "pty"
    target_port = "0"
  }

  graphics {
    type = "spice"
    listen_type = "address"
    autoport = "true"
  }
}

确认

root@r620-shoma-001:/home/shoma/terraform# virsh list
 Id    Name                    State
----------------------------------------
 237   ubuntu-terraform02      running
 238   ubuntu-terraform03      running
 239   ubuntu-terraform01      running

文献引用

 

bannerAds