From cf1a39a4e85eb518ee2d8f5a2d5004df775883a9 Mon Sep 17 00:00:00 2001 From: Megan Marsh Date: Wed, 26 Aug 2020 10:54:39 -0700 Subject: [PATCH] add variable gotcha to the variables docs not just the from-json hcl guides. --- website/pages/docs/from-1.5/variables.mdx | 66 +++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/website/pages/docs/from-1.5/variables.mdx b/website/pages/docs/from-1.5/variables.mdx index b4aea4a0f..c83c28720 100644 --- a/website/pages/docs/from-1.5/variables.mdx +++ b/website/pages/docs/from-1.5/variables.mdx @@ -168,6 +168,72 @@ $ packer build -var='image_id_map={"us-east-1":"ami-abc123","us-east-2":"ami-def The `-var` option can be used any number of times in a single command. +If you plan to assign variables via the command line, we strongly recommend that +you at least set a default type instead of using empty blocks; this helps the +HCL parser understand what is being set. + +For example: + +```hcl +variable "pizza" { + type = string +} +source "null" "example" { + communicator = "none" +} +build { + sources = [ + "source.null.example" + ] + provisioner "shell-local" { + inline = ["echo $PIZZA"] + environment_vars = ["PIZZA=${var.pizza}"] + } +} +``` + +If you call the above template using the command + +```sh +packer build -var pizza=pineapple shell_local_variables.pkr.hcl +``` + +then the Packer build will run successfully. However, if you define the variable +using an empty block, the parser will not know what type the variable is, and it +cannot infer the type from the command line, as shown in this example: + +```hcl +variable "pizza" {} +source "null" "example" { + communicator = "none" +} +build { + sources = [ + "source.null.example" + ] + provisioner "shell-local" { + inline = ["echo $PIZZA"] + environment_vars = ["PIZZA=${var.pizza}"] + } +} +``` +The above template will result in the error: + +``` +Error: Variables not allowed + on line 1: + (source code not available) +Variables may not be used here. +``` + +You can work around this either by quoting the variable on the command line, or +by adding the type to the variable block as shown in the previous example. +Setting the expected type is the more resilient option. + +```sh +packer build -var 'pizza="pineapple"' shell_local_variables.pkr.hcl +``` + ### Variable Definitions (`.pkrvars.hcl`) Files To set lots of variables, it is more convenient to specify their values in a