Skip to content

feat: Add "coder_metadata" resource #34

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

Merged
merged 8 commits into from
Aug 1, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
129 changes: 129 additions & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ package provider

import (
"context"
"errors"
"fmt"
"net/url"
"os"
"reflect"
"strings"

"github.com/google/uuid"
"github.com/hashicorp/go-cty/cty"
"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"
Expand Down Expand Up @@ -318,6 +320,74 @@ func New() *schema.Provider {
},
},
},
"coder_metadata": {
Description: "Use this resource to attach key/value pairs to a resource. They will be " +
"displayed in the Coder dashboard.",
CreateContext: func(c context.Context, resourceData *schema.ResourceData, i interface{}) diag.Diagnostics {
resourceData.SetId(uuid.NewString())

pairs, err := populateIsNull(resourceData)
if err != nil {
return errorAsDiagnostics(err)
}
err = resourceData.Set("pair", pairs)
if err != nil {
return errorAsDiagnostics(err)
}

return nil
},
ReadContext: func(c context.Context, resourceData *schema.ResourceData, i interface{}) diag.Diagnostics {
return nil
},
DeleteContext: func(ctx context.Context, rd *schema.ResourceData, i interface{}) diag.Diagnostics {
return nil
},
Schema: map[string]*schema.Schema{
"resource_id": {
Type: schema.TypeString,
Description: "The \"id\" property of another resource that metadata should be attached to.",
ForceNew: true,
Required: true,
},
"pair": {
Type: schema.TypeList,
ForceNew: true,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Description: "The key of this metadata item.",
ForceNew: true,
Required: true,
},
"value": {
Type: schema.TypeString,
Description: "The value of this metadata item.",
ForceNew: true,
Optional: true,
},
"sensitive": {
Type: schema.TypeBool,
Description: "Set to \"true\" to for items such as API keys whose values should be " +
"hidden from view by default. Note that this does not prevent metadata from " +
"being retrieved using the API, so it is not suitable for secrets that should " +
"not be exposed to workspace users.",
ForceNew: true,
Optional: true,
Default: false,
},
"is_null": {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would we just assume an empty string is null? Maybe that's too lossy?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possibly! I implemented it this way because the original ticket asked for null support, and I figured somebody who's used to Terraform's semantics wouldn't necessarily be expecting us to conflate null and "" the way Go does. But if we're OK with that behavior, I definitely wouldn't mind getting rid of this hack.

Type: schema.TypeBool,
ForceNew: true,
Computed: true,
},
},
},
},
},
},
},
}
}
Expand Down Expand Up @@ -356,3 +426,62 @@ func updateInitScript(resourceData *schema.ResourceData, i interface{}) diag.Dia
}
return nil
}

// populateIsNull reads the raw plan for a coder_metadata resource being created,
// figures out which items have null "value"s, and augments them by setting the
// "is_null" field to true. This ugly hack is necessary because terraform-plugin-sdk
// is designed around a old version of Terraform that didn't support nullable fields,
// and it doesn't correctly propagate null values for primitive types.
// Returns an interface{} representing the new value of the "pair" field, or an error.
func populateIsNull(resourceData *schema.ResourceData) (result interface{}, err error) {
// The cty package reports type mismatches by panicking
defer func() {
if r := recover(); r != nil {
err = errors.New(fmt.Sprintf("panic while handling coder_metadata: %#v", r))
}
}()

rawPlan := resourceData.GetRawPlan()
pairs := rawPlan.GetAttr("pair").AsValueSlice()

var resultPairs []interface{}
for _, pair := range pairs {
resultPair := map[string]interface{}{
"key": valueAsString(pair.GetAttr("key")),
"value": valueAsString(pair.GetAttr("value")),
"sensitive": valueAsBool(pair.GetAttr("sensitive")),
}
if pair.GetAttr("value").IsNull() {
resultPair["is_null"] = true
}
resultPairs = append(resultPairs, resultPair)
}

return resultPairs, nil
}

// valueAsString takes a cty.Value that may be a string or null, and converts it to either a Go string
// or a nil interface{}
func valueAsString(value cty.Value) interface{} {
if value.IsNull() {
return ""
}
return value.AsString()
}

// valueAsString takes a cty.Value that may be a boolean or null, and converts it to either a Go bool
// or a nil interface{}
func valueAsBool(value cty.Value) interface{} {
if value.IsNull() {
return nil
}
return value.True()
}

// errorAsDiagnostic transforms a Go error to a diag.Diagnostics object representing a fatal error.
func errorAsDiagnostics(err error) diag.Diagnostics {
return []diag.Diagnostic{{
Severity: diag.Error,
Summary: err.Error(),
}}
}
76 changes: 76 additions & 0 deletions internal/provider/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,3 +186,79 @@ func TestApp(t *testing.T) {
}},
})
}

func TestMetadata(t *testing.T) {
t.Parallel()
prov := provider.New()
resource.Test(t, resource.TestCase{
Providers: map[string]*schema.Provider{
"coder": prov,
},
IsUnitTest: true,
Steps: []resource.TestStep{{
Config: `
provider "coder" {
}
resource "coder_agent" "dev" {
os = "linux"
arch = "amd64"
}
resource "coder_metadata" "agent" {
resource_id = coder_agent.dev.id
pair {
key = "foo"
value = "bar"
}
pair {
key = "secret"
value = "squirrel"
sensitive = true
}
pair {
key = "implicit_null"
}
pair {
key = "explicit_null"
value = null
}
pair {
key = "empty"
value = ""
}
}
`,
Check: func(state *terraform.State) error {
require.Len(t, state.Modules, 1)
require.Len(t, state.Modules[0].Resources, 2)
agent := state.Modules[0].Resources["coder_agent.dev"]
require.NotNil(t, agent)
metadata := state.Modules[0].Resources["coder_metadata.agent"]
require.NotNil(t, metadata)
t.Logf("metadata attributes: %#v", metadata.Primary.Attributes)
for key, expected := range map[string]string{
"resource_id": agent.Primary.Attributes["id"],
"pair.#": "5",
"pair.0.key": "foo",
"pair.0.value": "bar",
"pair.0.sensitive": "false",
"pair.1.key": "secret",
"pair.1.value": "squirrel",
"pair.1.sensitive": "true",
"pair.2.key": "implicit_null",
"pair.2.is_null": "true",
"pair.2.sensitive": "false",
"pair.3.key": "explicit_null",
"pair.3.is_null": "true",
"pair.3.sensitive": "false",
"pair.4.key": "empty",
"pair.4.value": "",
"pair.4.is_null": "false",
"pair.4.sensitive": "false",
} {
require.Equal(t, expected, metadata.Primary.Attributes[key])
}
return nil
},
}},
})
}