Skip to content

Commit

Permalink
Merge pull request #532 from tonistiigi/vars-in-func
Browse files Browse the repository at this point in the history
bake: allow variables in user functions
  • Loading branch information
tonistiigi authored Feb 10, 2021
2 parents b77690a + 7878f0c commit ad95d6b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 9 deletions.
19 changes: 10 additions & 9 deletions bake/hcl.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,15 +167,6 @@ func parseHCL(dt []byte, fn string) (_ *Config, err error) {
}
}

userFunctions, _, diags := userfunc.DecodeUserFunctions(file.Body, "function", func() *hcl.EvalContext {
return &hcl.EvalContext{
Functions: stdlibFunctions,
}
})
if diags.HasErrors() {
return nil, diags
}

var sc staticConfig

// Decode only variable blocks without interpolation.
Expand All @@ -189,6 +180,16 @@ func parseHCL(dt []byte, fn string) (_ *Config, err error) {
variables[variable.Name] = cty.StringVal(variable.Default)
}

userFunctions, _, diags := userfunc.DecodeUserFunctions(file.Body, "function", func() *hcl.EvalContext {
return &hcl.EvalContext{
Functions: stdlibFunctions,
Variables: variables,
}
})
if diags.HasErrors() {
return nil, diags
}

// Override default with values from environment.
for _, env := range os.Environ() {
parts := strings.SplitN(env, "=", 2)
Expand Down
32 changes: 32 additions & 0 deletions bake/hcl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,4 +250,36 @@ func TestParseHCL(t *testing.T) {
require.Error(t, err)
require.Contains(t, err.Error(), "docker-bake.hcl:7,17-37: Variables not allowed; Variables may not be used here.")
})

t.Run("WithVariablesInFunctions", func(t *testing.T) {
dt := []byte(`
variable "REPO" {
default = "user/repo"
}
function "tag" {
params = [tag]
result = ["${REPO}:${tag}"]
}
target "webapp" {
tags = tag("v1")
}
`)

c, err := ParseHCL(dt, "docker-bake.hcl")
require.NoError(t, err)

require.Equal(t, 1, len(c.Targets))
require.Equal(t, c.Targets[0].Name, "webapp")
require.Equal(t, []string{"user/repo:v1"}, c.Targets[0].Tags)

os.Setenv("REPO", "docker/buildx")

c, err = ParseHCL(dt, "docker-bake.hcl")
require.NoError(t, err)

require.Equal(t, 1, len(c.Targets))
require.Equal(t, c.Targets[0].Name, "webapp")
require.Equal(t, []string{"docker/buildx:v1"}, c.Targets[0].Tags)
})
}

0 comments on commit ad95d6b

Please sign in to comment.