make sure cli vars supercede var files (#8964)

This commit is contained in:
Megan Marsh 2020-03-30 01:31:59 -07:00 committed by GitHub
parent f909167524
commit f5c98a7601
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 2 deletions

View File

@ -32,7 +32,16 @@ func TestBuild_VarArgs(t *testing.T) {
},
fileCheck: fileCheck{expected: []string{"apple.txt"}},
},
{
name: "json - json varfile sets an apple env var, " +
"override with banana cli var",
args: []string{
"-var", "fruit=banana",
"-var-file=" + filepath.Join(testFixture("var-arg"), "apple.json"),
filepath.Join(testFixture("var-arg"), "fruit_builder.json"),
},
fileCheck: fileCheck{expected: []string{"banana.txt"}},
},
{
name: "json - arg sets a pear env var",
args: []string{
@ -401,6 +410,7 @@ func cleanup(moreFiles ...string) {
os.RemoveAll("lilas.txt")
os.RemoveAll("campanules.txt")
os.RemoveAll("ducky.txt")
os.RemoveAll("banana.txt")
for _, file := range moreFiles {
os.RemoveAll(file)
}

View File

@ -44,17 +44,23 @@ func (m *Meta) Core(tpl *template.Template) (*packer.Core, error) {
config.Template = tpl
fj := &kvflag.FlagJSON{}
// First populate fj with contents from var files
for _, file := range m.varFiles {
err := fj.Set(file)
if err != nil {
return nil, err
}
}
// Now read fj values back into flagvars and set as config.Variables. Only
// add to flagVars if the key doesn't already exist, because flagVars comes
// from the command line and should not be overridden by variable files.
if m.flagVars == nil {
m.flagVars = map[string]string{}
}
for k, v := range *fj {
m.flagVars[k] = v
if _, exists := m.flagVars[k]; !exists {
m.flagVars[k] = v
}
}
config.Variables = m.flagVars