### Ubuntu 12.04 Installer Boot Command (JSON) Source: https://developer.hashicorp.com/packer/integrations/hashicorp/qemu/latest/components/builder/qemu Example boot command for starting an Ubuntu 12.04 installer using JSON configuration. This command includes sequences for escaping, waiting, and specifying installation parameters via HTTP. ```json "boot_command": [ "", "/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 -- " ] ``` -------------------------------- ### Example Boot Command for Debian Installer Source: https://developer.hashicorp.com/packer/plugins/builders/hyperv/iso This is an example of a boot command used to automate the Debian installer. It includes parameters for preseed URL, locale, keyboard layout, and hostname. ```shell /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 -- " ] ``` -------------------------------- ### Example: Install Happy Cloud Plugin Locally Source: https://developer.hashicorp.com/packer/docs/plugins/creation An example demonstrating the installation of the 'happycloud' plugin from a local binary named 'packer-plugin-happycloud'. ```bash $ packer plugins install --path packer-plugin-happycloud github.com/hashicorp/happycloud ``` ```bash $ packer plugins install --path packer-plugin-happycloud github.com/hashicorp/happycloud ``` -------------------------------- ### Install Local Plugin Binary Example Source: https://developer.hashicorp.com/packer/docs/plugins/install-plugins This example demonstrates installing the `happycloud` plugin from a locally-sourced binary. It involves unzipping the plugin, listing its contents, and then using the `packer plugins install` command. ```bash $ unzip packer-plugin-happycloud.zip $ ls -l -rwxr-xr-x [...] happycloud $ packer plugins install --path happycloud github.com/hashicorp/happycloud ``` -------------------------------- ### Example Boot Command for Debian Installer Source: https://developer.hashicorp.com/packer/integrations/hashicorp/hyperv/latest/components/builder/iso This snippet shows a typical boot command sequence for automating the Debian installer. It includes parameters for the kernel, preseed URL, locale, hostname, and keyboard configuration. ```shell /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 -- " ``` -------------------------------- ### Ubuntu 12.04 Installer Boot Command (HCL2) Source: https://developer.hashicorp.com/packer/integrations/hashicorp/qemu/latest/components/builder/qemu Example boot command for starting an Ubuntu 12.04 installer using HCL2 configuration. This command includes sequences for escaping, waiting, and specifying installation parameters via HTTP. ```hcl boot_command = [ "", "/install/vmlinuz noapic ", "preseed/url=http://{{ .HTTPIP }}:{{ .HTTPPort }}/preseed.cfg ", ``` -------------------------------- ### Debian Preseed Boot Configuration Example Source: https://developer.hashicorp.com/packer/integrations/hashicorp/virtualbox/latest/components/builder/vm Example boot command arguments for automated Debian installation using a preseed file hosted via HTTP. ```shell "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 -- " ``` -------------------------------- ### CentOS 6.4 Installer Boot Command (JSON) Source: https://developer.hashicorp.com/packer/integrations/hashicorp/qemu/latest/components/builder/qemu Example boot command for starting a CentOS 6.4 installer using JSON configuration. It utilizes special keys and HTTP variables for unattended installation. ```json "boot_command": [ "", " ks=http://{{ .HTTPIP }}:{{ .HTTPPort }}/centos6-ks.cfg" ] ``` -------------------------------- ### Clone Multicloud Example Repository Source: https://developer.hashicorp.com/packer/tutorials/cloud-production/multicloud Clone the example repository to your local machine to follow along with the tutorial. This command downloads the necessary files for the multicloud Packer setup. ```bash $ git clone https://github.com/hashicorp-education/learn-packer-multicloud ``` ```bash $ git clone https://github.com/hashicorp-education/learn-packer-multicloud ``` -------------------------------- ### JSON Example for boot_steps Source: https://developer.hashicorp.com/packer/integrations/hashicorp/qemu/latest/components/builder/qemu Use 'boot_steps' in JSON to define a sequence of commands and descriptions for interactive installer automation. Packer pauses after each command in debug mode. ```json { "boot_steps": [ ["1", "Install NetBSD"], ["a", "Installation messages in English"], ["a", "Keyboard type: unchanged"], ["a", "Install NetBSD to hard disk"], ["b", "Yes"] ] } ``` -------------------------------- ### QEMU Boot Command Example Source: https://developer.hashicorp.com/packer/integrations/hashicorp/qemu/latest/components/builder/qemu This snippet shows a typical boot command array used for automated Debian installations with Packer's QEMU builder. It includes parameters for locale, hostname, and preseed configuration. ```HCL boot_command = [ "", "/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 -- " ] ``` -------------------------------- ### VirtualBox ISO Builder Boot Commands Source: https://developer.hashicorp.com/packer/integrations/hashicorp/virtualbox/latest/components/builder/iso Example boot commands for unattended installations, including preseed URL, locale, hostname, and keyboard configuration. ```shell preseed/url=http://{{ .HTTPIP }}:{{ .HTTPPort }}/preseed.cfg ``` ```shell debian-installer=en_US auto locale=en_US kbd-chooser/method=us ``` ```shell hostname={{ .Name}} ``` ```shell fb=false debconf/frontend=noninteractive ``` ```shell keyboard-configuration/modelcode=SKIP keyboard-configuration/layout=USA ``` ```shell keyboard-configuration/variant=USA console-setup/ask_detect=false ``` ```shell initrd=/install/initrd.gz -- ``` -------------------------------- ### Basic Hyper-V ISO Builder Configuration Source: https://developer.hashicorp.com/packer/integrations/hashicorp/hyperv/latest/components/builder/iso This is a basic configuration example for the Hyper-V ISO builder. It demonstrates essential parameters like ISO URL, checksum, SSH credentials, and the shutdown command. Note that this example is not fully functional as it lacks a preseed file for automated OS installation. ```json { "type": "hyperv-iso", "iso_url": "http://releases.ubuntu.com/12.04/ubuntu-12.04.5-server-amd64.iso", "iso_checksum": "md5:769474248a3897f4865817446f9a4a53", "ssh_username": "packer", "ssh_password": "packer", "shutdown_command": "echo 'packer' | sudo -S shutdown -P now" } ``` -------------------------------- ### HCL Example for boot_steps Source: https://developer.hashicorp.com/packer/integrations/hashicorp/qemu/latest/components/builder/qemu Use 'boot_steps' in HCL to define a sequence of commands and descriptions for interactive installer automation. Packer pauses after each command in debug mode. ```hcl boot_steps = [ ["1", "Install NetBSD"], ["a", "Installation messages in English"], ["a", "Keyboard type: unchanged"], ["a", "Install NetBSD to hard disk"], ["b", "Yes"] ] ``` -------------------------------- ### Example HTTP Directory Usage in Builder Source: https://developer.hashicorp.com/packer/integrations/hashicorp/hyperv/latest/components/builder/vmcx Use these variables in your builder's boot command to fetch files from the HTTP server started by Packer. ```shell wget http://{{ .HTTPIP }}:{{ .HTTPPort }}/foo/bar/preseed.cfg ``` ```shell wget http://{{ .HTTPIP }}:{{ .HTTPPort }}/foo/bar/preseed.cfg ``` -------------------------------- ### CentOS 6.4 Installer Boot Command (HCL2) Source: https://developer.hashicorp.com/packer/integrations/hashicorp/qemu/latest/components/builder/qemu Example boot command for starting a CentOS 6.4 installer using HCL2 configuration. It utilizes special keys and HTTP variables for unattended installation. ```hcl boot_command = [ "", " ks=http://{{ .HTTPIP }}:{{ .HTTPPort }}/centos6-ks.cfg" ] ``` -------------------------------- ### QEMU Builder qemuargs Example (HCL2) Source: https://developer.hashicorp.com/packer/integrations/hashicorp/qemu/latest/components/builder/qemu This example demonstrates how to configure the `qemuargs` parameter in HCL2 format to provide custom command-line arguments to QEMU. It shows how to set memory, disable ACPI, configure user-mode networking with host forwarding, and specify a network device. ```hcl qemuargs = [ [ "-m", "1024M" ], [ "--no-acpi", "" ], [ "-netdev", "user,id=mynet0,", "hostfwd=hostip:hostport-guestip:guestport", "" ], [ "-device", "virtio-net,netdev=mynet0" ] ] ``` -------------------------------- ### Navigate to Repository Directory Source: https://developer.hashicorp.com/packer/tutorials/hcp/revoke-image Change into the cloned repository directory to access the tutorial files. ```bash cd learn-hcp-packer-revocation ``` -------------------------------- ### Breakpoint Provisioner Example Source: https://developer.hashicorp.com/packer/docs/provisioners/breakpoint This example shows the UI output when the breakpoint provisioner is triggered. It pauses the build and prompts the user to press Enter to continue. ```shell ==> docker: Pausing at breakpoint provisioner with note "foo bar baz". ==> docker: Press enter to continue. ``` -------------------------------- ### Install AWS CLI Source: https://developer.hashicorp.com/packer/guides/packer-on-cicd/upload-images-to-artifact Install the AWS Command Line Interface on the agent machine. This is a one-time setup step. ```bash $ pip install awscli ``` -------------------------------- ### VirtualBox ISO Builder Boot Configuration Example Source: https://developer.hashicorp.com/packer/plugins/builders/virtualbox/iso Example boot parameters for a Debian-based distribution using an HTTP preseed URL. Ensure the HTTP server is accessible from the VM. ```shell 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 -- ``` -------------------------------- ### Ubuntu 12.04 Installer Boot Command Source: https://developer.hashicorp.com/packer/integrations/hashicorp/hyperv/latest/components/builder/vmcx This is a working boot command used to start an Ubuntu 12.04 installer. It utilizes special keys and template variables for preconfiguration. ```json [ "", "/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 -- " ] ``` -------------------------------- ### Complete Example with Manual SBOM Generation (HCL) Source: https://developer.hashicorp.com/packer/docs/provisioners/hcp-sbom This example demonstrates a full Packer build configuration using the shell provisioner to generate an SBOM and then the hcp-sbom provisioner to upload it. ```HCL packer { required_plugins { docker = { version = ">= 1.0.0" source = "github.com/hashicorp/docker" } } } source "docker" "ubuntu" { image = "ubuntu:20.04" commit = true } build { sources = ["source.docker.ubuntu"] hcp_packer_registry { bucket_name = "test-bucket" } provisioner "shell" { inline = [ "apt-get update -y", "apt-get install -y curl gpg", "bash -c \"$(curl -sSL https://install.mondoo.com/sh)\"", "cnquery sbom --output cyclonedx-json --output-target /tmp/sbom_cyclonedx.json", ] } provisioner "hcp-sbom" { source = "/tmp/sbom_cyclonedx.json" destination = "./sbom" sbom_name = "sbom-cyclonedx" } } ``` -------------------------------- ### Basic Shell Provisioner Example Source: https://developer.hashicorp.com/packer/docs/provisioners/shell This is a basic example of the shell provisioner using inline commands to echo 'foo'. ```hcl provisioner "shell" { inline = ["echo foo"] } ``` -------------------------------- ### Basic Docker Image Export Example (HCL2) Source: https://developer.hashicorp.com/packer/integrations/hashicorp/docker/latest/components/builder/docker This example demonstrates how to configure the Docker builder to export a container as a tar archive. Ensure Docker Engine is installed on the machine running Packer. ```hcl source "docker" "example" { image = "ubuntu" export_path = "image.tar" } build { sources = ["source.docker.example"] } ``` -------------------------------- ### Import VM from Folder Source: https://developer.hashicorp.com/packer/integrations/hashicorp/hyperv/latest/components/builder/vmcx This example demonstrates how to import a virtual machine from a specified folder path. It includes necessary details for SSH communication and a shutdown command for safe power-off. ```json { "type": "hyperv-vmcx", "clone_from_vmcx_path": "c:/path/to/ubuntu-12.04.5-server-amd64", "ssh_username": "packer", "ssh_password": "packer", "shutdown_command": "echo 'packer' | sudo -S shutdown -P now" } ``` -------------------------------- ### Ubuntu Preseed Configuration for Automated Installation Source: https://developer.hashicorp.com/packer/integrations/hashicorp/hyperv/latest/components/builder/vmcx This preseed configuration automates the installation of Ubuntu, setting locale, keyboard layout, hostname, partitioning scheme (LVM), and user credentials. It is designed for non-interactive setup. ```cfg ## Options to set on the command line d-i debian-installer/locale string en_US.utf8 d-i console-setup/ask_detect boolean false d-i console-setup/layout string us d-i netcfg/get_hostname string nl-ams-basebox3 d-i netcfg/get_domain string unassigned-domain d-i time/zone string UTC d-i clock-setup/utc-auto boolean true d-i clock-setup/utc boolean true d-i kbd-chooser/method select American English d-i netcfg/wireless_wep string d-i base-installer/kernel/override-image string linux-server d-i debconf debconf/frontend select Noninteractive d-i pkgsel/install-language-support boolean false tasksel tasksel/first multiselect standard, ubuntu-server ## Partitioning d-i partman-auto/method string lvm d-i partman-lvm/confirm boolean true d-i partman-lvm/device_remove_lvm boolean true d-i partman-lvm/confirm boolean true d-i partman-auto-lvm/guided_size string max d-i partman-auto/choose_recipe select atomic d-i partman/confirm_write_new_label boolean true d-i partman/choose_partition select finish d-i partman/confirm boolean true d-i partman/confirm_nooverwrite boolean true # Write the changes to disks and configure LVM? d-i partman-lvm/confirm boolean true d-i partman-lvm/confirm_nooverwrite boolean true d-i partman-partitioning/no_bootable_gpt_biosgrub boolean false d-i partman-partitioning/no_bootable_gpt_efi boolean false d-i partman-efi/non_efi_system boolean true # Default user d-i passwd/user-fullname string packer d-i passwd/username string packer d-i passwd/user-password password packer d-i passwd/user-password-again password packer d-i user-setup/encrypt-home boolean false d-i user-setup/allow-password-weak boolean true ``` -------------------------------- ### Basic Windows-Shell Provisioner Example Source: https://developer.hashicorp.com/packer/docs/provisioners/windows-shell This example shows a basic configuration for the windows-shell provisioner, executing a single inline command. ```hcl provisioner "windows-shell" { inline = ["dir c:\\"] } ``` ```json { "type": "windows-shell", "inline": ["dir c:\\"] } ``` -------------------------------- ### setproduct Example: Basic Usage Source: https://developer.hashicorp.com/packer/docs/templates/hcl_templates/functions/collection/setproduct Demonstrates finding all combinations of environments and applications using setproduct. ```hcl > setproduct(["development", "staging", "production"], ["app1", "app2"]) [ [ "development", "app1", ], [ "development", "app2", ], [ "staging", "app1", ], [ "staging", "app2", ], [ "production", "app1", ], [ "production", "app2", ], ] ``` -------------------------------- ### Packer Shell Provisioner for Setup Source: https://developer.hashicorp.com/packer/tutorials/cloud-production/golden-image-with-hcp-packer This Packer shell provisioner executes a setup script to configure the instance, install dependencies, and set up the SSH key and Loki. It ensures the script runs after cloud-init completes to avoid race conditions. ```hcl build { ## ... # Execute setup script provisioner "shell" { script = "loki-setup.sh" # Run script after cloud-init finishes, otherwise you run into race conditions execute_command = "/usr/bin/cloud-init status --wait && sudo -E -S sh '{{ .Path }}'" } # Move temp files to actual destination # Must use this method because their destinations are protected provisioner "shell" { inline = [ "sudo cp /tmp/start-loki-grafana.sh /var/lib/cloud/scripts/per-boot/start-loki-grafana.sh", "rm /tmp/start-loki-grafana.sh", ] } # … } ``` -------------------------------- ### Extract Substring Example Source: https://developer.hashicorp.com/packer/docs/templates/hcl_templates/functions/string/substr Demonstrates extracting a substring starting from the second character (index 1) with a length of 4 characters. ```bash > substr("hello world", 1, 4) ello ``` -------------------------------- ### Disable WinRM Autostart Source: https://developer.hashicorp.com/packer/integrations/hashicorp/hyperv/latest/components/builder/iso Configures the WinRM service to not start automatically. This is often done after initial setup or for security hardening. ```xml cmd.exe /c sc config winrm start= disabled Win RM Autostart 15 true ``` -------------------------------- ### Shell Provisioner Example (JSON) Source: https://developer.hashicorp.com/packer/docs/templates/legacy_json_templates/provisioners Example of configuring the 'shell' provisioner to run a local script within the machines being created. The `script` key specifies the path to the shell script. ```json { "type": "shell", "script": "script.sh" } ``` -------------------------------- ### Basic Packer Template Example (JSON) Source: https://developer.hashicorp.com/packer/integrations/hashicorp/ansible/latest/components/provisioner/ansible This JSON configuration shows a basic setup for the Ansible provisioner within a Packer template. ```json { "builders": [ { "type": "digitalocean", "api_token": "6a561151587389c7cf8faa2d83e94150a4202da0e2bad34dd2bf236018ffaeeb", "image": "ubuntu-20-04-x64", "region": "sfo1" } ], "provisioners": [ { "type": "ansible", "playbook_file": "./playbook.yml" } ] } ``` -------------------------------- ### Basic Shell Provisioner Example Source: https://developer.hashicorp.com/packer/docs/templates/hcl_templates/blocks/build/provisioner A basic example of a shell provisioner that executes echo commands. It demonstrates how to use inline scripts and reference variables. ```hcl build { # ... provisioner "shell" { inline = [ "echo provisioning all the things", "echo the value of 'foo' is '${var.foo}'", ] } } ``` -------------------------------- ### Example Ansible Playbook Source: https://developer.hashicorp.com/packer/integrations/hashicorp/ansible/latest/components/provisioner/ansible A simple Ansible playbook that installs the Apache web server. This playbook is intended to be executed by the Packer Ansible provisioner. ```yaml --- # playbook.yml - name: 'Provision Image' hosts: default become: true tasks: - name: install Apache package: name: 'httpd' state: present ``` -------------------------------- ### Initialize Plugins from a Directory Path Source: https://developer.hashicorp.com/packer/docs/commands/init Installs plugins for templates found within the `builds/foo/` directory. The '.' indicates the directory itself. ```bash $ packer init builds/foo/. ``` -------------------------------- ### Packer HCL Source Block Example Source: https://developer.hashicorp.com/packer/docs/templates/hcl_templates Defines a source for an Amazon EBS AMI. This is a common starting point for creating AMIs in AWS. ```hcl source "amazon-ebs" "main" { ami_name = "main-ami" } ``` -------------------------------- ### QEMU Builder qemuargs Example (JSON) Source: https://developer.hashicorp.com/packer/plugins/builders/qemu This JSON snippet illustrates the equivalent configuration of advanced QEMU arguments using the `qemuargs` parameter as the HCL2 example. It is useful for environments where JSON is preferred for Packer configurations. ```json { "qemuargs": [ ["-m", "1024M"], ["--no-acpi", ""], [ "-netdev", "user,id=mynet0,", "hostfwd=hostip:hostport-guestip:guestport", "" ], ["-device", "virtio-net,netdev=mynet0"] ] } ``` -------------------------------- ### Vault KV Engine Setup (v1) Source: https://developer.hashicorp.com/packer/docs/templates/user-variables Example command to enable a v1 KV secrets engine in HashiCorp Vault and put a secret. ```bash vault secrets enable -version=1 -path=secrets kv vault kv put secrets/hello foo=world ``` ```bash vault secrets enable -version=1 -path=secrets kv vault kv put secrets/hello foo=world ``` -------------------------------- ### Basic Breakpoint Provisioner Example (JSON) Source: https://developer.hashicorp.com/packer/docs/provisioners/breakpoint This JSON example shows the equivalent configuration of the breakpoint provisioner in a Packer build. It pauses the build between shell-local provisioners. ```json { "builders": [ { "type": "null", "communicator": "none" } ], "provisioners": [ { "type": "shell-local", "inline": "echo hi" }, { "type": "breakpoint", "disable": false, "note": "this is a breakpoint" }, { "type": "shell-local", "inline": "echo hi 2" } ] } ``` -------------------------------- ### Basic Azure DTL Artifact Provisioner Example Source: https://developer.hashicorp.com/packer/integrations/hashicorp/azure/latest/components/provisioner/dtlartifact This example demonstrates how to configure the `azure-dtlartifact` provisioner to apply a Linux package artifact to a specified virtual machine within an Azure DevTest Lab. It includes setting artifact parameters for package installation and updates. ```hcl source "null" "example" { communicator = "none" } build { sources = ["source.null.example"] provisioner "azure-dtlartifact" { lab_name = "packer-test" lab_resource_group_name = "packer-test" vm_name = "packer-test-vm" dtl_artifacts { artifact_name = "linux-apt-package" parameters { name = "packages" value = "vim" } parameters { name = "update" value = "true" } parameters { name = "options" value = "--fix-broken" } } } } ``` -------------------------------- ### HTTP Server Example Usage Source: https://developer.hashicorp.com/packer/integrations/hashicorp/virtualbox/latest/components/builder/ovf Example of how to reference files served by Packer's HTTP server within a builder's boot command. ```shell wget http://{{ .HTTPIP }}:{{ .HTTPPort }}/foo/bar/preseed.cfg ``` ```shell wget http://{{ .HTTPIP }}:{{ .HTTPPort }}/foo/bar/preseed.cfg ``` -------------------------------- ### Basic shell-local Provisioner Example (JSON) Source: https://developer.hashicorp.com/packer/docs/provisioners/shell-local This example shows the equivalent Packer configuration for the shell-local provisioner in JSON format. It mirrors the HCL example, demonstrating how to define builders and provisioners. ```json { "builders": [ { "type": "file", "name": "example", "target": "./test_artifact.txt", "content": "example content" } ], "provisioners": [ { "type": "shell-local", "inline": ["echo foo"] } ] } ``` -------------------------------- ### Packer Configuration for Windows Unattended Install with WinRM Source: https://developer.hashicorp.com/packer/guides/automatic-operating-system-installs/autounattend_windows This Packer configuration uses the virtualbox-iso builder for an unattended Windows installation. It specifies the ISO, checksum, shutdown command, and includes floppy files for the autounattend.xml and an SSH setup script. It configures the WinRM communicator with provided credentials. ```json { "type": "virtualbox-iso", "guest_os_type": "Windows2008_64", "iso_url": "https://download.microsoft.com/download/7/5/E/75EC4E54-5B02-42D6-8879-D8D3A25FBEF7/7601.17514.101119-1850_x64fre_server_eval_en-us-GRMSXEVAL_EN_DVD.iso", "iso_checksum": "sha256:30832AD76CCFA4CE48CCB936EDEFE02079D42FB1DA32201BF9E3A880C8ED6312", "shutdown_command": "shutdown /s /t 10 /f /d p:4:1 /c Packer_Provisioning_Shutdown", "guest_additions_mode": "attach", "floppy_files": ["./scripts/Autounattend.xml", "./scripts/openssh.ps1"], "communicator": "winrm", "winrm_username": "vagrant", "winrm_password": "vagrant" } ``` -------------------------------- ### VirtualBox OVF Boot Configuration Example Source: https://developer.hashicorp.com/packer/plugins/builders/virtualbox/ovf Example boot parameters for a Debian-based distribution using an OVF template. These parameters are sent to the VM via VBoxManage. ```shell "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 -- " ``` -------------------------------- ### Error Cleanup Provisioner Example (JSON) Source: https://developer.hashicorp.com/packer/docs/templates/legacy_json_templates/provisioners Toy example demonstrating the `error-cleanup-provisioner`. This provisioner runs only if the normal provisioning fails, allowing for last-minute cleanup before the instance is shut down. ```json { "builders": [ { "type": "null", "communicator": "none" } ], "provisioners": [ { "type": "shell-local", "inline": ["exit 2"] } ], "error-cleanup-provisioner": { "type": "shell-local", "inline": ["echo 'rubber ducky'> ducky.txt"] } } ``` -------------------------------- ### Kickstart Script for User and SSH Key Setup Source: https://developer.hashicorp.com/packer/integrations/hashicorp/qemu/latest/components/builder/qemu A kickstart script snippet that processes kernel command line arguments to set up a user and configure SSH key authentication using the provided public key. ```bash %post # Newly created users need the file/folder framework for SSH key authentication. umask 0077 mkdir /etc/skel/.ssh touch /etc/skel/.ssh/authorized_keys # Loop over the command line. Set interesting variables. for x in $(cat /proc/cmdline) do case $x in PACKER_USER=*) PACKER_USER="${x#*=}" ;; PACKER_AUTHORIZED_KEY=*) # URL decode $encoded into $PACKER_AUTHORIZED_KEY encoded=$(echo "${x#*=}" | tr '+' ' ') printf -v PACKER_AUTHORIZED_KEY '%b' "${encoded//%/\x}" ;; esac done # Create/configure packer user, if any. if [ -n "$PACKER_USER" ] then useradd $PACKER_USER echo "%${PACKER_USER} ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/$PACKER_USER [ -n "$PACKER_AUTHORIZED_KEY" ] && echo $PACKER_AUTHORIZED_KEY >> $(eval echo ~"$PACKER_USER")/.ssh/authorized_keys fi %end ``` -------------------------------- ### Basic String Validation with Length and Prefix Source: https://developer.hashicorp.com/packer/docs/templates/hcl_templates/blocks/variable Use the `validation` block to enforce conditions on variable values. This example checks if a string variable is longer than 4 characters and starts with 'ami-'. ```hcl variable "image_id" { type = string description = "The ID of the machine image (AMI) to use for the server." validation { condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-" error_message = "The image_id value must be a valid AMI ID, starting with \"ami-\"." } } ``` -------------------------------- ### Packer Build Configuration with QEMU and Google Compute Import Source: https://developer.hashicorp.com/packer/integrations/hashicorp/googlecompute/latest/components/post-processor/googlecompute-import This example demonstrates a full Packer build configuration. It includes the qemu builder for creating a disk image and the googlecompute-import post-processor to upload the image to Google Compute Engine. ```json { "variables": { "account_file": "account.json", "bucket": "my-bucket", "project": "my-project", "serial": "" }, "builders": [ { "type": "qemu", "accelerator": "kvm", "boot_command": [ " console=ttyS0,115200n8 inst.text inst.ks=http://{{ .HTTPIP }}:{{ .HTTPPort }}/fedora-31-ks.cfg rd.live.check=0" ], "disk_size": "15000", "format": "raw", "iso_checksum": "sha256:225ebc160e40bb43c5de28bad9680e3a78a9db40c9e3f4f42f3ee3f10f95dbeb", "iso_url": "https://download-ib01.fedoraproject.org/pub/fedora/linux/releases/31/Server/x86_64/iso/Fedora-Server-dvd-x86_64-31-1.9.iso", "headless": "true", "http_directory": "http", "http_port_max": "10089", "http_port_min": "10082", "output_directory": "output", "shutdown_timeout": "30m", "shutdown_command": "echo 'vagrant'|sudo -S shutdown -P now", "ssh_username": "vagrant", "ssh_password": "vagrant", "vm_name": "disk.raw", "qemu_binary": "/usr/bin/kvm", "qemuargs": [ ["-m", "1024"], ["-cpu", "host"], ["-chardev", "tty,id=pts,path={{user `serial`}}"], ["-device", "isa-serial,chardev=pts"], ["-device", "virtio-net,netdev=user.0"] ] } ], "post-processors": [ [ { "type": "compress", "output": "output/disk.raw.tar.gz" }, { "type": "googlecompute-import", "project_id": "{{user `project`}}", "account_file": "{{user `account_file`}}", "bucket": "{{user `bucket`}}", "image_name": "fedora31-server-packertest", "image_description": "Fedora 31 Server", "image_family": "fedora31-server" } ] ] } ``` -------------------------------- ### Windows Server 2012 R2 Unattend Configuration Source: https://developer.hashicorp.com/packer/integrations/hashicorp/hyperv/latest/components/builder/vmcx This XML snippet configures settings for Windows Server 2012 R2, including installing Windows Updates and user account setup. ```xml cmd.exe /c IF EXIST a:\win-updates.ps1 (C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File a:\win-updates.ps1) ELSE (C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File f:\win-updates.ps1) Install Windows Updates 100 true true true true true true Work 1 vagrant true</PlainText> </AdministratorPassword> <LocalAccounts> <LocalAccount wcm:action="add"> <Password> <Value>vagrant</Value> <PlainText>true</PlainText> </Password> <Group>administrators</Group> <DisplayName>Vagrant</DisplayName> <Name>vagrant</Name> <Description>Vagrant User</Description> </LocalAccount> </LocalAccounts> </UserAccounts> <RegisteredOwner /> <TimeZone>Coordinated Universal Time</TimeZone> </component> </settings> <settings pass="offlineServicing"> <component name="Microsoft-Windows-LUA-Settings" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <EnableLUA>false</EnableLUA> </component> </settings> <cpi:offlineImage cpi:source="wim:c:/projects/baseboxes/9600.16384.winblue_rtm.130821-1623_x64fre_server_eval_en-us-irm_sss_x64free_en-us_dv5_slipstream/sources/install.wim#Windows Server 2012 R2 SERVERDATACENTER" xmlns:cpi="urn:schemas-microsoft-com:cpi" /> </unattend> ``` -------------------------------- ### Extracting the Basename of a Path Source: https://developer.hashicorp.com/packer/docs/templates/hcl_templates/functions/file/basename This example demonstrates how to use the basename function to get the final part of a file path string. The function operates on the string representation and does not interact with the actual filesystem. ```hcl > basename("foo/bar/baz.txt") baz.txt ``` -------------------------------- ### Basic QEMU Arguments Configuration (JSON) Source: https://developer.hashicorp.com/packer/integrations/hashicorp/qemu/latest/components/builder/qemu Example of setting basic QEMU arguments in JSON format for memory and network configuration. ```json "qemuargs": [ [ "-m", "1024M" ], [ "--no-acpi", "" ], [ "-netdev", "user,id=mynet0,", "hostfwd=hostip:hostport-guestip:guestport", "" ], [ "-device", "virtio-net,netdev=mynet0" ] ] ``` -------------------------------- ### Azure VM Provisioning with Ansible (WinRM) Source: https://developer.hashicorp.com/packer/integrations/hashicorp/ansible/latest/components/provisioner/ansible Example Packer HCL2 configuration for building an Azure VM and provisioning it with Ansible using WinRM. Requires pywinrm to be installed locally and the ConfigureRemotingForAnsible.ps1 script. ```hcl source "azure-arm" "server_2019" { use_azure_cli_auth = true build_resource_group_name = "ManagedImages-RGP" build_key_vault_name = "Example-Packer-Keyvault" os_type = "Windows" image_publisher = "MicrosoftWindowsServer" image_offer = "WindowsServer" image_sku = "2019-Datacenter" vm_size = "Standard_D2as_v5" os_disk_size_gb = 130 shared_gallery_image_version_exclude_from_latest = false virtual_network_resource_group_name = "VNET-Resource-Group" virtual_network_name = "My-VNET" virtual_network_subnet_name = "My-Subnet" private_virtual_network_with_public_ip = false communicator = "winrm" winrm_use_ssl = true winrm_insecure = true winrm_timeout = "3m" winrm_username = "Packer" managed_image_name = "Managed-Image-Name" managed_image_resource_group_name = "ManagedImages-RGP" managed_image_storage_account_type = "Standard_LRS" shared_image_gallery_destination { resource_group = "ManagedImages-RGP" gallery_name = "MyGallery" image_name = "Server2019" storage_account_type = "Standard_LRS" } } build { sources = [ ``` -------------------------------- ### Basic shell-local Provisioner Example Source: https://developer.hashicorp.com/packer/docs/provisioners/shell-local This example demonstrates the basic usage of the shell-local provisioner within a Packer build configuration. It shows how to define a source and then use the shell-local provisioner to execute an inline shell command. ```hcl source "file" "example" { content = "example content" } build { source "source.file.example" { target = "./test_artifact.txt" } provisioner "shell-local" { inline = ["echo foo"] } } ```