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

configs: Include context when variable default has nested problem #35465

Merged
merged 1 commit into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
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
8 changes: 6 additions & 2 deletions internal/configs/named_values.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/zclconf/go-cty/cty/convert"

"github.com/hashicorp/terraform/internal/addrs"
"github.com/hashicorp/terraform/internal/tfdiags"
)

// A consistent detail message for all "not a valid identifier" diagnostics.
Expand Down Expand Up @@ -163,8 +164,11 @@ func decodeVariableBlock(block *hcl.Block, override bool) (*Variable, hcl.Diagno
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Invalid default value for variable",
Detail: fmt.Sprintf("This default value is not compatible with the variable's type constraint: %s.", err),
Subject: attr.Expr.Range().Ptr(),
Detail: fmt.Sprintf(
"This default value is not compatible with the variable's type constraint: %s.",
tfdiags.FormatError(err),
),
Subject: attr.Expr.Range().Ptr(),
})
val = cty.DynamicVal
}
Expand Down
50 changes: 50 additions & 0 deletions internal/configs/named_values_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1

package configs

import (
"testing"

"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
)

func TestVariableInvalidDefault(t *testing.T) {
src := `
variable foo {
type = map(object({
foo = bool
}))

default = {
"thingy" = {
foo = "string where bool is expected"
}
}
}
`

hclF, diags := hclsyntax.ParseConfig([]byte(src), "test.tf", hcl.InitialPos)
if diags.HasErrors() {
t.Fatal(diags.Error())
}

_, diags = parseConfigFile(hclF.Body, nil, false, false)
if !diags.HasErrors() {
t.Fatal("unexpected success; want error")
}

for _, diag := range diags {
if diag.Severity != hcl.DiagError {
continue
}
if diag.Summary != "Invalid default value for variable" {
t.Errorf("unexpected diagnostic summary: %q", diag.Summary)
continue
}
if got, want := diag.Detail, `This default value is not compatible with the variable's type constraint: ["thingy"].foo: a bool is required.`; got != want {
t.Errorf("wrong diagnostic detault\ngot: %s\nwant: %s", got, want)
}
}
}
Loading