环境准备
- 准备一台 linux 物理机
- 安装对应的 packer 软件
- 安装对应的 qemu kvm 软件
镜像构建
分别将以下 hcl 文件以及 user-data 文件放置在提前准备好的目录当中
- Packer Hcl 文件
packer {
required_version = ">= 1.7.0, < 2.0.0"
required_plugins {
qemu = {
source = "github.com/hashicorp/qemu"
version = ">= 1.0.0, < 2.0.0"
}
}
}
variable "vm_name" {
type = string
default = "ubuntu-2004.qcow2"
}
source "qemu" "test" {
iso_url = "https://releases.ubuntu.com/20.04/ubuntu-20.04.5-live-server-amd64.iso"
iso_checksum = "5035be37a7e9abbdc09f0d257f3e33416c1a0fb322ba860d42d74aa75c3468d4"
vm_name = var.vm_name
output_directory = "output"
http_directory = "http"
boot_wait = "2s"
boot_command = [
"<esc><esc><esc>",
"<enter><wait>",
"/casper/vmlinuz ",
"initrd=/casper/initrd ",
"autoinstall ds=nocloud-net;s=http://{{.HTTPIP}}:{{.HTTPPort}}/",
"<enter>"
]
shutdown_command = "echo 'packer' | sudo -S shutdown -P now"
headless = true
format = "qcow2"
accelerator = "kvm"
qemu_binary = "/usr/libexec/qemu-kvm"
qemu_img_args {
convert = [
"-m",
"8"
]
}
ssh_username = "root"
ssh_password = "Root123!"
ssh_timeout = "30m"
vnc_bind_address = "0.0.0.0"
cpus = 8
memory = 8192
net_device = "virtio-net"
disk_size = "100G"
disk_compression = true
}
build {
name = "ubuntu20-04"
sources = [
"source.qemu.test"
]
provisioner "shell" {
pause_before = "20s"
inline = ["echo 'build success'"]
}
}
- Ubuntu auto install user-data 文件
#cloud-config
autoinstall:
version: 1
early-commands:
- hostnamectl set-hostname ubuntu # update hostname even for the installer environment
- dhclient # re-register the updated hostname
identity:
# hostname of the system
hostname: ubuntu
# root doesn't work
username: ubuntu
# ubuntu
password: "$6$FhcddHFVZ7ABA4Gi$MhQrLRAMZI65UOGGwxyCYRgolj13tIHC3/MRfyQQlP4nD9jgIdn63Ol2qlO3I8I/Gfdcsg7k58dTYOzz3LeqJ."
ssh:
install-server: true
allow-pw: true
user-data:
timezone: Asia/Shanghai
disable_root: false
ssh_pwauth: true
users:
- name: root
lock_passwd: false
plain_text_passwd: Root123!
- name: ubuntu
lock_passwd: false
plain_text_passwd: Root123!
sudo: ALL=(ALL) NOPASSWD:ALL
network:
version: 2
ethernets:
zz-all-en:
match:
name: "en*"
dhcp4: true
dhcp-identifier: mac
zz-all-eth:
match:
name: "eth*"
dhcp4: true
dhcp-identifier: mac
keyboard:
layout: en
variant: us
locale: en_US
storage:
swap:
size: 0
layout:
name: direct
packages:
- bc
- cloud-init
- git
- curl
- wget
- openssl
- vim
late-commands:
- sed -i -e 's/^#\?PasswordAuthentication.*/PasswordAuthentication yes/g' /target/etc/ssh/sshd_config
- sed -i -e 's/^#\?PermitRootLogin.*/PermitRootLogin yes/g' /target/etc/ssh/sshd_config
- sed -i 's/^#*\(send dhcp-client-identifier\).*$/\1 = hardware;/' /etc/dhcp/dhclient.conf
- echo 'ubuntu ALL=(ALL) NOPASSWD:ALL' > /target/etc/sudoers.d/ubuntu
- curtin in-target --target=/target -- chmod 440 /etc/sudoers.d/ubuntu
- 执行 Packer 打包命令
packer build qemu.pkr.hcl