使用Packer为 VMware Workstation Pro和 Oracle VM VirtualBox 自动化构建CentOS 8 虚拟机映像

使用Packer构建自动化的 CentOS 8 虚拟机映像。此 Packer 配置文件允许您为 VMware Workstation 和 Oracle VM VirtualBox 构建映像。

Kickstart

示例 Linux kickstart 配置文件,.cfg。

一个潜行高峰,一个kickstart的样子。

对于初学者来说,kickstart文件之于Linux,就像autounattend文件之于Windows一样。kickstart 文件是一个基于文本的配置文件,它能够以自动方式启用 Linux 操作系统安装。它们的扩展采用.cfg格式。

它以自动化的方式完成整个安装过程。它设置本地和时区,键盘布局,网络适配器配置和几个位和bob。

您找到的 kickstart 文件是混合了互联网上的蚕食,以及使用从之前的 CentOS 8.x.x 安装(无论是否自动化安装)生成的 kickstart 构建的。生成的 kickstart 将包含您在安装过程中选择的部分(但不是全部)选项。如果要从现有安装中提取配置文件,可以在此处找到它:

/root/anaconda-ks.cfg

现在,我们有了用于自动 Linux 安装的 kickstart 文件,现在我们需要提供将 kickstart 文件导入虚拟机的方法。我们不想手动执行此操作,因此我们寻找Packer来执行此操作。

查看 RHEL 的 kickstart 语法参考文档。它列出了所有命令和/或选项及其所需的语法。它极大地帮助我找到了自己的立足点。

软盘不再😔

Packer 为您提供了多个配置参考。这些是自动化操作系统的安装,配置和自定义的原因。你会发现的任何包装工指南,甚至是我即将推出的Windows指南,总是与软盘驱动器一起提供配置。对于基于文本的文件,它是快速而高效的,这就是它们所包含的全部内容!

那么,不再有软盘是怎么回事呢?从红帽企业 Linux 开始

8 或 RHEL 8 (其中 CentOS 是基於), 软盘驱动程序被省略了!如果您不相信,请阅读 RHEL 8 文档请点击此处。.我们现在必须通过使用替代我们以前的软盘生活方式来适应。

答案在于Packer托管和提供HTTP服务器的能力。这是让我们的自动化 CentOS 8.x.x 安装继续进行的关键。您可以通过指定要提供服务的目录来实现此目的,在我们的例子中,脚本文件夹。它将打开一个随机端口(如果需要,您可以设置静态端口),瞧。您可以检查 Packer 的输出以确定 IP 地址和端口 - 然后,如果您愿意,可以访问这些地址和端口。

打包程序在 CentOS VM 的端口 8957 上启动 HTTP 服务器,在 Windows 命令行中完成。

打包程序在端口 8957 上启动 HTTP 服务器以提供目录。

如果你不喜欢HTTP,你可以去做动态ISO。Packer可以做到这一点,但我承认我从来没有尝试过这个功能(我会在某个时候学习并添加它)。但是,我确实尝试了静态ISO;我留下了一些配置注释,如果你想使用它。这是狗屎,因为对kickstart的任何更改都需要您修改静态ISO(其中包含kickstart文件)以包含更改。

有关 HTTP 配置的更多详细信息,请访问此处获取 Packer 文档。

ks.cfg

# By Daniel Martins 01/03/2021
#
# Version=RHEL8
#
# KICKSTART syntax reference:
# https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/performing_an_advanced_rhel_installation/kickstart-commands-and-options-reference_installing-rhel-as-an-experienced-user

# Install new system using the first optical drive 
cdrom 

# Perform kickstart install in text mode (optional) (graphical by default)
text 

# Accept EULA without user interaction (optional)
eula --agreed

# Set language to use during installation and the default language to use on the installed system (required)
lang en_GB.UTF-8

# Set system keyboard type or layout (required)
keyboard --vckeymap=gb --xlayouts='gb'

# Configure network information for target system and activate network devices in the installer environment (optional)
# --device	        device to be activated and or configured with the network command
# --onboot          enable device at a boot time.
# --bootproto       method to obtain networking configuration for device (default dhcp).
# --activate        activate this device in the installation environment.
# --noipv6	        disable IPv6 on this device.
# --hostname        host name for the installed system.
# To use static IP configuration:
# network --bootproto=static --ip=10.0.2.15 --netmask=255.255.255.0 --gateway=10.0.2.254 --nameserver 192.168.2.1,192.168.3.1
network --device ens192 --onboot yes --bootproto dhcp --activate --noipv6 --hostname=CentOS8PackerTemplate

# Root password (required)
rootpw packer

# Configure firewall settings for the system (optional)
# firewall --enabled --ssh
# --enabled         reject incoming connections that are not in response to outbound requests.
# --ssh		        allow sshd service through the firewall.
# --disabled        do not configure any iptables rules.
firewall --disabled

# Set up the authentication options for the system (required)
# --enableshadow        enable shadowed passwords by default
# --passalgo		    hash / crypt algorithm for new passwords
# authconfig --enableshadow --passalgo=sha512

# State of SELinux on the installed system (optional)
# --disabled     disables SELinux completely on the system.
selinux --disabled

# Do not configure the X Window System
skipx

# Set the system time zone (required)
timezone Asia/Shanghai --isUtc
# Add a user named packer
user --groups=wheel --name=packer --password=packer --gecos="packer"

# Create partitions automatically, the automatically created partitions are:
# a root (/) partition (1 GB or larger)
# a swap partition
# an appropriate /boot partition for the architecture
# On large enough drives (50 GB and larger), this also creates a /home partition
autopart

# Initialize the first drive (optional)
# --all             erases all partitions from the system.
# --initlabel       initializes a disk (or disks) by creating a default disk label for all disks in their respective architecture that have been designated for formatting
clearpart --all --initlabel

# Reboot after the installation is complete (optional)
# --eject	    attempt to eject CD or DVD media before rebooting
reboot --eject

# Install packages.
%packages --ignoremissing 
@Core
bind-utils
unzip
curl
nano
net-tools
traceroute
wget

# Remove unnecessary firmware
# Taken from https://github.com/tvories/packer-vsphere-hcl/blob/master/boot_config/centos8/centos8-ks.cfg
-aic94xx-firmware
-atmel-firmware
-b43-openfwwf
-bfa-firmware
-ipw2100-firmware
-ipw2200-firmware
-ivtv-firmware
-iwl100-firmware
-iwl1000-firmware
-iwl3945-firmware
-iwl4965-firmware
-iwl5000-firmware
-iwl5150-firmware
-iwl6000-firmware
-iwl6000g2a-firmware
-iwl6050-firmware
-libertas-usb8388-firmware
-ql2100-firmware
-ql2200-firmware
-ql23xx-firmware
-ql2400-firmware
-ql2500-firmware
-rt61pci-firmware
-rt73usb-firmware
-xorg-x11-drv-ati-firmware
-zd1211-firmware
%end 

# Run
%post
sudo yum update -y
# check IT onenote for other bits like banner etc.
%end

%anaconda
pwpolicy root --minlen=6 --minquality=1 --notstrict --nochanges --notempty
pwpolicy user --minlen=6 --minquality=1 --notstrict --nochanges --emptyok
pwpolicy luks --minlen=6 --minquality=1 --notstrict --nochanges --notempty
%end
#version=RHEL8
# Use graphical install
graphical

repo --name="AppStream" --baseurl=file:///run/install/sources/mount-0000-cdrom/AppStream

%packages
@^minimal-environment
kexec-tools

%end

# Keyboard layouts
keyboard --xlayouts='cn'
# System language
lang zh_CN.UTF-8

# Network information
network  --hostname=localhost.localdomain

# Use CDROM installation media
cdrom

# Run the Setup Agent on first boot
firstboot --enable

ignoredisk --only-use=sda
autopart
# Partition clearing information
clearpart --none --initlabel


reboot --eject

# System timezone
timezone America/New_York --isUtc

network --device ens160 --onboot yes --bootproto dhcp --activate --noipv6 --hostname=CentOS8Packer

# Root password
rootpw --iscrypted $6$qC9lB22EyX3vb0wO$z/XXG4NZvVMz1wEFNfwYig9t0sYhzFMIfXkNfNAoBqxjfCY1USH2POrBnowaIC5w5QG0oYFnW3Ml6Ker/718y1
user --groups=wheel --name=packer --password=$6$AFD79/F4mP11CTLX$YgD6rTSaDj/kI0OIe22JhrlhYkBxMuut3phOGjQVx6IAtYrwGiVMAkEIY7HNWIiwi3r1JxZRlYJZ8vqJUtkZN0 --iscrypted --gecos="packer"

%addon com_redhat_kdump --enable --reserve-mb='auto'

%end

%anaconda
pwpolicy root --minlen=6 --minquality=1 --notstrict --nochanges --notempty
pwpolicy user --minlen=6 --minquality=1 --notstrict --nochanges --emptyok
pwpolicy luks --minlen=6 --minquality=1 --notstrict --nochanges --notempty
%end

centos8.json

{
  "variables": {
      "boot_wait": "5s",
      "disk_size": "40960",
      "iso_checksum": "5d61940668bc5e40d1c974e42d39f048",
      "iso_url": "file://F:\\CentOS-Stream-8-x86_64-20211206-dvd1.iso",
      "memsize": "1024",
      "numvcpus": "1",
      "ssh_password" : "packer",
      "ssh_username" : "packer",
      "vm_name": "CentOS-Stream-8-x86_64-20211206"
    },
    "builders": [
      {
        "type": "vmware-iso",
        "boot_command": [
          "<tab><bs><bs><bs><bs><bs>text ks=http://{{ .HTTPIP }}:{{ .HTTPPort }}/ks.cfg<enter><wait>"
        ],
        "boot_wait": "{{ user `boot_wait` }}",
        "disk_size": "{{ user `disk_size` }}",
        "disk_type_id": "0",
        "guest_os_type": "centos-64",
        "headless": false,
        "http_directory": "http",
        "iso_checksum": "{{ user `iso_checksum` }}",
        "iso_url": "{{ user `iso_url` }}",
        "shutdown_command": "echo 'packer'|sudo -S /sbin/halt -h -p",
        "ssh_password": "{{ user `ssh_password` }}",
        "ssh_port": 22,
        "ssh_username": "{{ user `ssh_username` }}",
        "ssh_timeout": "30m",
        "vm_name": "{{ user `vm_name` }}",
        "vmx_data": {
          "memsize": "{{ user `memsize` }}",
          "numvcpus": "{{ user `numvcpus` }}",
          "virtualHW.version": "14"
        }
      },
      {
        "type": "virtualbox-iso",
        "boot_command": [
          "<tab><bs><bs><bs><bs><bs>text ks=http://{{ .HTTPIP }}:{{ .HTTPPort }}/ks.cfg<enter><wait>"
        ],
        "boot_wait": "{{ user `boot_wait` }}",
        "disk_size": "{{ user `disk_size` }}",
        "guest_os_type": "RedHat_64",
        "headless": false,
        "http_directory": "http",
        "iso_checksum": "{{ user `iso_checksum` }}",
        "iso_url": "{{ user `iso_url` }}",
        "shutdown_command": "echo 'packer'|sudo -S /sbin/halt -h -p",
        "ssh_password": "{{ user `ssh_password` }}",
        "ssh_port": 22,
        "ssh_username": "{{ user `ssh_username` }}",
        "ssh_timeout": "30m",
        "vm_name": "{{ user `vm_name` }}",
        "vboxmanage": [
          ["modifyvm", "{{.Name}}", "--memory", "{{ user `memsize` }}"],
          ["modifyvm", "{{.Name}}", "--cpus", "{{ user `numvcpus` }}"]
        ]
      }
    ],
  "provisioners": [
    {
      "type": "shell",
      "execute_command": "echo 'packer'|{{.Vars}} sudo -S -E bash '{{.Path}}'",
      "inline": [
        "dnf -y update"
      ]
    }
  ]
}

用于创建自动 VM 映像的命令:

要使用 VMware Workstation 创建 CentOS 8 VM 映像,请使用以下命令:

cd c:\packer-CentOS8
packer build -only=vmware-iso centos8.json

要使用Oracle VM VirtualBox创建CentOS 8 VM映像,请使用以下命令:

cd c:\packer-CentOS8
packer build -only=virtualbox-iso centos8.json

如果省略关键字"-only=",则会创建VMware Workstation 和Virtualbox VMs虚拟机。

构建输出:


F:\packer-CentOS8>packer build -only=vmware-iso centos8.json
Warning: Warning when preparing build: "vmware-iso"

Your vmx data contains the following variable(s), which Packer normally sets
when it generates its own default vmx template. This may cause your build to
fail or behave unpredictably: numvcpus, memsize, virtualHW.version


vmware-iso: output will be in this color.

==> vmware-iso: Retrieving ISO
==> vmware-iso: Trying file://F:\CentOS-Stream-8-x86_64-20211206-dvd1.iso
==> vmware-iso: Trying file://F:/CentOS-Stream-8-x86_64-20211206-dvd1.iso?checksum=md5%3A5d61940668bc5e40d1c974e42d39f048
==> vmware-iso: file://F:/CentOS-Stream-8-x86_64-20211206-dvd1.iso?checksum=md5%3A5d61940668bc5e40d1c974e42d39f048 => F:/CentOS-Stream-8-x86_64-20211206-dvd1.iso
==> vmware-iso: Configuring output and export directories...
==> vmware-iso: Creating required virtual machine disks
==> vmware-iso: Building and writing VMX file
==> vmware-iso: Starting HTTP server on port 8699
==> vmware-iso: Starting virtual machine...
==> vmware-iso: Connecting to VNC...
==> vmware-iso: Waiting 5s for boot...
==> vmware-iso: Typing the boot command over VNC...
==> vmware-iso: Waiting for SSH to become available...
==> vmware-iso: Connected to SSH!
==> vmware-iso: Provisioning with shell script: C:\Users\ADMINI~1\AppData\Local\Temp\packer-shell3999798490
==> vmware-iso:
==> vmware-iso: We trust you have received the usual lecture from the local System
==> vmware-iso: Administrator. It usually boils down to these three things:
==> vmware-iso:
==> vmware-iso:     #1) Respect the privacy of others.
==> vmware-iso:     #2) Think before you type.
==> vmware-iso:     #3) With great power comes great responsibility.
==> vmware-iso:
    vmware-iso: Last metadata expiration check: 0:06:10 ago on Wed 22 Dec 2021 08:19:28 CST.
    vmware-iso: Dependencies resolved.
    vmware-iso: Nothing to do.
    vmware-iso: Complete!
==> vmware-iso: [sudo] password for packer:
==> vmware-iso: Gracefully halting virtual machine...
    vmware-iso: Waiting for VMware to clean up after itself...
==> vmware-iso: Deleting unnecessary VMware files...
    vmware-iso: Deleting: output-vmware-iso\vm.scoreboard
    vmware-iso: Deleting: output-vmware-iso\vmware.log
==> vmware-iso: Compacting all attached virtual disks...
    vmware-iso: Compacting virtual disk 1
==> vmware-iso: Cleaning VMX prior to finishing up...
    vmware-iso: Disabling VNC server...
==> vmware-iso: Skipping export of virtual machine...
Build 'vmware-iso' finished after 26 minutes 55 seconds.

==> Wait completed after 26 minutes 55 seconds

==> Builds finished. The artifacts of successful builds are:
--> vmware-iso: VM files in directory: output-vmware-iso

F:\packer-CentOS8>

默认凭据

此 VM 映像的默认凭据为:

UsernamePassword
packerpacker
rootpacker

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值