Merge pull request #3 from ddelnano/add-examples-of-using-packer-builder

Add start of centos 8 and ubuntu 20.04 examples
This commit is contained in:
Dom Del Nano 2021-01-03 00:19:58 -08:00 committed by GitHub
commit 1a562a2190
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 149 additions and 307 deletions

View File

@ -609,22 +609,17 @@ func (self *VM) SetPlatform(params map[string]string) (err error) {
} }
func ConnectNetwork(c *Connection, networkRef xenapi.NetworkRef, vmRef xenapi.VMRef, device string) (*xenapi.VIFRef, error) { func ConnectNetwork(c *Connection, networkRef xenapi.NetworkRef, vmRef xenapi.VMRef, device string) (*xenapi.VIFRef, error) {
// Create the VIF
// vif_rec["other_config"] = make(xmlrpc.Struct)
// vif_rec["qos_algorithm_params"] = make(xmlrpc.Struct)
vif, err := c.client.VIF.Create(c.session, xenapi.VIFRecord{ vif, err := c.client.VIF.Create(c.session, xenapi.VIFRecord{
Network: networkRef, Network: networkRef,
VM: vmRef, VM: vmRef,
MAC: "",
Device: device, Device: device,
MTU: 1504, LockingMode: xenapi.VifLockingModeNetworkDefault,
QosAlgorithmType: "",
}) })
if err != nil { if err != nil {
return nil, err return nil, err
} }
log.Printf("Created the following VIF: %s", vif)
return &vif, nil return &vif, nil
} }

View File

@ -170,7 +170,8 @@ func (self *stepCreateInstance) Run(state multistep.StateBag) multistep.StepActi
_, err = xscommon.ConnectNetwork(c, network, instance, "0") _, err = xscommon.ConnectNetwork(c, network, instance, "0")
if err != nil { if err != nil {
ui.Say(err.Error()) ui.Error(fmt.Sprintf("Failed to create VIF with error: %v", err))
return multistep.ActionHalt
} }
} else { } else {

View File

@ -2,7 +2,7 @@
layout: "docs" layout: "docs"
page_title: "XenServer Builder (from an ISO)" page_title: "XenServer Builder (from an ISO)"
description: |- description: |-
The XenServer Packer builder is able to create XenServer virtual machines and export them either as an XVA or a VDI, starting from an ISO image. The XenServer Packer builder is able to create XenServer virtual machines and export them either as an XVA or a VDI and create VM templates starting from an ISO image.
--- ---
# XenServer Builder (from an ISO) # XenServer Builder (from an ISO)
@ -18,32 +18,6 @@ the OS, then shutting it down. The result of the XenServer builder is a
directory containing all the files necessary to run the virtual machine directory containing all the files necessary to run the virtual machine
portably. portably.
## Basic Example
Here is a basic example. This example is not functional. Even when the
`remote_*` fields have been completed, it will start the OS installer but then
fail because we don't provide the preseed file for Ubuntu to self-install.
Still, the example serves to show the basic configuration:
```javascript
{
"type": "xenserver-iso",
"remote_host": "your-server.example.com",
"remote_username": "root",
"remote_password": "password",
"iso_url": "http://releases.ubuntu.com/12.04/ubuntu-12.04.5-server-amd64.iso",
"iso_checksum": "769474248a3897f4865817446f9a4a53",
"iso_checksum_type": "md5",
"ssh_username": "packer",
"ssh_password": "packer",
"ssh_wait_timeout": "30s",
"shutdown_command": "echo 'packer' | sudo -S shutdown -P now"
}
```
It is important to add a `shutdown_command`. By default Packer forcibly halts the
virtual machine and the file system may not be sync'd. Thus, changes made in a
provisioner might not be saved.
## Configuration Reference ## Configuration Reference
@ -69,7 +43,7 @@ each category, the available options are alphabetized and described.
If this is an HTTP URL, Packer will download it and cache it between If this is an HTTP URL, Packer will download it and cache it between
runs. runs.
* `remote_host` (string) - The host of the remote machine. * `remote_host` (string) - The host of the Xenserver / XCP-ng pool primary. Typically these will be specified through environment variables as seen in the [examples](../../examples/centos8.json).
* `remote_username` (string) - The XenServer username used to access the remote machine. * `remote_username` (string) - The XenServer username used to access the remote machine.
@ -85,7 +59,7 @@ each category, the available options are alphabetized and described.
be to type just enough to initialize the operating system installer. Special be to type just enough to initialize the operating system installer. Special
keys can be typed as well, and are covered in the section below on the boot keys can be typed as well, and are covered in the section below on the boot
command. If this is not specified, it is assumed the installer will start command. If this is not specified, it is assumed the installer will start
itself. itself. See the [Ubuntu](../../examples/ubuntu-2004.json) and [centos](../../examples/centos8.json) examples to see how these are used to launch autoinstall and kickstart respectively.
* `boot_wait` (string) - The time to wait after booting the initial virtual * `boot_wait` (string) - The time to wait after booting the initial virtual
machine before typing the `boot_command`. The value of this should be machine before typing the `boot_command`. The value of this should be
@ -270,7 +244,7 @@ will be replaced by the proper key:
is useful if you have to generally wait for the UI to update before typing more. is useful if you have to generally wait for the UI to update before typing more.
In addition to the special keys, each command to type is treated as a In addition to the special keys, each command to type is treated as a
[configuration template](/docs/templates/configuration-templates.html). configuration template.
The available variables are: The available variables are:
* `HTTPIP` and `HTTPPort` - The IP and port, respectively of an HTTP server * `HTTPIP` and `HTTPPort` - The IP and port, respectively of an HTTP server
@ -278,19 +252,4 @@ The available variables are:
configuration parameter. If `http_directory` isn't specified, these will be configuration parameter. If `http_directory` isn't specified, these will be
blank! blank!
Example boot command. This is actually a working boot command used to start See the [examples](../../examples/) for working boot commands.
an Ubuntu 12.04 installer:
```javascript
[
"<esc><esc><enter><wait>",
"/install/vmlinuz noapic ",
"preseed/url=http://{{ .HTTPIP }}:{{ .HTTPPort }}/preseed.cfg ",
"debian-installer=en_US auto locale=en_US kbd-chooser/method=us ",
"hostname={{ .Name }} ",
"fb=false debconf/frontend=noninteractive ",
"keyboard-configuration/modelcode=SKIP keyboard-configuration/layout=USA ",
"keyboard-configuration/variant=USA console-setup/ask_detect=false ",
"initrd=/install/initrd.gz -- <enter>"
]
```

32
examples/README.md Normal file
View File

@ -0,0 +1,32 @@
## Examples
In order for new users to get up and running with the packer builder, a few examples of building a machine image with popular distros have been created. At the time of this writing there are examples for the latest Ubuntu (20.04) and Centos (8.3) releases. Please open an issue if you'd like to see an example for another distro.
In order to see an exhaustive list of configuration options for the packer builder please see the [following documentation](../docs/builders/xenserver-iso.html.markdown). This doc will focus on the details relevant to the particular distro.
### Running the examples
In order to run this example you will need to perform the following steps:
1. Export the `XAPI_HOST`, `XAPI_USERNAME` and `XAPI_PASSWORD` environment variables to the current shell. Note: The `XAPI_HOST` must be the resource pool primary.
2. Run the `packer build` command specifying the storage repositories to use for the ISO upload and for the VM created during the build.
```
# Replace sr_name and sr_iso_name with your storage repositories names
packer build -debug --var sr_name='Local storage' --var sr_iso_name=LocalISO examples/centos8.json
# Do the same variable replacement for the ubuntu example as well.
packer build -debug --var sr_name='Local storage' --var sr_iso_name=LocalISO examples/ubuntu-2004.json
```
### Ubuntu
The Ubuntu example uses the [autoinstall tool](https://ubuntu.com/server/docs/install/autoinstallhttps://ubuntu.com/server/docs/install/autoinstall) to configure the VM template. Please see the [autoinstall docs](https://ubuntu.com/server/docs/install/autoinstall-reference) for an exhaustive list of what is supported.
Packer will create a http server to serve the files as specified from the `http_directory` specified in the builder configuration. This is where the [user-data](http/ubuntu-2004/user-data) and [meta-data](http/ubuntu-2004/meta-data) for autoinstall must be present.
### Centos
The centos example uses kickstart to configure the VM template. Please see the [kickstart documentation](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/installation_guide/sect-kickstart-syntax) for the options that are supported.
Packer will create a http server to serve the files as specified from the `http_directory` specified in the builder configuration. This is where the [kickstart config](http/centos8/ks-centos8.cfg) file must be present.

42
examples/centos8.json Normal file
View File

@ -0,0 +1,42 @@
{
"variables": {
"sr_name": "",
"sr_iso_name": "",
"remote_host": "{{env `XAPI_HOST`}}",
"remote_username": "{{env `XAPI_USERNAME`}}",
"remote_password": "{{env `XAPI_PASSWORD`}}"
},
"builders": [
{
"type": "xenserver-iso",
"sr_name": "{{user `sr_name`}}",
"sr_iso_name": "{{user `sr_iso_name`}}",
"remote_host": "{{user `remote_host`}}",
"remote_username": "{{user `remote_username`}}",
"remote_password": "{{user `remote_password`}}",
"vm_memory": "4096",
"boot_command": [
"<tab> text ks=http://{{ .HTTPIP }}:{{ .HTTPPort }}/ks-centos8.cfg<enter><wait>"
],
"boot_wait": "10s",
"disk_size": 40960,
"http_directory": "examples/http/centos8",
"iso_checksum": "07a8e59c42cc086ec4c49bdce4fae5a17b077dea",
"iso_checksum_type": "sha1",
"iso_url": "http://mirrors.ocf.berkeley.edu/centos/8.3.2011/isos/x86_64/CentOS-8.3.2011-x86_64-boot.iso",
"iso_name": "CentOS-8.3.2011-x86_64-boot.iso",
"tools_iso_name": "guest-tools.iso",
"vm_other_config": {
"conversionvm":"true"
},
"output_directory": "packer-centos-8.3-x86_64-xenserver",
"shutdown_command": "/sbin/shutdown",
"ssh_username": "vagrant",
"ssh_password": "vagrant",
"ssh_wait_timeout": "10000s",
"vm_name": "packer-centos-8.3-x86_64-{{isotime}}",
"vm_description": "Build time: {{isotime}}",
"keep_vm": "always"
}
]
}

View File

@ -1,48 +0,0 @@
install
cdrom
lang en_US.UTF-8
keyboard us
unsupported_hardware
network --bootproto=dhcp
rootpw --iscrypted $1$DIlig7gp$FuhFdeHj.R1VrEzZsI4uo0
firewall --disabled
authconfig --enableshadow --passalgo=sha512
selinux --permissive
timezone UTC
bootloader --location=mbr
text
skipx
zerombr
clearpart --all --initlabel
autopart
auth --useshadow --enablemd5
firstboot --disabled
reboot
%packages --ignoremissing
@Base
@Core
@Development Tools
openssl-devel
readline-devel
zlib-devel
kernel-devel
vim
wget
%end
%post
yum -y update
# update root certs
wget -O/etc/pki/tls/certs/ca-bundle.crt http://curl.haxx.se/ca/cacert.pem
# vagrant
groupadd vagrant -g 999
useradd vagrant -g vagrant -G wheel -u 900 -s /bin/bash
echo "vagrant" | passwd --stdin vagrant
# sudo
echo "vagrant ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
sed -i "s/^.*requiretty/#Defaults requiretty/" /etc/sudoers
%end

View File

@ -1,5 +1,8 @@
install install
cdrom # TODO: Figure out why cdrom does not work
# cdrom
# TODO: parameterize this from the packer config file
url --url="http://mirror.centos.org/centos/8.3.2011/BaseOS/x86_64/os/"
lang en_US.UTF-8 lang en_US.UTF-8
keyboard us keyboard us
network --bootproto=dhcp network --bootproto=dhcp
@ -21,8 +24,8 @@ user --name=vagrant --plaintext --password=vagrant --groups=wheel
reboot reboot
%packages --ignoremissing --excludedocs %packages --ignoremissing --excludedocs
@Base @base
@Core @core
@Development Tools @Development Tools
openssh-clients openssh-clients
sudo sudo

View File

@ -1,199 +0,0 @@
#
#Kickstart template for Ubuntu
#Platform: x86-64
#
# Customized for Server 18.04 minimal vm install
#
# See README.mkd for usage
# Load the minimal server preseed off cdrom
preseed preseed/file string /cdrom/preseed/ubuntu-server-minimalvm.seed
# OPTIONAL: Change hostname from default 'preseed'
# If your DHCP hands out a hostname that will take precedence over this
# see: https://bugs.launchpad.net/ubuntu/+source/preseed/+bug/1452202
#preseed netcfg/hostname string minimal-vm
# Use local proxy
# Setup a server with apt-cacher-ng and enter that hostname here
#preseed mirror/http/proxy string http://my-local-cache:3142/
#System language
lang en_US
#Language modules to install
langsupport en_US
#System keyboard
keyboard us
#System mouse
mouse
#System timezone
timezone America/New_York
#Root password
rootpw --disabled
#Initial user (user with sudo capabilities)
user ubuntu --fullname "Ubuntu" --password ChangeMe
#Reboot after installation
reboot
#Use text mode install
text
#Install OS instead of upgrade
install
#Installation media
cdrom
#Change console size to 1024x768x24
preseed debian-installer/add-kernel-opts string "vga=792"
#System bootloader configuration
bootloader --location=mbr
#Clear the Master Boot Record
zerombr yes
#Partition clearing information
# `--all` will give message in install log about only clearing first drive but
# this is still needed
clearpart --all --initlabel
#Advanced partition
# The last lv specified will take up the remaining space of the vg. To get
# around that add up all your disk sizes and set this value. It appears to
# factor in the size of non lvm partitions as well
preseed partman-auto-lvm/guided_size string 8192MB
part /boot --fstype=ext4 --size=512 --asprimary
part pv.1 --grow --size=1 --asprimary
volgroup vg0 pv.1
logvol / --fstype=ext4 --name=root --vgname=vg0 --size=1024
logvol /usr --fstype=ext4 --name=usr --vgname=vg0 --size=2048
logvol /var --fstype=ext4 --name=var --vgname=vg0 --size=1536
logvol /var/log --fstype=ext4 --name=var_log --vgname=vg0 --size=512
logvol swap --name=swap --vgname=vg0 --size=2048 --maxsize=2048
logvol /home --fstype=ext4 --name=home --vgname=vg0 --size=512
# Don't install recommended items by default
# This will also be set for built system at
# /etc/apt/apt.conf.d/00InstallRecommends
preseed base-installer/install-recommends boolean false
#System authorization infomation
auth --useshadow
#Network information
# If the system has a single interface the '--device' option isn't needed. If
# you do use it remember that in 18.04 the device names are different. For
# example I was seeing enp0s3 as the interface name. I haven't tested this
# but you should be able to specify 'interface=enp0s3' as a boot paramater and
# it will be passed through to installer. I have tested setting the device to
# 'auto' will have it automatically pick the first active interface
#network --bootproto=dhcp --device=enp0s3
network --bootproto=dhcp --device=auto
#Firewall configuration
# Not supported by ubuntu
#firewall --disabled --trust=eth0 --ssh
# Policy for applying updates. May be "none" (no automatic updates),
# "unattended-upgrades" (install security updates automatically), or
# "landscape" (manage system with Landscape).
preseed pkgsel/update-policy select unattended-upgrades
#Do not configure the X Window System
skipx
# Additional packages to install
# - Most of these would have installed if it wasn't for turning off
# install-recommends
# - software-properties-common provides add-apt-repository which is needed for
# adding additional PPAs. You can remove that if you don't plan on
# installing anything. The %post script needs it for adding git
# - Starting in 16.04 Ubuntu no longer installs python v2.7 by default.
# Instead the default version of python is v3.x. If you still need v2.7
# then add the `python` package to this list
# - Uncomment the open-vm-tools line if this is going to run in vmware and are
# not going to use vmware-tools that's distributed with it. Don't think the
# --no-install-recommends is needed to not install desktop tools but doesn't
# hurt anything
%packages
# -- required for %post --
vim
software-properties-common
# -- pretty much required --
gpg-agent # apt-key needs this when piping certs in through stdin
curl
openssh-server
net-tools # this includes commands like ifconfig and netstat
wget
man
# -- additional packages you'll likely want --
#open-vm-tools --no-install-recommends # only needed on vmware vms
#bash-completion # personally I always install it but not everyone uses bash
#chrony # default time server in 18.04. systemd will manage time if this doesn't
#haveged # helps keep entropy pool full on VMs
%post
# -- begin security hardening --
# Change default umask from 022 to 027 (not world readable)
sed -i -e 's/^\(UMASK\W*\)[0-9]\+$/\1027/' /etc/login.defs
# Add noatime to /
sed -i -e 's/\(errors=remount-ro\)/noatime,\1/' /etc/fstab
# Add noatime and nodev to everything else
sed -i -e 's/\(boot.*defaults\)/\1,noatime,nodev/' /etc/fstab
sed -i -e 's/\(home.*defaults\)/\1,noatime,nodev/' /etc/fstab
sed -i -e 's/\(usr.*defaults\)/\1,noatime,nodev/' /etc/fstab
# Remove nodev from this one if it causes issues for you
sed -i -e 's/\(var .*defaults\)/\1,noatime,nodev/' /etc/fstab
# Add noatime, nodev, and noexec to /var/log
sed -i -e 's/\(var\/log .*defaults\)/\1,noatime,nodev,noexec/' /etc/fstab
# Add line to enable noexec on /dev/shm
echo "none /dev/shm tmpfs defaults,noexec,nosuid,nodev 0 0" >>/etc/fstab
# -- end security hardening --
# Set some defaults for apt to keep things tidy
cat > /etc/apt/apt.conf.d/90local <<"_EOF_"
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "1";
APT::Periodic::MaxSize "200";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
#Acquire::http::Proxy "http://my-local-cache:3142";
_EOF_
# -- begin vim package customizations --
echo "set background=dark" >>/etc/vim/vimrc.local
# -- end vim package customizations --
# -- begin install git from 'Ubuntu Git Maintainers' PPA --
add-apt-repository -y ppa:git-core/ppa
apt-get -qq -y update
apt-get -qq -y install git
# -- end install git from 'Ubuntu Git Maintainers' PPA --
# -- begin set xdg base directories --
cat > /etc/profile.d/xdg_basedir.sh <<"_EOF_"
# Set XDG base directory global variables
# XDG_RUNTIME_HOME is set on user login
export XDG_DATA_HOME="${XDG_DATA_HOME:-"${HOME}/.local/share"}"
export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-"${HOME}/.config"}"
export XDG_CACHE_HOME="${XDG_CACHE_HOME:-"${HOME}/.cache"}"
_EOF_
chmod 0644 /etc/profile.d/xdg_basedir.sh
# -- end set xdg base directories --
# Clean up
apt-get -qq -y autoremove
apt-get clean
rm -f /var/cache/apt/*cache.bin
rm -rf /var/lib/apt/lists/*

View File

View File

@ -0,0 +1,11 @@
#cloud-config
autoinstall:
version: 1
identity:
hostname: ubuntu-server
# This is the crypted pass of 'ubuntu'
password: "$6$exDY1mhS4KUYCE/2$zmn9ToZwTKLhCw.b4/b.ZRTIZM30JZ4QrOQ2aOXJ8yk96xpcCof0kxKwuX1kqLG/ygbJ1f8wxED22bTL4F46P0"
username: testuser
ssh:
install-server: yes
allow-pw: yes

46
examples/ubuntu-2004.json Normal file
View File

@ -0,0 +1,46 @@
{
"variables": {
"sr_name": "",
"sr_iso_name": "",
"remote_host": "{{env `XAPI_HOST`}}",
"remote_username": "{{env `XAPI_USERNAME`}}",
"remote_password": "{{env `XAPI_PASSWORD`}}"
},
"builders": [
{
"type": "xenserver-iso",
"sr_name": "{{user `sr_name`}}",
"sr_iso_name": "{{user `sr_iso_name`}}",
"remote_host": "{{user `remote_host`}}",
"remote_username": "{{user `remote_username`}}",
"remote_password": "{{user `remote_password`}}",
"tools_iso_name": "guest-tools.iso",
"boot_command": [
"<esc><f6> autoinstall ds=nocloud-net;s=http://{{ .HTTPIP }}:{{ .HTTPPort }}/<enter><wait>",
"<f6><wait><esc><wait> autoinstall ds=nocloud-net;s=http://{{ .HTTPIP }}:{{ .HTTPPort }}/<enter><wait>"
],
"boot_wait": "10s",
"disk_size": 10960,
"http_directory": "examples/http/ubuntu-2004",
"iso_checksum": "443511f6bf12402c12503733059269a2e10dec602916c0a75263e5d990f6bb93",
"iso_checksum_type": "sha256",
"iso_url": "http://releases.ubuntu.com/20.04/ubuntu-20.04.1-live-server-amd64.iso",
"iso_name": "ubuntu-20.04.1-live-server-amd64.iso",
"vm_other_config": {
"conversionvm":"true"
},
"output_directory": "packer-ubuntu-2004-x86_64-xenserver",
"shutdown_command": "/sbin/shutdown",
"ssh_username": "testuser",
"ssh_password": "ubuntu",
"ssh_wait_timeout": "60000s",
"ssh_timeout": "60000s",
"vm_name": "packer-ubuntu-2004-x86_64",
"vm_description": "Build time: {{isotime}}",
"disk_size": "20000",
"vm_memory": "4096",
"keep_vm": "always",
"ssh_handshake_attempts": "10000"
}
]
}