Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bake: allow variables in user functions #532

Merged
merged 1 commit into from
Feb 10, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions bake/hcl.go
Original file line number Diff line number Diff line change
@@ -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)
32 changes: 32 additions & 0 deletions bake/hcl_test.go
Original file line number Diff line number Diff line change
@@ -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)
})
}