The Hyper-V Packer builder is able to use exported virtual machines or clone
existing
Hyper-V
virtual machines.
Typically, the builder imports or clones an existing virtual machine,
boots it, provisions software within the OS, and then shuts it down. The
result of the Hyper-V builder is a directory containing all the files
necessary to run the virtual machine portably.
Here are some basic examples. Neither example would really do anything more
than producing a copy of the source virtual machine. However, the examples
could be used as a starting point for more advanced templates.
By default Packer will perform a hard power off of a virtual machine.
However, when a machine is powered off this way, it is possible that
changes made to the VMs file system may not be fully synced, possibly
leading to corruption of files or lost changes. As such, it is important to
add a shutdown_command. This tells Packer how to safely shutdown and
power off the VM.
There are many configuration options available for the Hyper-V builder. They
are organized below into two categories: required and optional. Within each
category, the available options are alphabetized and described.
In addition to the options listed here, a
communicator can be configured for this
builder.
By default, Packer will symlink, download or copy image files to the Packer
cache into a "hash($iso_url+$iso_checksum).$iso_target_extension" file.
Packer uses hashicorp/go-getter in
file mode in order to perform a download.
go-getter supports the following protocols:
Local files
Git
Mercurial
HTTP
Amazon S3
Examples:
go-getter can guess the checksum type based on iso_checksum length, and it is
also possible to specify the checksum type.
iso_checksum (string) - The checksum for the ISO file or virtual hard drive file. The type of
the checksum is specified within the checksum field as a prefix, ex:
"md5:{$checksum}". The type of the checksum can also be omitted and
Packer will try to infer it based on string length. Valid values are
"none", "{$checksum}", "md5:{$checksum}", "sha1:{$checksum}",
"sha256:{$checksum}", "sha512:{$checksum}" or "file:{$path}". Here is a
list of valid checksum values:
none
Although the checksum will not be verified when it is set to "none",
this is not recommended since these files can be very large and
corruption does happen from time to time.
iso_url (string) - A URL to the ISO containing the installation image or virtual hard drive
(VHD or VHDX) file to clone.
iso_urls ([]string) - Multiple URLs for the ISO to download. Packer will try these in order.
If anything goes wrong attempting to download or while downloading a
single URL, it will move on to the next. All URLs must point to the same
file (same checksum). By default this is empty and iso_url is used.
Only one of iso_url or iso_urls can be specified.
iso_target_path (string) - The path where the iso should be saved after download. By default will
go in the packer cache, with a hash of the original filename and
checksum as its name.
iso_target_extension (string) - The extension of the iso file after download. This defaults to iso.
clone_from_vmcx_path (string) - The path to a directory containing a
previously exported virtual machine. The exported machine will be used
as the source for new VM.
note: You should provide the named directory that contains the
"Virtual Machines", "Snapshots", and/or "Virtual Hard Disks" subdirectories,
not the .vmcx file itself.
disable_shutdown (bool) - Packer normally halts the virtual machine after all provisioners have
run when no shutdown_command is defined. If this is set to true, Packer
will not halt the virtual machine but will assume that the VM will shut itself down
when it's done, via the preseed.cfg or your final provisioner.
Packer will wait for a default of 5 minutes until the virtual machine is shutdown.
The timeout can be changed using the shutdown_timeout option.
clone_from_vmcx_path (string) - This is the path to a directory containing an exported virtual machine.
clone_from_vm_name (string) - This is the name of the virtual machine to clone from.
clone_from_snapshot_name (string) - The name of a snapshot in the
source machine to use as a starting point for the clone. If the value
given is an empty string, the last snapshot present in the source will
be chosen as the starting point for the new VM.
clone_all_snapshots (bool) - If set to true all snapshots
present in the source machine will be copied when the machine is
cloned. The final result of the build will be an exported virtual
machine that contains all the snapshots of the parent.
differencing_disk (bool) - If true enables differencing disks. Only
the changes will be written to the new disk. This is especially useful if
your source is a VHD/VHDX. This defaults to false.
copy_in_compare (bool) - When cloning a vm to build from, we run a powershell
Compare-VM command, which, depending on your version of Windows, may need
the "Copy" flag to be set to true or false. Defaults to "false". Command:
disk_block_size (uint) - The block size of the VHD to be created.
Recommended disk block size for Linux hyper-v guests is 1 MiB. This
defaults to "32" MiB.
memory (uint) - The amount, in megabytes, of RAM to assign to the
VM. By default, this is 1 GB.
secondary_iso_images ([]string) - A list of ISO paths to
attach to a VM when it is booted. This is most useful for unattended
Windows installs, which look for an Autounattend.xml file on removable
media. By default, no secondary ISO will be attached.
disk_additional_size ([]uint) - The size or sizes of any
additional hard disks for the VM in megabytes. If this is not specified
then the VM will only contain a primary hard disk. Additional drives
will be attached to the SCSI interface only. The builder uses
expandable rather than fixed-size virtual hard disks, so the actual
file representing the disk will not use the full size unless it is
full.
guest_additions_mode (string) - If set to attach then attach and
mount the ISO image specified in guest_additions_path. If set to
none then guest additions are not attached and mounted; This is the
default.
vm_name (string) - This is the name of the new virtual machine,
without the file extension. By default this is "packer-BUILDNAME",
where "BUILDNAME" is the name of the build.
switch_name (string) - The name of the switch to connect the virtual
machine to. By default, leaving this value unset will cause Packer to
try and determine the switch to use by looking for an external switch
that is up and running.
switch_vlan_id (string) - This is the VLAN of the virtual switch's
network card. By default none is set. If none is set then a VLAN is not
set on the switch's network card. If this value is set it should match
the VLAN specified in by vlan_id.
mac_address (string) - This allows a specific MAC address to be used on
the default virtual network card. The MAC address must be a string with
no delimiters, for example "0000deadbeef".
vlan_id (string) - This is the VLAN of the virtual machine's network
card for the new virtual machine. By default none is set. If none is set
then VLANs are not set on the virtual machine's network card.
cpus (uint) - The number of CPUs the virtual machine should use. If
this isn't specified, the default is 1 CPU.
generation (uint) - The Hyper-V generation for the virtual machine. By
default, this is 1. Generation 2 Hyper-V virtual machines do not support
floppy drives. In this scenario use secondary_iso_images instead. Hard
drives and DVD drives will also be SCSI and not IDE.
enable_mac_spoofing (bool) - If true enable MAC address spoofing
for the virtual machine. This defaults to false.
enable_dynamic_memory (bool) - If true enable dynamic memory for
the virtual machine. This defaults to false.
enable_secure_boot (bool) - If true enable secure boot for the
virtual machine. This defaults to false. See secure_boot_template
below for additional settings.
secure_boot_template (string) - The secure boot template to be
configured. Valid values are "MicrosoftWindows" (Windows) or
"MicrosoftUEFICertificateAuthority" (Linux). This only takes effect if
enable_secure_boot is set to "true". This defaults to "MicrosoftWindows".
enable_virtualization_extensions (bool) - If true enable
virtualization extensions for the virtual machine. This defaults to
false. For nested virtualization you need to enable MAC spoofing,
disable dynamic memory and have at least 4GB of RAM assigned to the
virtual machine.
temp_path (string) - The location under which Packer will create a directory to house all the
VM files and folders during the build. By default %TEMP% is used
which, for most systems, will evaluate to
%USERPROFILE%/AppData/Local/Temp.
The build directory housed under temp_path will have a name similar to
packerhv1234567. The seven digit number at the end of the name is
automatically generated by Packer to ensure the directory name is
unique.
configuration_version (string) - This allows you to set the vm version when calling New-VM to generate
the vm.
keep_registered (bool) - If "true", Packer will not delete the VM from
The Hyper-V manager.
skip_compaction (bool) - If true skip compacting the hard disk for
the virtual machine when exporting. This defaults to false.
skip_export (bool) - If true Packer will skip the export of the VM.
If you are interested only in the VHD/VHDX files, you can enable this
option. The resulting VHD/VHDX file will be output to
<output_directory>/Virtual Hard Disks. By default this option is false
and Packer will export the VM to output_directory.
headless (bool) - Packer defaults to building Hyper-V virtual
machines by launching a GUI that shows the console of the machine being
built. When this value is set to true, the machine will start without a
console.
first_boot_device (string) - When configured, determines the device or device type that is given preferential
treatment when choosing a boot device.
boot_order ([]string) - When configured, the boot order determines the order of the devices
from which to boot.
The device name must be in the form of SCSI:x:y, for example,
to boot from the first scsi device use SCSI:0:0.
NB You should also set first_boot_device (e.g. DVD).
NB Although the VM will have this initial boot order, the OS can
change it, for example, Ubuntu 18.04 will modify the boot order to
include itself as the first boot option.
In addition to the above, some builders have custom communicators they
can use. For example, the Docker builder has a "docker" communicator
that uses docker exec and docker cp to execute scripts and copy
files.
pause_before_connecting (duration string | ex: "1h5m2s") - We recommend that you enable SSH or WinRM as the very last step in your
guest's bootstrap script, but sometimes you may have a race condition
where you need Packer to wait before attempting to connect to your
guest.
If you end up in this situation, you can use the template option
pause_before_connecting. By default, there is no pause. For example if
you set pause_before_connecting to 10m Packer will check whether it
can connect, as normal. But once a connection attempt is successful, it
will disconnect and then wait 10 minutes before connecting to the guest
and beginning provisioning.
ssh_host (string) - The address to SSH to. This usually is automatically configured by the
builder.
ssh_port (int) - The port to connect to SSH. This defaults to 22.
ssh_username (string) - The username to connect to SSH with. Required if using SSH.
ssh_password (string) - A plaintext password to use to authenticate with SSH.
ssh_ciphers ([]string) - This overrides the value of ciphers supported by default by golang.
The default value is [
"aes128-gcm@openssh.com",
"chacha20-poly1305@openssh.com",
"aes128-ctr", "aes192-ctr", "aes256-ctr",
]
ssh_clear_authorized_keys (bool) - If true, Packer will attempt to remove its temporary key from
~/.ssh/authorized_keys and /root/.ssh/authorized_keys. This is a
mostly cosmetic option, since Packer will delete the temporary private
key from the host system regardless of whether this is set to true
(unless the user has set the -debug flag). Defaults to "false";
currently only works on guests with sed installed.
ssh_key_exchange_algorithms ([]string) - If set, Packer will override the value of key exchange (kex) altorighms
supported by default by golang. Acceptable values include:
"curve25519-sha256@libssh.org", "ecdh-sha2-nistp256",
"ecdh-sha2-nistp384", "ecdh-sha2-nistp521",
"diffie-hellman-group14-sha1", and "diffie-hellman-group1-sha1".
ssh_certificate_file (string) - Path to user certificate used to authenticate with SSH.
The ~ can be used in path and will be expanded to the
home directory of current user.
ssh_pty (bool) - If true, a PTY will be requested for the SSH connection. This defaults
to false.
ssh_timeout (duration string | ex: "1h5m2s") - The time to wait for SSH to become available. Packer uses this to
determine when the machine has booted so this is usually quite long.
Example value: 10m.
ssh_bastion_password (string) - The password to use to authenticate with the bastion host.
ssh_bastion_interactive (bool) - If true, the keyboard-interactive used to authenticate with bastion host.
ssh_bastion_private_key_file (string) - Path to a PEM encoded private key file to use to authenticate with the
bastion host. The ~ can be used in path and will be expanded to the
home directory of current user.
ssh_bastion_certificate_file (string) - Path to user certificate used to authenticate with bastion host.
The ~ can be used in path and will be expanded to the
home directory of current user.
ssh_file_transfer_method (string) - scp or sftp - How to transfer files, Secure copy (default) or SSH
File Transfer Protocol.
ssh_proxy_host (string) - A SOCKS proxy host to use for SSH connection
ssh_proxy_port (int) - A port of the SOCKS proxy. Defaults to 1080.
ssh_proxy_username (string) - The optional username to authenticate with the proxy server.
ssh_proxy_password (string) - The optional password to use to authenticate with the proxy server.
ssh_keep_alive_interval (duration string | ex: "1h5m2s") - How often to send "keep alive" messages to the server. Set to a negative
value (-1s) to disable. Example value: 10s. Defaults to 5s.
ssh_read_write_timeout (duration string | ex: "1h5m2s") - The amount of time to wait for a remote command to end. This might be
useful if, for example, packer hangs on a connection after a reboot.
Example: 5m. Disabled by default.
ssh_private_key_file (string) - Path to a PEM encoded private key file to use to authenticate with SSH.
The ~ can be used in path and will be expanded to the home directory
of current user.
winrm_username (string) - The username to use to connect to WinRM.
winrm_password (string) - The password to use to connect to WinRM.
winrm_host (string) - The address for WinRM to connect to.
NOTE: If using an Amazon EBS builder, you can specify the interface
WinRM connects to via
ssh_interface
winrm_no_proxy (bool) - Setting this to true adds the remote
host:port to the NO_PROXY environment variable. This has the effect of
bypassing any configured proxies when connecting to the remote host.
Default to false.
winrm_port (int) - The WinRM port to connect to. This defaults to 5985 for plain
unencrypted connection and 5986 for SSL when winrm_use_ssl is set to
true.
winrm_timeout (duration string | ex: "1h5m2s") - The amount of time to wait for WinRM to become available. This defaults
to 30m since setting up a Windows machine generally takes a long time.
winrm_use_ssl (bool) - If true, use HTTPS for WinRM.
winrm_insecure (bool) - If true, do not check server certificate chain and host name.
winrm_use_ntlm (bool) - If true, NTLMv2 authentication (with session security) will be used
for WinRM, rather than default (basic authentication), removing the
requirement for basic authentication to be enabled within the target
guest. Further reading for remote connection authentication can be found
here.
An iso (CD) containing custom files can be made available for your build.
By default, no extra CD will be attached. All files listed in this setting
get placed into the root directory of the CD and the CD is attached as the
second CD device.
This config exists to work around modern operating systems that have no
way to mount floppy disks, which was our previous go-to for adding files at
boot time.
cd_files ([]string) - A list of files to place onto a CD that is attached when the VM is
booted. This can include either files or directories; any directories
will be copied onto the CD recursively, preserving directory structure
hierarchy. Symlinks will have the link's target copied into the directory
tree on the CD where the symlink was. File globbing is allowed.
The above will create a CD with two files, user-data and meta-data in the
CD root. This specific example is how you would create a CD that can be
used for an Ubuntu 20.04 autoinstall.
Since globbing is also supported,
cd_files=["./somedirectory/*"]cd_label="cidata"
cd_files=["./somedirectory/*"]cd_label="cidata"
Would also be an acceptable way to define the above cd. The difference
between providing the directory with or without the glob is whether the
directory itself or its contents will be at the CD root.
Use of this option assumes that you have a command line tool installed
that can handle the iso creation. Packer will use one of the following
tools:
xorriso
mkisofs
hdiutil (normally found in macOS)
oscdimg (normally found in Windows as part of the Windows ADK)
cd_content (map[string]string) - Key/Values to add to the CD. The keys represent the paths, and the values
contents. It can be used alongside cd_files, which is useful to add large
files without loading them into memory. If any paths are specified by both,
the contents in cd_content will take precedence.
The boot_command configuration is very important: it specifies the keys to
type when the virtual machine is first booted in order to start the OS
installer. This command is typed after boot_wait, which gives the virtual
machine some time to actually load the ISO.
As documented above, the boot_command is an array of strings. The strings
are all typed in sequence. It is an array only to improve readability within
the template.
The boot command is "typed" character for character over the virtual keyboard
to the machine, simulating a human actually typing the keyboard.
There are a set of special keys available. If these are in your boot
command, they will be replaced by the proper key:
<wait> <wait5> <wait10> - Adds a 1, 5 or 10 second pause before
sending any additional keys. This is useful if you have to generally wait
for the UI to update before typing more.
<waitXX> - Add an arbitrary pause before sending any additional keys. The
format of XX is a sequence of positive decimal numbers, each with
optional fraction and a unit suffix, such as 300ms, 1.5h or 2h45m.
Valid time units are ns, us (or µs), ms, s, m, h. For example
<wait10m> or <wait1m20s>
Any printable keyboard character, and of these "special" expressions, with the
exception of the <wait> types, can also be toggled on or off. For example, to
simulate ctrl+c, use <leftCtrlOn>c<leftCtrlOff>. Be sure to release them,
otherwise they will be held down until the machine reboots.
To hold the c key down, you would use <cOn>. Likewise, <cOff> to release.
In addition to the special keys, each command to type is treated as a
template engine. The
available variables are:
HTTPIP and HTTPPort - The IP and port, respectively of an HTTP server
that is started serving the directory specified by the http_directory
configuration parameter or the content specified in the http_content map. If
http_directory or http_content isn't specified, these will be blank!
Packer will create an http server serving http_directory when it is set, a
random free port will be selected and the architecture of the directory
referenced will be available in your builder.
http_directory (string) - Path to a directory to serve using an HTTP server. The files in this
directory will be available over HTTP that will be requestable from the
virtual machine. This is useful for hosting kickstart files and so on.
By default this is an empty string, which means no HTTP server will be
started. The address and port of the HTTP server will be available as
variables in boot_command. This is covered in more detail below.
http_content (map[string]string) - Key/Values to serve using an HTTP server. http_content works like and
conflicts with http_directory. The keys represent the paths and the
values contents, the keys must start with a slash, ex: /path/to/file.
http_content is useful for hosting kickstart files and so on. By
default this is empty, which means no HTTP server will be started. The
address and port of the HTTP server will be available as variables in
boot_command. This is covered in more detail below.
Example:
http_port_min (int) - These are the minimum and maximum port to use for the HTTP server
started to serve the http_directory. Because Packer often runs in
parallel, Packer will choose a randomly available port in this range to
run the HTTP server. If you want to force the HTTP server to be on one
port, make this minimum and maximum port the same. By default the values
are 8000 and 9000, respectively.
Floppy drives are no longer supported by generation 2 machines. This requires
you to take another approach when dealing with preseed or answer files. Two
possible options are using the cd_files option or using Packer's built in web
server.
When dealing with Windows you need to enable UEFI drives for generation 2
virtual machines.
Warning: Please note that if you're setting up WinRM for provisioning, you'll probably want to turn it off or restrict its permissions as part of a shutdown script at the end of Packer's provisioning process. For more details on the why/how, check out this useful blog post and the associated code:
https://cloudywindows.io/post/winrm-for-provisioning-close-the-door-on-the-way-out-eh/