Commit e0a9215e authored by Mitchell Hashimoto's avatar Mitchell Hashimoto

packer: test for environment variables interpolation

parent 913d6f69
......@@ -66,12 +66,17 @@ func NewCore(c *CoreConfig) (*Core, error) {
builds[v] = b
}
return &Core{
result := &Core{
components: c.Components,
template: c.Template,
variables: c.Variables,
builds: builds,
}, nil
}
if err := result.init(); err != nil {
return nil, err
}
return result, nil
}
// BuildNames returns the builds that are available in this configured core.
......@@ -228,3 +233,35 @@ func (c *Core) Validate() error {
return err
}
func (c *Core) init() error {
if c.variables == nil {
c.variables = make(map[string]string)
}
// Go through the variables and interpolate the environment variables
ctx := &interpolate.Context{EnableEnv: true}
for k, v := range c.template.Variables {
// Ignore variables that are required
if v.Required {
continue
}
// Ignore variables that have a value
if _, ok := c.variables[k]; ok {
continue
}
// Interpolate the default
def, err := interpolate.Render(v.Default, ctx)
if err != nil {
return fmt.Errorf(
"error interpolating default value for '%s': %s",
k, err)
}
c.variables[k] = def
}
return nil
}
......@@ -5,6 +5,7 @@ import (
"reflect"
"testing"
configHelper "github.com/mitchellh/packer/helper/config"
"github.com/mitchellh/packer/template"
)
......@@ -108,6 +109,38 @@ func TestCoreBuild_basicInterpolated(t *testing.T) {
}
}
func TestCoreBuild_env(t *testing.T) {
os.Setenv("PACKER_TEST_ENV", "test")
defer os.Setenv("PACKER_TEST_ENV", "")
config := TestCoreConfig(t)
testCoreTemplate(t, config, fixtureDir("build-env.json"))
b := TestBuilder(t, config, "test")
core := TestCore(t, config)
b.ArtifactId = "hello"
build, err := core.Build("test")
if err != nil {
t.Fatalf("err: %s", err)
}
if _, err := build.Prepare(); err != nil {
t.Fatalf("err: %s", err)
}
// Interpolate the config
var result map[string]interface{}
err = configHelper.Decode(&result, nil, b.PrepareConfig...)
if err != nil {
t.Fatalf("err: %s", err)
}
if result["value"] != "test" {
t.Fatalf("bad: %#v", result)
}
}
func TestCoreBuild_nonExist(t *testing.T) {
config := TestCoreConfig(t)
testCoreTemplate(t, config, fixtureDir("build-basic.json"))
......
{
"variables": {
"var": "{{env `PACKER_TEST_ENV`}}"
},
"builders": [{
"type": "test",
"value": "{{user `var`}}"
}]
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment