### Packer Plugin Installation Confirmation Source: https://github.com/hashicorp/packer/blob/main/website/content/guides/1.7-template-upgrade.mdx This is an example output from the `packer init` command, confirming that a specific plugin (`sylviamoss/comment` version `v0.2.23`) has been successfully downloaded and installed to the user's local Packer plugin directory. ```shell Installed plugin sylviamoss/comment v0.2.23 in "/Users//.packer.d/plugins/github.com/sylviamoss/comment/packer-plugin-comment_v0.2.23_x5.0_darwin_amd64" ``` -------------------------------- ### Manually Install Plugins via CLI Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/plugins/install.mdx Demonstrates how to install a plugin binary from a local path using the packer plugins install command. This is useful for offline environments or custom plugin distributions. ```shell-session $ unzip packer-plugin-happycloud.zip $ ls -l -rwxr-xr-x [...] happycloud $ packer plugins install --path happycloud github.com/hashicorp/happycloud ``` -------------------------------- ### Basic Shell Provisioner Example Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/provisioners/shell.mdx This example demonstrates the basic usage of the shell provisioner to execute a simple echo command. It shows how to define the provisioner and its inline script in both HCL2 and JSON formats. ```HCL2 provisioner "shell" { inline = ["echo foo"] } ``` ```JSON { "type": "shell", "inline": ["echo foo"] } ``` -------------------------------- ### Packer ISO Configuration Examples (HCL2) Source: https://github.com/hashicorp/packer/blob/main/website/content/partials/packer-plugin-sdk/multistep/commonsteps/ISOConfig.mdx Illustrates how to define ISO download URLs and checksums using HCL2 syntax for Packer configurations. Includes examples for direct checksums and file references. ```hcl iso_checksum = "946a6077af6f5f95a51f82fdc44051c7aa19f9cfc5f737954845a6050543d7c2" iso_url = "ubuntu.org/.../ubuntu-14.04.1-server-amd64.iso" ``` ```hcl iso_checksum = "file:ubuntu.org/..../ubuntu-14.04.1-server-amd64.iso.sum" iso_url = "ubuntu.org/.../ubuntu-14.04.1-server-amd64.iso" ``` ```hcl iso_checksum = "file://./shasums.txt" iso_url = "ubuntu.org/.../ubuntu-14.04.1-server-amd64.iso" ``` ```hcl iso_checksum = "file:./shasums.txt" iso_url = "ubuntu.org/.../ubuntu-14.04.1-server-amd64.iso" ``` -------------------------------- ### Basic AWS Packer Template Example Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/templates/legacy_json_templates/index.mdx A standard Packer template configuration for creating an AWS EBS-backed AMI, including a shell provisioner to execute a setup script. ```json { "builders": [ { "type": "amazon-ebs", "access_key": "...", "secret_key": "...", "region": "us-east-1", "source_ami": "ami-fce3c696", "instance_type": "t2.micro", "ssh_username": "ubuntu", "ami_name": "packer {{timestamp}}" } ], "provisioners": [ { "type": "shell", "script": "setup_things.sh" } ] } ``` -------------------------------- ### Building and Installing a Custom Packer Docker Plugin Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/plugins/install.mdx This sequence of shell commands demonstrates cloning a plugin repository, building it as a development binary using Go, and then installing it into Packer. It includes steps for validation and usage. ```shell $ git clone https://github.com/hashicorp/packer-plugin-docker.git ``` ```shell $ cd packer-plugin-docker $ go build -ldflags="-X github.com/hashicorp/packer-plugin-docker/version.VersionPrerelease=dev" -o packer-plugin-docker-dev ``` ```shell $ ./packer-plugin-docker-dev describe {"version":"1.0.10-dev","sdk_version":"0.5.2","api_version":"x5.0","builders":["-packer-default-plugin-name-"],"post_processors":["import","push","save","tag"],"provisioners":[],"datasources":[]} ``` ```shell packer plugins install --path packer-plugin-docker-dev github.com/hashicorp/docker Successfully installed plugin github.com/hashicorp/docker from $HOME/Development/packer-plugin-docker/packer-plugin-docker-dev to ~/github.com/hashicorp/docker/packer-plugin-docker_v1.0.10-dev_x5.0_darwin_arm64 ``` ```shell $ packer build . ``` -------------------------------- ### Packer HCL chunklist Function Examples Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/templates/hcl_templates/functions/collection/chunklist.mdx Illustrates practical examples of the `chunklist` function in Packer HCL, showing how different chunk sizes affect the output. The examples demonstrate splitting a list into chunks of size 2 and size 1. ```shell > chunklist(["a", "b", "c", "d", "e"], 2) [ ["a", "b"], ["c", "d"], ["e"] ] > chunklist(["a", "b", "c", "d", "e"], 1) [ ["a"], ["b"], ["c"], ["d"], ["e"] ] ``` -------------------------------- ### Packer Build Output Example Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/commands/index.mdx This example demonstrates the machine-readable output format generated by `packer build`. It includes various data types such as 'ui' (for messages and errors), 'artifact-count', and 'artifact' details, showing timestamps, builder IDs, and artifact information. ```text 1539967803,,ui,say,\n==> Builds finished. The artifacts of successful builds are: 1539967803,amazon-ebs,artifact-count,2 1539967803,amazon-ebs,artifact,0,builder-id,mitchellh.amazonebs 1539967803,amazon-ebs,artifact,0,id,eu-west-1:ami-04d23aca8bdd36e30 1539967803,amazon-ebs,artifact,0,string,AMIs were created: eu-west-1: ami-04d23aca8bdd36e30\n 1539967803,amazon-ebs,artifact,0,files-count,0 1539967803,amazon-ebs,artifact,0,end 1539967803,,ui,say,--> amazon-ebs: AMIs were created: eu-west-1: ami-04d23aca8bdd36e30\n 1539967803,amazon-ebs,artifact,1,builder-id, 1539967803,amazon-ebs,artifact,1,id, 1539967803,amazon-ebs,artifact,1,string, 1539967803,amazon-ebs,artifact,1,files-count,0 2018/10/19 09:50:03 waiting for all plugin processes to complete... 1539967803,amazon-ebs,artifact,1,end ``` -------------------------------- ### Initialize Packer Plugins with packer init Source: https://github.com/hashicorp/packer/blob/main/website/content/guides/1.7-template-upgrade.mdx This shell command initializes a Packer template by downloading and installing all the required plugins defined in the `required_plugins` block. It ensures that the plugins are available in the local Packer environment before proceeding with a build. The output confirms the plugin installation path and version. ```shell packer init example.pkr.hcl ``` -------------------------------- ### Basic hcp-packer-version Data Source Example Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/datasources/hcp/hcp-packer-version.mdx A basic example demonstrating how to use the `hcp-packer-version` data source to retrieve information about an HCP Packer Version. This information can then be accessed as a variable for subsequent use in Packer configurations. ```hcl data "hcp-packer-version" "hardened-source" { bucket_name = "hardened-ubuntu-16-04" channel_name = "dev" } ``` -------------------------------- ### Packer CLI Autocompletion Example Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/commands/index.mdx This example shows how to enable and use shell autocompletion for the Packer CLI. After installation with `packer -autocomplete-install`, typing a partial command and pressing Tab provides suggestions for subcommands and flags. ```shell $ packer p plugin build $ packer build - -color -debug -except -force -machine-readable -on-error -only -parallel -timestamp -var -var-file ``` -------------------------------- ### Example: Using shell-local with WSL on Windows Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/provisioners/shell-local.mdx Demonstrates how to configure the shell-local provisioner to execute bash scripts using the Windows Subsystem for Linux (WSL). ```APIDOC ## Example: Shell-Local with WSL on Windows ### Description This example shows how to configure the `shell-local` provisioner to run bash scripts on a Windows host using the Windows Subsystem for Linux (WSL). It involves setting `use_linux_pathing` to `true` and customizing the `execute_command`. ### Method Provisioner Configuration ### Endpoint N/A (Provisioner Configuration) ### Parameters - `execute_command`: Set to `["bash", "-c", "{{.Vars}} {{.Script}}"]` to invoke bash. - `use_linux_pathing`: Set to `true` to ensure correct path interpretation within WSL. - `scripts` or `script`: Provide the path to your bash script. ### Request Example (HCL2) ```hcl provisioner "shell-local"{ environment_vars = ["PROVISIONERTEST=ProvisionerTest1"] execute_command = ["bash", "-c", "{{.Vars}} {{.Script}}"] use_linux_pathing = true scripts = ["C:/Users/me/scripts/example_bash.sh"] } ``` ### Request Example (JSON) ```json { "type": "shell-local", "environment_vars": ["PROVISIONERTEST=ProvisionerTest1"], "execute_command": ["bash", "-c", "{{.Vars}} {{.Script}}"], "use_linux_pathing": true, "scripts": ["C:/Users/me/scripts/example_bash.sh"] } ``` ### Response #### Success Response (200) Bash script executed successfully within the WSL environment. #### Response Example N/A (Output is logged by Packer). ``` -------------------------------- ### Basic windows-shell provisioner configuration Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/provisioners/windows-shell.mdx A simple example demonstrating how to define a windows-shell provisioner to execute a directory listing command on a Windows target. ```hcl provisioner "windows-shell" { inline = ["dir c:\\"] } ``` ```json { "type": "windows-shell", "inline": ["dir c:\\"] } ``` -------------------------------- ### Full hcp-packer-image and hcp-packer-iteration Example Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/datasources/hcp/hcp-packer-image.mdx A comprehensive example illustrating the use of `hcp-packer-image` with `hcp-packer-iteration` to retrieve an image ID via a channel. This setup allows for creating build pipelines where a base image is customized in secondary layers, using the output from previous Packer builds. ```hcl # Retrieves information about the HCP Packer "iteration"; an "iteration" can be # thought of as all the metadata created by a single call of `packer build`. data "hcp-packer-iteration" "hardened-source" { bucket_name = "hardened-ubuntu-16-04" channel = "packer-test" } # Retrieves information about the HCP Packer "image"; an image can be thought # of as all the metadata (including the artifact names) created by a single # "source" builder; this can include multiple images so we provide a cloud # region to disambiguate. data "hcp-packer-image" "foo" { bucket_name = "hardened-ubuntu-16-04" iteration_id = data.hcp-packer-iteration.hardened-source.id cloud_provider = "aws" region = "us-east-1" } # This source uses the output from a previous Packer build. By using the # HCP Packer registry in this way, you can easily create build pipelines where # a single base image can be customized in multiple secondary layers. source "amazon-ebs" "packer-secondary" { source_ami = data.hcp-packer-image.foo.id # ... } ``` -------------------------------- ### Packer Build Command Examples Source: https://github.com/hashicorp/packer/blob/main/website/content/guides/hcl/variables.mdx Demonstrates how to execute a Packer build using default variables or specifying a configuration file. ```shell $ packer build . $ packer build self_contained_example.pkr.hcl ``` -------------------------------- ### Windows Host - Running .cmd file Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/provisioners/shell-local.mdx Example demonstrating how to execute a `.cmd` file on a Windows host using the `shell-local` provisioner. ```APIDOC ## Windows Host - Running .cmd file ### Description This example shows how to run a Windows batch command file (`.cmd`) using the `shell-local` provisioner. It sets an environment variable and executes a script. ### Method POST ### Endpoint N/A (Provisioner configuration within a Packer template) ### Parameters #### Request Body (HCL2 Example) ```hcl provisioner "shell-local" { environment_vars = ["SHELLLOCALTEST=ShellTest1"] scripts = ["./scripts/test_cmd.cmd"] } ``` #### Request Body (JSON Example) ```json { "type": "shell-local", "environment_vars": ["SHELLLOCALTEST=ShellTest1"], "scripts": ["./scripts/test_cmd.cmd"] } ``` ### Request Example (Contents of "test_cmd.cmd") ```batch echo %SHELLLOCALTEST% ``` ### Response N/A (Output is typically logged during the Packer build process.) ``` -------------------------------- ### Extracting elements from a list using slice Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/templates/hcl_templates/functions/collection/slice.mdx This example demonstrates how to use the slice function to extract a range of elements from a list. The start index is inclusive and the end index is exclusive. ```hcl slice(["a", "b", "c", "d"], 1, 3) ``` ```shell-session > slice(["a", "b", "c", "d"], 1, 3) [ "b", "c", ] ``` -------------------------------- ### Packer File Provisioner Examples Source: https://context7.com/hashicorp/packer/llms.txt Illustrates the usage of the file provisioner in Packer for uploading files and directories to the target machine. Shows how to upload single files and entire directories, with attention to trailing slashes. ```hcl # Upload single file provisioner "file" { source = "app/config.json" destination = "/tmp/config.json" } # Upload directory (trailing slash matters) provisioner "file" { source = "configs/" # Contents of configs/ go to /etc/app/ destination = "/etc/app/" } provisioner "file" { source = "configs" # Creates /etc/app/configs/ destination = "/etc/app/" } ``` -------------------------------- ### Configure shell-local post-processor with WSL in JSON Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/post-processors/shell-local.mdx This JSON configuration illustrates the equivalent setup for the shell-local post-processor with WSL as the HCL2 example. It configures `use_linux_pathing` and `execute_command` for bash script execution within WSL, along with environment variables and script paths. ```json { "builders": [ { "type": "null", "communicator": "none" } ], "post-processors": [ { "type": "shell-local", "environment_vars": ["PROVISIONERTEST=ProvisionerTest1"], "execute_command": ["bash", "-c", "{{.Vars}} {{.Script}}"], "use_linux_pathing": true, "scripts": ["C:/Users/me/scripts/example_bash.sh"] }, { "type": "shell-local", "environment_vars": ["PROVISIONERTEST=ProvisionerTest2"], "execute_command": ["bash", "-c", "{{.Vars}} {{.Script}}"], "use_linux_pathing": true, "script": "C:/Users/me/scripts/example_bash.sh" } ] } ``` -------------------------------- ### Full hcp-packer-artifact and hcp-packer-version Integration Example Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/datasources/hcp/hcp-packer-artifact.mdx This full example illustrates the integration of `hcp-packer-artifact` with the `hcp-packer-version` data source. It first retrieves a version fingerprint using a channel from `hcp-packer-version`, then uses that fingerprint within `hcp-packer-artifact` to get artifact details. Finally, it shows how to use the artifact data source within a `source` block (e.g., `amazon-ebs`) to leverage outputs from previous Packer builds, enabling layered artifact customization. ```hcl # Retrieves information about the HCP Packer Version; a "version" can be # thought of as all the metadata created by a single call of `packer build`. data "hcp-packer-version" "hardened-source" { bucket_name = "hardened-ubuntu-16-04" channel_name = "dev" } # Retrieves information about the HCP Packer Artifact; an artifact can be thought # of as all the metadata (including the artifact names) created by a single # "source" builder; this can include multiple artifacts so we provide a # region to disambiguate. data "hcp-packer-artifact" "example" { bucket_name = "hardened-ubuntu-16-04" version_fingerprint = data.hcp-packer-version.hardened-source.fingerprint platform = "aws" region = "us-east-1" } # This source uses the output from a previous Packer build. By using the # HCP Packer Registry in this way, you can easily create build pipelines where # a single base artifact can be customized in multiple secondary layers. source "amazon-ebs" "packer-secondary" { source_ami = data.hcp-packer-artifact.example.external_identifier ... } ``` -------------------------------- ### Packer Shell Provisioner Examples Source: https://context7.com/hashicorp/packer/llms.txt Demonstrates various ways to use the shell provisioner in Packer, including running inline commands, executing script files, setting environment variables, and handling reboots. ```hcl # Inline commands provisioner "shell" { inline = [ "sudo apt-get update", "sudo apt-get install -y nginx curl wget", "sudo systemctl enable nginx" ] } # Script file provisioner "shell" { script = "scripts/install.sh" } # Multiple scripts (executed in order) provisioner "shell" { scripts = [ "scripts/base.sh", "scripts/install-deps.sh", "scripts/configure.sh", "scripts/cleanup.sh" ] } # With environment variables provisioner "shell" { environment_vars = [ "DEBIAN_FRONTEND=noninteractive", "APP_VERSION=${var.app_version}", "CONFIG_PATH=/etc/myapp" ] inline = [ "echo $APP_VERSION", "sudo mkdir -p $CONFIG_PATH" ] } # Custom execute command (for sudo with password) provisioner "shell" { execute_command = "echo 'vagrant' | sudo -S -E sh -c '{{ .Vars }} {{ .Path }}'" inline = ["apt-get update"] } # Handling reboots provisioner "shell" { expect_disconnect = true inline = ["sudo reboot"] } provisioner "shell" { pause_before = "30s" inline = ["echo 'Continuing after reboot'"] } ``` -------------------------------- ### HCL For Expression: Grouping Object Results by Key Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/templates/hcl_templates/expressions.mdx Illustrates an advanced HCL `for` expression that creates an object and uses the `...` suffix to group results by a common key. This example extracts the first character of strings, uses it as a key, and collects all strings starting with that character into a list associated with the key, filtering out empty strings. ```hcl {for s in var.list : substr(s, 0, 1) => s... if s != ""} ``` -------------------------------- ### Clone private Git repository using SSH agent forwarding Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/provisioners/shell.mdx This example demonstrates how to clone a private Git repository within a Packer build using SSH agent forwarding. It includes installing git, scanning the Git server's host key to avoid prompts, and then cloning the repository. This requires `ssh-agent` to be running on the client and the relevant SSH keys to be added. ```hcl provisioner "shell" { inline = [ "sudo apt-get install -y git", "ssh-keyscan github.com >> ~/.ssh/known_hosts", "git clone git@github.com:exampleorg/myprivaterepo.git" ] } ``` ```json { "type": "shell", "inline": [ "sudo apt-get install -y git", "ssh-keyscan github.com >> ~/.ssh/known_hosts", "git clone git@github.com:exampleorg/myprivaterepo.git" ] } ``` -------------------------------- ### Packer Plugins Installed Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/commands/plugins/index.mdx Lists all installed Packer plugin binaries. ```APIDOC ## packer plugins installed ### Description Lists all installed Packer plugin binaries. ### Method ```shell-session packer plugins installed ``` ``` -------------------------------- ### Serve Packer Plugin Components using Go Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/plugins/creation/index.mdx This Go code demonstrates how to register and serve different Packer plugin components (Builder, PostProcessor, Provisioner) using the packer-plugin-sdk. It initializes a plugin set, registers components with specific names or the default name, and runs the server to handle communication with Packer core. Ensure dependencies are managed with 'go mod'. ```go package main import ( "fmt" "github.com/hashicorp/packer-plugin-sdk/plugin" "os" ) // Assume this implements the packer.Builder interface type ExampleBuilder struct{} // Assume this implements the packer.PostProcessor interface type FooPostProcessor struct{} // Assume this implements the packer.Provisioner interface type BarProvisioner struct{} // Assume this implements the packer.Builder interface type AnotherBuilder struct{} func main() { pps := plugin.NewSet() pps.RegisterBuilder("example", new(ExampleBuilder)) pps.RegisterBuilder(plugin.DEFAULT_NAME, new(AnotherBuilder)) pps.RegisterPostProcessor("foo", new(FooPostProcessor)) pps.RegisterProvisioner("bar", new(BarProvisioner)) err := pps.Run() if err != nil { fmt.Fprintln(os.Stderr, err.Error()) os.Exit(1) } } ``` -------------------------------- ### Build AWS AMI with Packer Source: https://context7.com/hashicorp/packer/llms.txt This Packer template defines the configuration for building an Amazon Machine Image (AMI) for Ubuntu. It specifies the AWS region, instance type, source AMI filter, SSH username, block device mappings, and tags. It also includes provisioners for installing packages, copying configuration files, and running setup scripts, along with a post-processor to generate a manifest file. ```hcl packer { required_plugins { amazon = { version = ">= 1.2.0" source = "github.com/hashicorp/amazon" } } } variable "aws_region" { type = string default = "us-west-2" } variable "app_version" { type = string } variable "environment" { type = string default = "production" } locals { timestamp = regex_replace(timestamp(), "[- TZ:]", "") ami_name = "myapp-${var.app_version}-${local.timestamp}" } source "amazon-ebs" "ubuntu" { ami_name = local.ami_name instance_type = "t3.medium" region = var.aws_region source_ami_filter { filters = { name = "ubuntu/images/*ubuntu-jammy-22.04-amd64-server-*" root-device-type = "ebs" virtualization-type = "hvm" } most_recent = true owners = ["099720109477"] } ssh_username = "ubuntu" launch_block_device_mappings { device_name = "/dev/sda1" volume_size = 20 volume_type = "gp3" delete_on_termination = true } tags = { Name = local.ami_name Version = var.app_version Environment = var.environment BuildTime = timestamp() } } build { sources = ["source.amazon-ebs.ubuntu"] provisioner "shell" { inline = [ "sudo apt-get update", "sudo apt-get upgrade -y", "sudo apt-get install -y docker.io nginx" ] } provisioner "file" { source = "configs/" destination = "/tmp/configs/" } provisioner "shell" { scripts = [ "scripts/setup-app.sh", "scripts/hardening.sh", "scripts/cleanup.sh" ] environment_vars = [ "APP_VERSION=${var.app_version}", "ENVIRONMENT=${var.environment}" ] } post-processor "manifest" { output = "manifest.json" strip_path = true custom_data = { version = var.app_version environment = var.environment } } } ``` -------------------------------- ### Packer ISO Configuration Examples (JSON) Source: https://github.com/hashicorp/packer/blob/main/website/content/partials/packer-plugin-sdk/multistep/commonsteps/ISOConfig.mdx Demonstrates how to specify ISO download URLs and checksums within a JSON configuration for Packer. Supports direct checksums and file-based checksums. ```json { "iso_checksum": "946a6077af6f5f95a51f82fdc44051c7aa19f9cfc5f737954845a6050543d7c2", "iso_url": "ubuntu.org/.../ubuntu-14.04.1-server-amd64.iso" } ``` ```json { "iso_checksum": "file:ubuntu.org/..../ubuntu-14.04.1-server-amd64.iso.sum", "iso_url": "ubuntu.org/.../ubuntu-14.04.1-server-amd64.iso" } ``` ```json { "iso_checksum": "file://./shasums.txt", "iso_url": "ubuntu.org/.../ubuntu-14.04.1-server-amd64.iso" } ``` ```json { "iso_checksum": "file:./shasums.txt", "iso_url": "ubuntu.org/.../ubuntu-14.04.1-server-amd64.iso" } ``` -------------------------------- ### Packer Shell Provisioner Example Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/templates/legacy_json_templates/provisioners.mdx An example of a 'shell' provisioner definition in a Packer JSON template. This specific example configures the shell provisioner to execute a local script named 'script.sh' on the machine being created. ```json { "type": "shell", "script": "script.sh" } ``` -------------------------------- ### Packer Plugins Install Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/commands/plugins/index.mdx Installs the latest Packer plugin, optionally matching a specific version constraint. ```APIDOC ## packer plugins install ### Description Installs the latest Packer plugin, optionally matching a specific version constraint. ### Method ```shell-session packer plugins install ``` ### Parameters #### Query Parameters - **version** (string) - Optional - The version constraint for the plugin to install. ``` -------------------------------- ### windows-restart Provisioner with Custom Restart Check Command Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/provisioners/windows-restart.mdx This example illustrates how to configure the windows-restart provisioner with a custom command to check if the Windows guest machine has successfully restarted. This is useful for more complex restart scenarios or when the default check is insufficient. ```hcl2 provisioner "windows-restart" { restart_check_command = "powershell -command \"& {Write-Output 'restarted.'}\"" } ``` ```json { "type": "windows-restart", "restart_check_command": "powershell -command \"& {Write-Output 'restarted.'}\"" } ``` -------------------------------- ### Run Packer Provisioning Hook Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/plugins/creation/custom-builders.mdx This Go code demonstrates how to run the `packer.HookProvision` hook, which is essential for invoking provisioners. It requires a context, UI, communicator, and optionally, generated data. ```go hook.Run(context.Context, packer.HookProvision, ui, comm, nil) ``` ```go hook.Run(context.Context, packer.HookProvision, ui, comm, generatedData) ``` -------------------------------- ### Install VirtualBox on Ubuntu Source: https://github.com/hashicorp/packer/blob/main/website/content/guides/packer-on-cicd/build-virtualbox-image.mdx Downloads and installs the VirtualBox Debian package to enable the Packer VirtualBox builder. ```shell-session $ curl -OL "https://download.virtualbox.org/virtualbox/5.2.2/virtualbox-5.2_5.2.2-119230~Ubuntu~xenial_amd64.deb" $ dpkg -i virtualbox-5.2_5.2.2-119230~Ubuntu~xenial_amd64.deb ``` -------------------------------- ### Example: formatlist with string and list argument Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/templates/hcl_templates/functions/string/formatlist.mdx Shows how formatlist can format a list of values using a static string and a list of dynamic values. The static string is applied to each element of the list, creating a new list of formatted strings. ```shell-session > formatlist("%s, %s!", "Salutations", ["Valentina", "Ander", "Olivia", "Sam"]) [ "Salutations, Valentina!", "Salutations, Ander!", "Salutations, Olivia!", "Salutations, Sam!", ] ``` -------------------------------- ### Remove All Packer Plugins Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/commands/plugins/remove.mdx Removes all installed Packer plugins by piping the output of the 'packer plugins installed' command to the 'packer plugins remove' command using xargs. This is a convenient way to clean up all installed plugins on Unix-based systems. ```shell packer plugins installed | xargs -n1 packer plugins remove ``` -------------------------------- ### Scaffolding Provisioner Example in HCL Source: https://github.com/hashicorp/packer/blob/main/packer_test/common/plugin_tester/docs/provisioners/provisioner-name.mdx This HCL code demonstrates how to use the scaffolding provisioner within a Packer build. It configures a null source and then applies the scaffolding provisioner with a required 'mock' argument. ```hcl source "null" "example" { communicator = "none" } build { source "null.example" { name = "jay" } provisioner "scaffolding" { mock = "mocking ${source.name}" } } ``` -------------------------------- ### Configure shell-local post-processor Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/post-processors/shell-local.mdx This example demonstrates how to define a shell-local post-processor to execute an inline command after a file build. It shows the implementation in both HCL2 and JSON configuration styles. ```hcl source "file" "example" { content = "example content" } build { source "source.file.example" { target = "./test_artifact.txt" } post-processor "shell-local" { inline = ["echo foo"] } } ``` ```json { "builders": [ { "type": "file", "name": "example", "target": "./test_artifact.txt", "content": "example content" } ], "post-processors": [ { "type": "shell-local", "inline": ["echo foo"] } ] } ``` -------------------------------- ### GET /data/http Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/datasources/http.mdx Documentation for the http data source used to perform HTTP GET requests within Packer configurations. ```APIDOC ## GET http data source ### Description The `http` data source makes an HTTP `GET` request to the specified URL and exports information about the response for use in Packer builds. ### Method GET ### Endpoint N/A (Configured via HCL data block) ### Parameters #### Required Parameters - **url** (string) - Required - The URL to perform the GET request against. #### Optional Parameters - **request_headers** (map) - Optional - A map of key/value pairs to be sent as HTTP headers. ### Request Example ```hcl data "http" "example" { url = "https://checkpoint-api.hashicorp.com/v1/check/terraform" request_headers = { Accept = "application/json" } } ``` ### Response #### Success Response (200) - **body** (string) - The raw body of the HTTP response. - **status_code** (number) - The HTTP status code returned by the server. - **response_headers** (map) - The headers returned by the server. #### Response Example ```json { "body": "{\"current_version\": \"1.0.0\"}", "status_code": 200, "response_headers": { "Content-Type": "application/json" } } ``` ``` -------------------------------- ### List Installed Packer Plugins (Shell) Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/commands/plugins/installed.mdx The `packer plugins installed` command lists all installed plugin binaries that match the current operating system and architecture. This command does not consider Packer's API version. It is useful for verifying which plugins are available for use. ```shell $ packer plugins installed -h Usage: packer plugins installed This command lists all installed plugin binaries that match with the current OS and architecture. Packer's API version will be ignored. ``` -------------------------------- ### Configure shell-local provisioner in Packer Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/provisioners/shell-local.mdx This example demonstrates how to define a shell-local provisioner within a Packer build configuration. It shows the syntax for both HCL2 and JSON formats to execute a simple echo command on the host machine. ```hcl source "file" "example" { content = "example content" } build { source "source.file.example" { target = "./test_artifact.txt" } provisioner "shell-local" { inline = ["echo foo"] } } ``` ```json { "builders": [ { "type": "file", "name": "example", "target": "./test_artifact.txt", "content": "example content" } ], "provisioners": [ { "type": "shell-local", "inline": ["echo foo"] } ] } ``` -------------------------------- ### Example AWS Builder Definition Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/templates/legacy_json_templates/builders.mdx An example of a specific builder definition for the Amazon EBS builder, including required authentication parameters. ```APIDOC ## AWS EBS Builder Definition ### Description This example shows how to configure the `amazon-ebs` builder within the `builders` block of a Packer JSON template. It includes essential authentication details. ### Method N/A (Configuration Block) ### Endpoint N/A (Configuration Block) ### Parameters #### Request Body - **type** (string) - Required - Specifies the builder type as `amazon-ebs`. - **access_key** (string) - Required - Your AWS access key. - **secret_key** (string) - Required - Your AWS secret key. ### Request Example ```json { "type": "amazon-ebs", "access_key": "YOUR_AWS_ACCESS_KEY", "secret_key": "YOUR_AWS_SECRET_KEY" } ``` ### Response #### Success Response (200) N/A (This is a configuration block, not an API endpoint with a direct response.) #### Response Example N/A ``` -------------------------------- ### Full Build Template with Manifest Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/post-processors/manifest.mdx A complete example of a Docker build template that includes the manifest post-processor. ```hcl source "docker" "docker"{ image = "ubuntu:latest" export_path = "packer_example" run_command = ["-d", "-i", "-t", "--entrypoint=/bin/bash", "{{.Image}}"] } build { sources = ["docker.docker"] post-processor "manifest" { output = "manifest.json" strip_path = true custom_data = { my_custom_data = "example" } } } ``` ```json { "builders": [ { "type": "docker", "image": "ubuntu:latest", "export_path": "packer_example", "run_command": ["-d", "-i", "-t", "--entrypoint=/bin/bash", "{{.Image}}"] } ], "post-processors": [ { "type": "manifest", "output": "manifest.json", "strip_path": true, "custom_data": { "my_custom_data": "example" } } ] } ``` -------------------------------- ### Install Local Packer Plugin Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/plugins/creation/index.mdx Commands to install a locally compiled plugin binary into the Packer environment. This allows for testing the plugin before distribution. ```shell-session packer plugins install --path // packer plugins install --path packer-plugin-happycloud github.com/hashicorp/happycloud ``` -------------------------------- ### Rendering Maps with templatefile Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/templates/hcl_templates/functions/file/templatefile.mdx This example shows how to use `templatefile` to render a map of configuration settings. The template file iterates through the `config` map using a `for` loop to set key-value pairs. ```hcl %{ for config_key, config_value in config } set ${config_key} = ${config_value} %{ endfor ~} ``` -------------------------------- ### Install AWS CLI using pip Source: https://github.com/hashicorp/packer/blob/main/website/content/guides/packer-on-cicd/upload-images-to-artifact.mdx Installs the AWS Command Line Interface using pip. This is a prerequisite for interacting with S3 from the command line. ```shell pip install awscli ``` -------------------------------- ### Windows Host - Running Bash Script via WSL Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/provisioners/shell-local.mdx Example for running a bash script on Windows using WSL, configuring `execute_command` and `use_linux_pathing`. ```APIDOC ## Windows Host - Running Bash Script via WSL ### Description This example shows how to execute a bash script on a Windows host by leveraging the Windows Subsystem for Linux (WSL). It requires specific configurations for `execute_command` and `use_linux_pathing`. ### Method POST ### Endpoint N/A (Provisioner configuration within a Packer template) ### Parameters #### Request Body (HCL2 Example) ```hcl provisioner "shell-local" { environment_vars = ["SHELLLOCALTEST=ShellTest3"], execute_command = ["bash", "-c", "{{.Vars}} {{.Script}}"], use_linux_pathing = true, script = "./scripts/example_bash.sh" } ``` #### Request Body (JSON Example) ```json { "type": "shell-local", "environment_vars": ["SHELLLOCALTEST=ShellTest3"], "execute_command": ["bash", "-c", "{{.Vars}} {{.Script}}"], "use_linux_pathing": true, "script": "./scripts/example_bash.sh" } ``` ### Request Example (Contents of `example_bash.sh`) ```bash #!/bin/bash echo $SHELLLOCALTEST ``` ### Response N/A (Output is typically logged during the Packer build process.) ``` -------------------------------- ### cidrsubnet Function Examples Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/templates/hcl_templates/functions/ipnet/cidrsubnet.mdx Examples demonstrating the usage of the `cidrsubnet` function with different IPv4 and IPv6 prefixes, new bit counts, and network numbers. ```shell-session > cidrsubnet("172.16.0.0/12", 4, 2) 172.18.0.0/16 ``` ```shell-session > cidrsubnet("10.1.2.0/24", 4, 15) 10.1.2.240/28 ``` ```shell-session > cidrsubnet("fd00:fd12:3456:7890::/56", 16, 162) fd00:fd12:3456:7800:a200::/72 ``` -------------------------------- ### Packer Provisioner Override Example (JSON) Source: https://github.com/hashicorp/packer/blob/main/website/content/partials/packer-plugin-sdk/provisioners/common-config.mdx Illustrates the usage of the 'override' parameter in a Packer JSON configuration, showing how to customize provisioner behavior for specific builders. ```json { "builders": [ { "type": "null", "name": "example1", "communicator": "none" }, { "type": "null", "name": "example2", "communicator": "none" } ], "provisioners": [ { "type": "shell-local", "inline": ["echo not overridden"], "override": { "example1": { "inline": ["echo yes overridden"] } } } ] } ``` -------------------------------- ### Example of file function usage Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/templates/hcl_templates/functions/file/file.mdx Shows a practical example of reading a text file using the file function within a shell session context. ```shell-session > file("${path.folder}/hello.txt") Hello World ``` -------------------------------- ### Packer Boot Command Configuration (JSON) Source: https://github.com/hashicorp/packer/blob/main/website/content/partials/packer-plugin-sdk/bootcommand/BootConfig.mdx Defines the sequence of keystrokes to automate the OS installation process when a virtual machine first boots. It supports special key codes for navigation and actions, as well as template variables for dynamic content. ```json "boot_command": [ "", " ks=http://{{ .HTTPIP }}:{{ .HTTPPort }}/centos6-ks.cfg" ] ``` ```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 -- " ] ``` -------------------------------- ### Configure Minimal Manifest Post-Processor Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/post-processors/manifest.mdx Demonstrates the simplest way to enable the manifest post-processor in both HCL2 and JSON configuration formats. ```hcl post-processor "manifest" {} ``` ```json { "post-processors": [ { "type": "manifest" } ] } ``` -------------------------------- ### Example of timeadd calculation Source: https://github.com/hashicorp/packer/blob/main/website/content/docs/templates/hcl_templates/functions/datetime/timeadd.mdx Shows a practical example of adding 10 minutes to a specific timestamp. The output is a new RFC 3339 formatted string. ```shell-session > timeadd("2017-11-22T00:00:00Z", "10m") 2017-11-22T00:10:00Z ``` -------------------------------- ### Install TeamCity and VirtualBox Dependencies Source: https://github.com/hashicorp/packer/blob/main/website/content/guides/packer-on-cicd/build-virtualbox-image.mdx Installs essential system packages, including JDK and kernel headers, required for running TeamCity agents and VirtualBox on Ubuntu. ```shell-session $ apt-get upgrade $ apt-get install -y zip linux-headers-generic linux-headers-4.13.0-16-generic build-essential openjdk-8-jdk ```