Fix crash when variables block is undefined

This change fixes a crash that occurs when trying to add undeclared variables into an empty
variables map. The variables block when defined will always be non-nil but in the case
where variables are declared and initialized from a legacy JSON variables file the map
must be initialized first.
pull/12258/head
Wilken Rivera 3 years ago committed by Wilken Rivera
parent b986a7c948
commit 095959ed6d

@ -870,6 +870,9 @@ func (p *VariableParser) Parse(tpl *template.Template) error {
p.localsOut = []byte{}
}
if len(tpl.Variables) == 0 {
tpl.Variables = make(map[string]*template.Variable)
}
// JSON supports variable declaration via var-files.
// User variables that might be defined in a var-file
// but not in the actual JSON template should be accounted for.

@ -34,6 +34,7 @@ func Test_hcl2_upgrade(t *testing.T) {
{folder: "variables-with-variables", flags: []string{}},
{folder: "complete-variables-with-template-engine", flags: []string{}},
{folder: "undeclared-variables", flags: []string{}, exitCode: 0},
{folder: "varfile-with-no-variables-block", flags: []string{}, exitCode: 0},
}
for _, tc := range tc {

@ -0,0 +1,33 @@
variable "ssh_host" {
type = string
}
variable "ssh_password" {
type = string
}
variable "ssh_username" {
type = string
}
variable "version_tag" {
type = string
}
source "null" "autogenerated_1" {
communicator = "ssh"
ssh_host = "${var.ssh_host}"
ssh_password = "${var.ssh_password}"
ssh_username = "${var.ssh_username}"
}
build {
sources = ["source.null.autogenerated_1"]
provisioner "shell-local" {
inline = ["echo ${var.version_tag} > provision.txt"]
pause_before = "20s"
}
}

@ -0,0 +1,18 @@
{
"builders": [
{
"type": "null",
"communicator": "ssh",
"ssh_host": "{{ user `ssh_host` }}",
"ssh_password": "{{ user `ssh_password` }}",
"ssh_username": "{{ user `ssh_username` }}"
}
],
"provisioners": [
{
"pause_before": "20s",
"type": "shell-local",
"inline": [ "echo {{ user `version_tag` }} > provision.txt" ]
}
]
}

@ -0,0 +1,6 @@
{
"version_tag": "1.0.0",
"ssh_host": "localhost",
"ssh_username": "packer",
"ssh_password": "packer"
}
Loading…
Cancel
Save