From 7878f0c514fe68bc4587aaf86d424c62213460af Mon Sep 17 00:00:00 2001 From: Tonis Tiigi Date: Thu, 4 Feb 2021 23:27:09 -0800 Subject: [PATCH] bake: allow variables in user functions Signed-off-by: Tonis Tiigi --- bake/hcl.go | 19 ++++++++++--------- bake/hcl_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 9 deletions(-) diff --git a/bake/hcl.go b/bake/hcl.go index 704d244fb7ad..dbca9ce7ed02 100644 --- a/bake/hcl.go +++ b/bake/hcl.go @@ -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. @@ -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) diff --git a/bake/hcl_test.go b/bake/hcl_test.go index 6cb53ea392c6..ebe74bb630f7 100644 --- a/bake/hcl_test.go +++ b/bake/hcl_test.go @@ -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) + }) }