Post

Guia Avançado: Template Debian 13 com UEFI, LVM, Packer e Terraform (Parte 1/2)

Domine a criação de imagens Debian 13 com suporte a UEFI e LVM usando Packer. Provisione VMs modernas com Terraform e virt-install de forma automatizada.

Guia Avançado: Template Debian 13 com UEFI, LVM, Packer e Terraform (Parte 1/2)

Introdução

Este guia é uma variação do nosso tutorial anterior,Guia Completo: Criando um Template Debian 13 (BIOS+LVM) com Packer e Terraform (Parte 1/2), focado em criar uma imagem de máquina virtual (VM) para o Debian 13 “Trixie” com suporte nativo a UEFI. A automação será feita com o Packer para gerar um template otimizado com particionamento LVM, pronto para infraestruturas modernas.

O resultado será uma imagem qcow2 compactada e configurada para boot UEFI, que servirá como base para provisionar VMs de forma rápida e consistente com KVM/Libvirt.


1. Pré-requisitos e Ambiente

Os pré-requisitos de software são os mesmos da versão anterior (Packer, Terraform, KVM/Libvirt). No entanto, para o build UEFI, há um requisito adicional de sistema:

  • Pacote OVMF: É necessário ter o firmware UEFI para QEMU instalado.
    • Em Debian/Ubuntu: sudo apt install ovmf
    • Em Fedora/RHEL: sudo dnf install edk2-ovmf

Nota: O ambiente de teste para este guia foi uma estação de trabalho com Ubuntu 24.04.


2. Estrutura do Projeto Packer

Vamos criar uma estrutura de diretórios dedicada para a versão UEFI do nosso template.

1
2
3
4
5
6
7
8
# Crie o diretório de trabalho
mkdir -p ~/Workspace/packer/qemu/debian/debian13-lvm-uefi

# Navegue até o diretório
cd ~/Workspace/packer/qemu/debian/debian13-lvm-uefi

# Crie os arquivos de configuração HCL
touch debian-template.pkr.hcl packer.pkr.hcl preseed.cfg provisioners.pkr.hcl variables.pkr.hcl

3. Configuração do Packer

As configurações são similares à versão BIOS, mas com ajustes importantes para o UEFI.

3.1. packer.pkr.hcl (Plugins Necessários)

Este arquivo define a versão do Packer e os plugins necessários, neste caso, o plugin QEMU.

1
2
3
4
5
6
7
8
9
10
packer {
  required_version = ">= 1.7.0, < 2.0.0"

  required_plugins {
    qemu = {
      source  = "github.com/hashicorp/qemu"
      version = ">= 1.0.0, < 2.0.0"
    }
  }
}

3.2. variables.pkr.hcl (Variáveis de Configuração)

Aqui centralizamos todas as variáveis para facilitar a customização do template, desde o hardware da VM até as credenciais de acesso. Adicionamos uma nova seção para os caminhos do firmware OVMF, com uma lógica de fallback para detectar automaticamente a localização correta em diferentes distribuições Linux.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#############################################
# Configuração de ISO e Cache
#############################################
variable "iso_file" {
  type        = string
  description = "Nome do arquivo ISO a ser utilizado para a instalação."
  default     = "debian-13.0.0-amd64-netinst.iso"
}

variable "iso_path" {
  type        = string
  description = "Caminho HTTP ou local para o diretório que contém o arquivo ISO."
  default     = "http://cdimage.debian.org/cdimage/release/current/amd64/iso-cd"
}

variable "iso_checksum" {
  type        = string
  description = "Checksum do arquivo ISO. Pode ser um valor direto ou um caminho para um arquivo de checksum."
  default     = "file:http://cdimage.debian.org/cdimage/release/current/amd64/iso-cd/SHA512SUMS"
}

variable "packer_cache_dir" {
  type        = string
  description = "Diretório para o cache do Packer, usado para armazenar arquivos baixados como ISOs."
  default     = "${env("PACKER_CACHE_DIR")}"
}

variable "preseed_file" {
  type        = string
  description = "Nome do arquivo preseed para automação da instalação do sistema operacional."
  default     = "preseed.cfg"
}

#############################################
# Hardware da VM
#############################################
variable "cpus" {
  type    = number
  default = 1
}

variable "memory" {
  type    = number
  default = 1024
}

variable "disk_size" {
  type    = number
  default = 4096
}

variable "qemu_binary" {
  type    = string
  default = "qemu-system-x86_64"
}

variable "vm_name" {
  type    = string
  default = "trixie"
}

variable "headless" {
  type    = bool
  default = false
}

#############################################
# Rede e Acesso
#############################################
variable "communicator" {
  type    = string
  default = "ssh"
}

variable "domain" {
  type    = string
  default = ""
}

variable "host_ports" {
  type        = string
  description = "Intervalo de portas para acesso SSH (ex: '2222-4444')"
  default     = "2222-4444"
}

variable "http_ports" {
  type        = string
  description = "Intervalo de portas para servidor HTTP (ex: '8000-9000')"
  default     = "8000-9000"
}

variable "vnc_vrdp_bind_address" {
  type    = string
  default = "127.0.0.1"
}

variable "vnc_vrdp_ports" {
  type        = string
  description = "Intervalo de portas para VNC (ex: '5900-6000')"
  default     = "5900-6000"
}

#############################################
# SSH e Provisionamento
#############################################
variable "ssh_username" {
  type    = string
  default = "debian"
}

variable "ssh_password" {
  type    = string
  default = "debian"
}

variable "ssh_fullname" {
  type    = string
  default = "Debian User"
}

variable "ssh_port" {
  type    = number
  default = 22
}

variable "ssh_timeout" {
  type    = string
  default = "60m"
}

variable "ssh_handshake_attempts" {
  type    = number
  default = 10
}

variable "ssh_keep_alive_interval" {
  type    = string
  default = "5s"
}

variable "ssh_agent_auth" {
  type    = bool
  default = false
}

variable "ssh_clear_authorized_keys" {
  type    = bool
  default = false
}

variable "ssh_disable_agent_forwarding" {
  type    = bool
  default = false
}

variable "ssh_file_transfer_method" {
  type    = string
  default = "scp"
}

variable "ssh_pty" {
  type    = bool
  default = false
}

#############################################
# Localização e Sistema
#############################################
variable "language" {
  type    = string
  default = "pt_BR"
}

variable "country" {
  type    = string
  default = "BR"
}

variable "locale" {
  type    = string
  default = "pt_BR.UTF-8"
}

variable "keyboard" {
  type    = string
  default = "br"
}

variable "timezone" {
  type    = string
  default = "America/Sao_Paulo"
}

variable "system_clock_in_utc" {
  type    = bool
  default = true
}

variable "mirror" {
  type    = string
  default = "deb.debian.org"
}

#############################################
# Path OVMF - Com fallback para diferentes SOs
#############################################
variable "ovmf_code" {
  type        = string
  description = "Caminho para o firmware OVMF_CODE (UEFI). Em Debian/Ubuntu: /usr/share/OVMF/OVMF_CODE_4M.fd, em Fedora/RHEL: /usr/share/edk2/ovmf/OVMF_CODE.fd"
  default     = "/usr/share/OVMF/OVMF_CODE_4M.fd"
}

variable "ovmf_vars" {
  type        = string
  description = "Caminho para o firmware OVMF_VARS (NVRAM UEFI)."
  default     = "/usr/share/OVMF/OVMF_VARS_4M.fd"
}

# Fallback automático para paths alternativos
locals {
  ovmf_code_fallback = fileexists(var.ovmf_code) ? var.ovmf_code : "/usr/share/edk2/ovmf/OVMF_CODE.fd"
  ovmf_vars_fallback = fileexists(var.ovmf_vars) ? var.ovmf_vars : "/usr/share/edk2/ovmf/OVMF_VARS.fd"
}

#############################################
# Tempos de Espera
#############################################
variable "boot_wait" {
  type    = string
  default = "3s"
}

variable "shutdown_timeout" {
  type    = string
  default = "5m"
}

variable "start_retry_timeout" {
  type    = string
  default = "5m"
}

#############################################
# Saída
#############################################
locals {
  output_directory = "build/${var.vm_name}-${formatdate("YYYY-MM-DD", timestamp())}"
}

3.3. debian-template.pkr.hcl (Fonte da Imagem - Source)

Este é o coração do nosso build. Ele define como o Packer irá construir a VM, incluindo comandos de boot, hardware, configurações de rede e como se conectar via SSH.

Este arquivo contém as mudanças mais significativas:

  1. boot_command: Modificado para interagir com o shell do GRUB em modo UEFI.
  2. Configurações de EFI: Novas diretivas (efi_boot, efi_firmware_code, efi_firmware_vars) para habilitar o boot UEFI.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#############################################
# Fonte QEMU
#############################################
source "qemu" "debian" {
  boot_command = [
    "<wait><wait><wait>c<wait><wait><wait>",
    "linux /install.amd/vmlinuz ",
    "auto=true ",
    "url=http://:/${var.preseed_file} ",
    "hostname=${var.vm_name} ",
    "domain=${var.domain} ",
    "interface=auto ",
    "vga=788 noprompt quiet --<enter>",
    "initrd /install.amd/initrd.gz<enter>",
    "boot<enter>"
  ]
  boot_wait                    = var.boot_wait
  communicator                 = var.communicator
  cpus                         = var.cpus
  accelerator                  = "kvm"
  disk_cache                   = "writeback"
  disk_compression             = false
  disk_discard                 = "ignore"
  disk_interface               = "virtio-scsi"
  disk_size                    = var.disk_size
  format                       = "raw"
  headless                     = var.headless
  host_port_min                = split("-", var.host_ports)[0]
  host_port_max                = split("-", var.host_ports)[1]
  http_content                 = { "/${var.preseed_file}" = templatefile(var.preseed_file, { var = var }) }
  http_port_min                = split("-", var.http_ports)[0]
  http_port_max                = split("-", var.http_ports)[1]
  iso_checksum                 = var.iso_checksum
  iso_target_extension         = "iso"
  iso_target_path              = "${coalesce(var.packer_cache_dir, "/tmp")}/${var.iso_file}"
  iso_urls                     = ["${var.iso_path}/${var.iso_file}"]
  machine_type                 = "q35"
  efi_boot                     = true
  efi_firmware_code            = local.ovmf_code_fallback
  efi_firmware_vars            = local.ovmf_vars_fallback
  memory                       = var.memory
  net_device                   = "virtio-net"
  output_directory             = local.output_directory
  qemu_binary                  = var.qemu_binary
  shutdown_command             = "echo '${var.ssh_password}' | sudo -S poweroff"
  shutdown_timeout             = var.shutdown_timeout
  skip_compaction              = true
  skip_nat_mapping             = false
  ssh_agent_auth               = var.ssh_agent_auth
  ssh_clear_authorized_keys    = var.ssh_clear_authorized_keys
  ssh_disable_agent_forwarding = var.ssh_disable_agent_forwarding
  ssh_file_transfer_method     = var.ssh_file_transfer_method
  ssh_handshake_attempts       = var.ssh_handshake_attempts
  ssh_keep_alive_interval      = var.ssh_keep_alive_interval
  ssh_password                 = var.ssh_password
  ssh_port                     = var.ssh_port
  ssh_pty                      = var.ssh_pty
  ssh_timeout                  = var.ssh_timeout
  ssh_username                 = var.ssh_username
  use_default_display          = false
  vm_name                      = var.vm_name
  vnc_bind_address             = var.vnc_vrdp_bind_address
  vnc_port_min                 = split("-", var.vnc_vrdp_ports)[0]
  vnc_port_max                 = split("-", var.vnc_vrdp_ports)[1]
}

3.4. provisioners.pkr.hcl (Provisionamento Pós-instalação)

Após a instalação do sistema operacional, estes scripts são executados dentro da VM para configurar, atualizar e limpar a imagem antes de finalizá-la.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# Build
build {
  sources = ["source.qemu.debian"]

  provisioner "shell" {
    execute_command     = "echo '${var.ssh_password}' |  sudo -E -S ''"
    expect_disconnect   = true
    inline              = ["echo 'FS0:\\EFI\\debian\\grubx64.efi' > /boot/efi/startup.nsh"]
    inline_shebang      = "/bin/sh -e"
    start_retry_timeout = var.start_retry_timeout
  }

  provisioner "shell" {
    execute_command   = "echo '${var.ssh_password}' |  sudo -E -S ''"
    expect_disconnect = true
    inline = [
      "echo '${var.ssh_username} ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/99${var.ssh_username}",
      "chmod 0440 /etc/sudoers.d/99${var.ssh_username}"
    ]
    inline_shebang      = "/bin/sh -e"
    start_retry_timeout = var.start_retry_timeout
  }

  provisioner "shell" {
    execute_command     = "echo '${var.ssh_password}' |  sudo -E -S ''"
    expect_disconnect   = true
    inline              = ["apt-get update", "apt-get --yes dist-upgrade", "apt-get clean"]
    inline_shebang      = "/bin/sh -e"
    start_retry_timeout = var.start_retry_timeout
  }

  # Provisionador para generalizar e limpar a imagem antes de finalizar
  provisioner "shell" {
    execute_command = "echo '${var.ssh_password}' |  sudo -E -S ''"
    inline = [
      "echo '==> Generalizando a imagem para uso como template...'",

      "echo '--> Limpando e recriando /etc/hosts'",
      "truncate -s 0 /etc/hosts",
      "echo '127.0.0.1  localhost' >> /etc/hosts",
      "echo '::1        localhost ip6-localhost ip6-loopback' >> /etc/hosts",
      "echo 'ff02::1    ip6-allnodes' >> /etc/hosts",
      "echo 'ff02::2    ip6-allrouters' >> /etc/hosts",

      "echo '--> Resetando o hostname'",
      "truncate -s 0 /etc/hostname",
      "echo 'localhost' > /etc/hostname",
      
      "echo '--> Limpando configurações de rede específicas da build'",
      "cat > /etc/network/interfaces <<'EOF'",
      "# This file is intentionally left blank. Network is managed by cloud-init.",
      "source /etc/network/interfaces.d/*",
      "",
      "auto lo",
      "iface lo inet loopback",
      "EOF",
      
      "echo '--> Limpando o machine-id'",
      "truncate -s 0 /etc/machine-id",
      "rm -f /var/lib/dbus/machine-id",
      "ln -s /etc/machine-id /var/lib/dbus/machine-id",

      "echo '--> Limpando logs e arquivos temporários'",
      "cloud-init clean --logs --seed",
      "rm -rf /tmp/* /var/tmp/*",
      "find /var/log -type f -name '*.log' -delete",
    ]
    inline_shebang      = "/bin/sh -e"
    start_retry_timeout = var.start_retry_timeout
  }

  provisioner "shell" {
    execute_command     = "echo '${var.ssh_password}' |  sudo -E -S ''"
    expect_disconnect   = true
    inline              = ["dd if=/dev/zero of=/ZEROFILL bs=16M || true", "rm /ZEROFILL", "sync"]
    inline_shebang      = "/bin/sh -e"
    start_retry_timeout = var.start_retry_timeout
  }
}

4. Arquivo de Pré-configuração (Preseed) com Particionamento UEFI

A receita de particionamento no preseed.cfg é a mudança mais crítica. Para UEFI, precisamos de uma Partição de Sistema EFI (ESP).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# Locale Setup
d-i debian-installer/language string ${var.language}
d-i debian-installer/country string ${var.country}
d-i debian-installer/locale string ${var.locale}

# Keyboard Setup
d-i keyboard-configuration/xkb-keymap select ${var.keyboard}

# Clock Setup
d-i time/zone string ${var.timezone}
d-i clock-setup/utc boolean ${var.system_clock_in_utc}

# Network Setup
d-i netcfg/get_hostname string ${var.vm_name}
d-i netcfg/get_domain string
d-i netcfg/choose_interface select auto

# User Setup
d-i passwd/user-fullname string ${var.ssh_fullname}
d-i passwd/username string ${var.ssh_username}
d-i passwd/user-password password ${var.ssh_password}
d-i passwd/user-password-again password ${var.ssh_password}
d-i user-setup/allow-password-weak boolean true
d-i user-setup/encrypt-home boolean false
d-i passwd/root-login boolean false

# Package Setup
d-i hw-detect/load_firmware boolean false
d-i hw-detect/load_media boolean false
apt-cdrom-setup apt-setup/cdrom/set-first boolean false
d-i mirror/country string manual
d-i mirror/http/hostname string ${var.mirror}
d-i mirror/http/directory string /debian
d-i mirror/http/proxy string
d-i apt-setup/contrib boolean true
d-i apt-setup/non-free boolean true
tasksel tasksel/first multiselect ssh-server, standard
d-i pkgsel/include string sudo, unattended-upgrades, cloud-init, qemu-guest-agent
popularity-contest popularity-contest/participate boolean false

# Drive Setup
d-i partman-auto/disk string /dev/sda

# Forçar recriação limpa
d-i partman-lvm/device_remove_lvm boolean true
d-i partman-md/device_remove_md boolean true
d-i partman-auto/purge_lvm_from_device boolean true
d-i partman-partitioning/confirm_write_new_label boolean true

# Método de particionamento
d-i partman-auto/method string lvm
d-i partman-auto-lvm/new_vg_name string vg0
d-i partman-auto-lvm/guided_size string max

# Confirmar sem perguntar
d-i partman/choose_partition select finish
d-i partman/confirm boolean true
d-i partman/confirm_nooverwrite boolean true
d-i partman-lvm/confirm boolean true
d-i partman-lvm/confirm_nooverwrite boolean true

# Receita customizada
d-i partman-auto/choose_recipe select custom-lvm
d-i partman-auto/expert_recipe string custom-lvm :: \
  1 1 1 free \
    $bios_boot{ } method{ biosgrub } \
  . \
  512 512 512 fat32 \
    $primary{ } $lvmignore{ } \
    method{ efi } format{ } \
  . \
  1024 1024 1024 linux-swap \
    $lvmok{ } lv_name{ swap } in_vg{ vg0 } \
    method{ swap } format{ } \
  . \
  10240 10240 -1 ext4 \
    $lvmok{ } lv_name{ root } in_vg{ vg0 } \
    method{ format } format{ } use_filesystem{ } filesystem{ ext4 } \
    mountpoint{ / } \
  . 

# Grub
d-i grub-installer/only_debian boolean true
d-i grub-installer/with_other_os boolean true
d-i grub-installer/bootdev string default

# Final Setup
d-i finish-install/reboot_in_progress note

5. Construção e Finalização da Imagem

Com todos os arquivos configurados, podemos iniciar a construção da imagem.

5.1. Validar e Iniciar o Build

Execute os seguintes comandos para inicializar os plugins, validar a sintaxe e iniciar o processo de build.

1
2
3
4
5
6
7
8
9
10
11
# Inicializa os plugins do Packer
packer init .

# Valida a sintaxe dos arquivos de configuração
packer validate .

# Formata os arquivos para o padrão HCL
packer fmt .

# Inicia o build com log detalhado
PACKER_LOG=1 packer build .

5.2. Converter e Compactar a Imagem

Após o build, o Packer gerará uma imagem raw no diretório build/. O próximo passo é convertê-la para o formato qcow2 e compactá-la para otimizar o espaço em disco.

1
2
# O comando converte (-O qcow2) e compacta (-c) a imagem final
qemu-img convert -O qcow2 -c build/trixie-2025-08-23/trixie ~/kvm/templates/debian-13-uefi.qcow2

5.3. Verificar a Imagem Final

Por fim, verifique as informações da imagem qcow2 gerada. Note como o disk size (tamanho real) é significativamente menor que o virtual size (tamanho virtual), graças à compactação.

1
qemu-img info ~/kvm/templates/debian-13.qcow2
1
2
3
4
5
6
7
8
9
10
11
12
image: /home/gean/kvm/templates/debian-13.qcow2
file format: qcow2
virtual size: 4 GiB (4294967296 bytes)
disk size: 773 MiB
cluster_size: 65536
Format specific information:
    compat: 1.1
    compression type: zlib
    lazy refcounts: false
    refcount bits: 16
    corrupt: false
    extended l2: false

Próximos Passos

Na Parte 2 deste guia, Guia Avançado: Template Debian 13 com UEFI, LVM, Packer e Terraform (Parte 2/2), vamos explorar como usar este template para provisionar novas máquinas virtuais de forma automatizada usando virt-install e Terraform.

This post is licensed under CC BY 4.0 by the author.