From d83da633203e771e07bb0662854462534f3082d7 Mon Sep 17 00:00:00 2001 From: Justin Chadwell Date: Thu, 2 Nov 2023 17:47:16 +0000 Subject: [PATCH] bake: fix global target access when using a matrix Previously, we would fail while trying to use the global "target" field when using a matrix. The contents of the matrix really don't matter for this. What was happening was that we would copy the "target" property into the child evaluation context, so that when it was updated on the parent, it wouldn't propagate to the child. The correct behavior here is to avoid copying variables from the target evaluation context if it is the root. Signed-off-by: Justin Chadwell --- bake/bake.go | 6 ++++-- bake/hcl_test.go | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/bake/bake.go b/bake/bake.go index 84df59bb..4b069402 100644 --- a/bake/bake.go +++ b/bake/bake.go @@ -949,8 +949,10 @@ func (t *Target) GetEvalContexts(ectx *hcl.EvalContext, block *hcl.Block, loadDe for _, e := range ectxs { e2 := ectx.NewChild() e2.Variables = make(map[string]cty.Value) - for k, v := range e.Variables { - e2.Variables[k] = v + if e != ectx { + for k, v := range e.Variables { + e2.Variables[k] = v + } } e2.Variables[k] = v ectxs2 = append(ectxs2, e2) diff --git a/bake/hcl_test.go b/bake/hcl_test.go index 005b4785..31abc43e 100644 --- a/bake/hcl_test.go +++ b/bake/hcl_test.go @@ -1113,6 +1113,27 @@ func TestHCLMatrixBadTypes(t *testing.T) { require.Error(t, err) } +func TestHCLMatrixWithGlobalTarget(t *testing.T) { + dt := []byte(` + target "x" { + tags = ["a", "b"] + } + + target "default" { + tags = target.x.tags + matrix = { + dummy = [""] + } + } + `) + c, err := ParseFile(dt, "docker-bake.hcl") + require.NoError(t, err) + require.Equal(t, 2, len(c.Targets)) + require.Equal(t, "x", c.Targets[0].Name) + require.Equal(t, "default", c.Targets[1].Name) + require.Equal(t, []string{"a", "b"}, c.Targets[1].Tags) +} + func TestJSONAttributes(t *testing.T) { dt := []byte(`{"FOO": "abc", "variable": {"BAR": {"default": "def"}}, "target": { "app": { "args": {"v1": "pre-${FOO}-${BAR}"}} } }`)