@hashicorp
The Hyper-V plugin can be used with HashiCorp Packer to create custom images from Hyper-V.
- Community
Updated 2 years ago
- GitHub(opens in new tab)
Hyper-V VMCX
Type: hyperv-vmcx
Artifact BuilderId: MSOpenTech.hyperv
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.
Basic Examples
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.
Import from folder:
Clone from existing virtual machine:
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.
Configuration Reference
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.
ISO Configuration Reference
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.
In JSON:
In HCL2:
Required:
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:- md5:090992ba9fd140077b0661cb75f7ce13
- 090992ba9fd140077b0661cb75f7ce13
- sha1:ebfb681885ddf1234c18094a45bbeafd91467911
- ebfb681885ddf1234c18094a45bbeafd91467911
- sha256:ed363350696a726b7932db864dda019bd2017365c9e299627830f06954643f93
- ed363350696a726b7932db864dda019bd2017365c9e299627830f06954643f93
- file:http://releases.ubuntu.com/20.04/SHA256SUMS
- file:file://./local/path/file.sum
- file:./local/path/file.sum
- 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.
Optional:
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 andiso_url
is used. Only one ofiso_url
oriso_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 toiso
.
Required for virtual machine import:
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.
Required for virtual machine clone:
clone_from_vm_name
(string) - The name of the VM to clone from. Ideally the machine to clone from should be shutdown.
Optional:
disable_shutdown
(bool) - Packer normally halts the virtual machine after all provisioners have run when noshutdown_command
is defined. If this is set totrue
, 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 theshutdown_timeout
option.disk_size
(*uint) - The size, in megabytes, of the primary hard disk for the VM. By default, this is the same as the cloned VM.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.guest_additions_path
(string) - The path to the ISO image for guest additions.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.enable_tpm
(bool) - If true enable a virtual TPM for the virtual machine. This defaults to false.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 topackerhv1234567
. 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.For Generation 1:
IDE
CD
orDVD
Floppy
NET
For Generation 2:
IDE:x:y
SCSI:x:y
CD
orDVD
NET
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 useSCSI: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.
NB This only works for Generation 2 machines.
Communicator configuration reference
communicator
(string) - Packer currently supports three kinds of communicators:none
- No communicator will be used. If this is set, most provisioners also can't be used.ssh
- An SSH connection will be established to the machine. This is usually the default.winrm
- A WinRM connection will be established.
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
anddocker 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 setpause_before_connecting
to10m
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 fields:
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 to22
.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", ]Valid options for ciphers include: "aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "chacha20-poly1305@openssh.com", "arcfour256", "arcfour128", "arcfour", "aes128-cbc", "3des-cbc",
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 withsed
installed.ssh_key_exchange_algorithms
([]string) - If set, Packer will override the value of key exchange (kex) algorithms 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) - Iftrue
, a PTY will be requested for the SSH connection. This defaults tofalse
.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
. This defaults to5m
, unlessssh_handshake_attempts
is set.ssh_disable_agent_forwarding
(bool) - If true, SSH agent forwarding will be disabled. Defaults tofalse
.ssh_handshake_attempts
(int) - The number of handshakes to attempt with SSH once it can connect. This defaults to10
, unless assh_timeout
is set.ssh_bastion_host
(string) - A bastion host to use for the actual SSH connection.ssh_bastion_port
(int) - The port of the bastion host. Defaults to22
.ssh_bastion_agent_auth
(bool) - Iftrue
, the local SSH agent will be used to authenticate with the bastion host. Defaults tofalse
.ssh_bastion_username
(string) - The username to connect to the bastion host.ssh_bastion_password
(string) - The password to use to authenticate with the bastion host.ssh_bastion_interactive
(bool) - Iftrue
, 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
orsftp
- How to transfer files, Secure copy (default) or SSH File Transfer Protocol.NOTE: Guests using Windows with Win32-OpenSSH v9.1.0.0p1-Beta, scp (the default protocol for copying data) returns a a non-zero error code since the MOTW cannot be set, which cause any file transfer to fail. As a workaround you can override the transfer protocol with SFTP instead
ssh_file_transfer_protocol = "sftp"
.ssh_proxy_host
(string) - A SOCKS proxy host to use for SSH connectionssh_proxy_port
(int) - A port of the SOCKS proxy. Defaults to1080
.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 to5s
.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_remote_tunnels
([]string) -ssh_local_tunnels
([]string) -
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 fields:
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 totrue
adds the remotehost:port
to theNO_PROXY
environment variable. This has the effect of bypassing any configured proxies when connecting to the remote host. Default tofalse
.winrm_port
(int) - The WinRM port to connect to. This defaults to5985
for plain unencrypted connection and5986
for SSL whenwinrm_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 to30m
since setting up a Windows machine generally takes a long time.winrm_use_ssl
(bool) - Iftrue
, use HTTPS for WinRM.winrm_insecure
(bool) - Iftrue
, do not check server certificate chain and host name.winrm_use_ntlm
(bool) - Iftrue
, 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.
CD configuration
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.
Optional:
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.Usage example (JSON):
Usage example (HCL):
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,
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 alongsidecd_files
, which is useful to add large files without loading them into memory. If any paths are specified by both, the contents incd_content
will take precedence.Usage example (HCL):
cd_label
(string) - CD Label
Boot Command
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:
<bs>
- Backspace<del>
- Delete<enter> <return>
- Simulates an actual "enter" or "return" keypress.<esc>
- Simulates pressing the escape key.<tab>
- Simulates pressing the tab key.<f1> - <f12>
- Simulates pressing a function key.<up> <down> <left> <right>
- Simulates pressing an arrow key.<spacebar>
- Simulates pressing the spacebar.<insert>
- Simulates pressing the insert key.<home> <end>
- Simulates pressing the home and end keys.<pageUp> <pageDown>
- Simulates pressing the page up and page down keys.<menu>
- Simulates pressing the Menu key.<leftAlt> <rightAlt>
- Simulates pressing the alt key.<leftCtrl> <rightCtrl>
- Simulates pressing the ctrl key.<leftShift> <rightShift>
- Simulates pressing the shift key.<leftSuper> <rightSuper>
- Simulates pressing the ⌘ or Windows 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 ofXX
is a sequence of positive decimal numbers, each with optional fraction and a unit suffix, such as300ms
,1.5h
or2h45m
. Valid time units arens
,us
(orµs
),ms
,s
,m
,h
. For example<wait10m>
or<wait1m20s>
On/Off variants
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.
Templates inside boot command
In addition to the special keys, each command to type is treated as a template engine. The available variables are:
HTTPIP
andHTTPPort
- The IP and port, respectively of an HTTP server that is started serving the directory specified by thehttp_directory
configuration parameter or the content specified in thehttp_content
map. Ifhttp_directory
orhttp_content
isn't specified, these will be blank!Name
- The name of the VM.
For more examples of various boot commands, see the sample projects from our community templates page. command.mdx'
The example shown below is a working boot command used to start an Ubuntu 12.04 installer:
For more examples of various boot commands, see the sample projects from our community templates page.
HTTP directory configuration
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.
Example usage from a builder:
Optional:
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 inboot_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 withhttp_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 inboot_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 thehttp_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 are8000
and9000
, respectively.http_port_max
(int) - HTTP Port Maxhttp_bind_address
(string) - This is the bind address for the HTTP server. Defaults to 0.0.0.0 so that it will work with any network interface.
Integration Services
Packer will automatically attach the integration services ISO as a DVD drive for the version of Hyper-V that is running.
Generation 1 vs Generation 2
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.
Creating an ISO From a Directory
Programs like mkisofs can be used to create an ISO from a directory. There is a windows version of mkisofs available.
Below is a working PowerShell script that can be used to create a Windows answer ISO:
Example For Windows Server 2012 R2 Generation 2
Packer config:
autounattend.xml:
sysprep-unattend.xml:
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/
Example For Ubuntu Vivid Generation 2
If you are running Windows under virtualization, you may need to create a
virtual switch with an External
connection type.
Packer config:
preseed.cfg: