notes/devops/sandbox/terraform/libvirt/getting-started/conf.tf

139 lines
3.1 KiB
HCL

terraform {
required_providers {
libvirt = {
source = "dmacvicar/libvirt"
version = "~> 0.7.0"
}
}
}
provider "libvirt" {
uri = "qemu:///system"
}
variable "prefix" {
default = "libvirt_getting_started"
}
# see https://github.com/dmacvicar/terraform-provider-libvirt/blob/v0.6.14/website/docs/r/network.markdown
resource "libvirt_network" "libvirt_getting_started" {
name = var.prefix
mode = "nat"
domain = "libvirt_getting_started.test"
addresses = ["10.17.3.0/24"]
dhcp {
enabled = false
}
dns {
enabled = true
local_only = false
}
}
resource "libvirt_pool" "debian" {
name = "debian-getting-started"
type = "dir"
path = "/var/lib/libvirt/images/terraform-provider-libvirt-pool-debian"
}
# We fetch the latest debian release image from their mirrors
resource "libvirt_volume" "debian-qcow2" {
name = "debian-qcow2"
pool = libvirt_pool.debian.name
source = "https://cloud.debian.org/images/cloud/buster/latest/debian-10-genericcloud-amd64.qcow2"
format = "qcow2"
}
data "template_file" "user_data" {
template = file("${path.module}/cloud_init.cfg")
}
data "template_file" "network_config" {
template = file("${path.module}/network_config.cfg")
}
# for more info about paramater check this out
# https://github.com/dmacvicar/terraform-provider-libvirt/blob/master/website/docs/r/cloudinit.html.markdown
# Use CloudInit to add our ssh-key to the instance
# you can add also meta_data field
resource "libvirt_cloudinit_disk" "commoninit" {
name = "commoninit.iso"
user_data = data.template_file.user_data.rendered
network_config = data.template_file.network_config.rendered
pool = libvirt_pool.debian.name
}
resource "libvirt_domain" "libvirt_getting_started" {
name = "debian-terraform"
memory = "512"
vcpu = 1
cloudinit = libvirt_cloudinit_disk.commoninit.id
network_interface {
network_id = libvirt_network.libvirt_getting_started.id
wait_for_lease = true
addresses = ["10.17.3.2"]
}
# # IMPORTANT: this is a known bug on cloud images, since they expect a console
# # we need to pass it
# # https://bugs.launchpad.net/cloud-images/+bug/1573095
console {
type = "pty"
target_port = "0"
target_type = "serial"
}
console {
type = "pty"
target_type = "virtio"
target_port = "1"
}
connection {
type = "ssh"
user = "root"
host = self.network_interface[0].addresses[0] # see https://github.com/dmacvicar/terraform-provider-libvirt/issues/660
public_key = file("~/.ssh/aravinth.pub")
}
disk {
volume_id = libvirt_volume.debian-qcow2.id
}
graphics {
type = "vnc"
listen_type = "address"
}
boot_device {
dev = ["hd", "network"]
}
network_interface {
network_id = libvirt_network.libvirt_getting_started.id
wait_for_lease = true
addresses = ["10.17.3.2"]
}
}
output "ip" {
value = length(libvirt_domain.libvirt_getting_started.network_interface[0].addresses) > 0 ? libvirt_domain.libvirt_getting_started.network_interface[0].addresses[0] : ""
}