Skip to content

Commit

Permalink
Merge pull request #13051 from hashicorp/backport/docs/string-templat…
Browse files Browse the repository at this point in the history
…es/officially-on-garfish

This pull request was automerged via backport-assistant
  • Loading branch information
hc-github-team-packer authored Jun 14, 2024
2 parents 80ac03f + ecf4de1 commit b786867
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions website/content/docs/templates/hcl_templates/expressions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -429,3 +429,54 @@ beginning a template sequence, double the leading character: `$${` or `%%{`.
Within quoted and heredoc string expressions, the sequences `${` and `%{` begin
_template sequences_. Templates let you directly embed expressions into a string
literal, to dynamically construct strings from other values.

The following 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:

```hcl
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:

```shell
$ 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
```

0 comments on commit b786867

Please sign in to comment.