Skip to content

Commit

Permalink
fix: add error detail for duplicate agent metadata key (#172)
Browse files Browse the repository at this point in the history
* fix: add error detail for duplicate agent metadata key

* Update provider/agent.go

Co-authored-by: Mathias Fredriksson <mafredri@gmail.com>

---------

Co-authored-by: Mathias Fredriksson <mafredri@gmail.com>
  • Loading branch information
Kira-Pilot and mafredri committed Nov 22, 2023
1 parent 0040c1d commit 7d258c1
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
14 changes: 14 additions & 0 deletions provider/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"golang.org/x/xerrors"
)

func agentResource() *schema.Resource {
Expand Down Expand Up @@ -38,6 +39,19 @@ func agentResource() *schema.Resource {
return diag.FromErr(err)
}
}

rawPlan := resourceData.GetRawPlan()
items := rawPlan.GetAttr("metadata").AsValueSlice()
itemKeys := map[string]struct{}{}
for _, item := range items {
key := valueAsString(item.GetAttr("key"))
_, exists := itemKeys[key]
if exists {
return diag.FromErr(xerrors.Errorf("duplicate agent metadata key %q", key))
}
itemKeys[key] = struct{}{}
}

return updateInitScript(resourceData, i)
},
ReadWithoutTimeout: func(ctx context.Context, resourceData *schema.ResourceData, i interface{}) diag.Diagnostics {
Expand Down
36 changes: 36 additions & 0 deletions provider/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,42 @@ func TestAgent_Metadata(t *testing.T) {
})
}

func TestAgent_MetadataDuplicateKeys(t *testing.T) {
t.Parallel()
resource.Test(t, resource.TestCase{
Providers: map[string]*schema.Provider{
"coder": provider.New(),
},
IsUnitTest: true,
Steps: []resource.TestStep{{
Config: `
provider "coder" {
url = "https://example.com"
}
resource "coder_agent" "dev" {
os = "linux"
arch = "amd64"
metadata {
key = "process_count"
display_name = "Process Count"
script = "ps aux | wc -l"
interval = 5
timeout = 1
}
metadata {
key = "process_count"
display_name = "Process Count"
script = "ps aux | wc -l"
interval = 5
timeout = 1
}
}
`,
ExpectError: regexp.MustCompile("duplicate agent metadata key"),
}},
})
}

func TestAgent_DisplayApps(t *testing.T) {
t.Parallel()
t.Run("OK", func(t *testing.T) {
Expand Down

0 comments on commit 7d258c1

Please sign in to comment.