hashicorp / packer

Packer is a tool for creating identical machine images for multiple platforms from a single source configuration.
http://www.packer.io
Other
14.98k stars 3.33k forks source link

docs: string templates #13049

Closed tenthirtyam closed 2 weeks ago

tenthirtyam commented 2 weeks ago

Description

Adds an example of a string template being used.

The example demonstrates how a template sequence can be used to embed the value of a variable into a string that can be used as script content.

locals {
  packages = ["git", "curl", "vim"]

  install_packages = <<-EOF
    #!/bin/bash
    if [ ${length(local.packages)} -eq 0 ]; then
      echo "No packages to install."
      exit 1
    fi
    apt-get update
    %{ for package in local.packages ~}
    apt-get install -y ${package}
    %{ endfor ~}
  EOF
}

source "amazon-ebs" "example" {
  # ...
}

build {
  sources = ["source.amazon-ebs.example"]

  provisioner "shell" {
    inline = [local.install_packages]
  }
}

This can be tested using the packer console command:

$ packer source.pkr.hcl

> local.install_packages

> #!/bin/bash
if [ 3 -eq 0 ]; then
  echo "No packages to install."
  exit 1
fi
apt-get update
    apt-get install -y git
    apt-get install -y curl
    apt-get install -y vim

Reference

Closes #12651