Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit eb0c94a

Browse files
committedJul 19, 2024·
feat: add coderd_template resource
1 parent 2fca026 commit eb0c94a

File tree

13 files changed

+727
-1
lines changed

13 files changed

+727
-1
lines changed
 

‎docs/resources/template.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
---
2+
# generated by https://github.com/hashicorp/terraform-plugin-docs
3+
page_title: "coderd_template Resource - coderd"
4+
subcategory: ""
5+
description: |-
6+
A Coder template
7+
---
8+
9+
# coderd_template (Resource)
10+
11+
A Coder template
12+
13+
14+
15+
<!-- schema generated by tfplugindocs -->
16+
## Schema
17+
18+
### Required
19+
20+
- `name` (String) The name of the template.
21+
22+
### Optional
23+
24+
- `description` (String) A description of the template.
25+
- `display_name` (String) The display name of the template. Defaults to the template name.
26+
- `organization_id` (String) The ID of the organization. Defaults to the provider's default organization
27+
- `version` (Block List) (see [below for nested schema](#nestedblock--version))
28+
29+
### Read-Only
30+
31+
- `id` (String) The ID of the template.
32+
33+
<a id="nestedblock--version"></a>
34+
### Nested Schema for `version`
35+
36+
Required:
37+
38+
- `directory` (String) A path to the directory to create the template version from. Changes in the directory contents will trigger the creation of a new template version.
39+
40+
Optional:
41+
42+
- `active` (Boolean) Whether this version is the active version of the template. Only one version can be active at a time.
43+
- `message` (String) A message describing the changes in this version of the template. Messages longer than 72 characters will be truncated..
44+
- `name` (String) The name of the template version. Automatically generated if not provided.
45+
46+
Read-Only:
47+
48+
- `directory_hash` (String)

‎go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ require (
120120
github.com/secure-systems-lab/go-securesystemslib v0.7.0 // indirect
121121
github.com/shopspring/decimal v1.3.1 // indirect
122122
github.com/spaolacci/murmur3 v1.1.0 // indirect
123+
github.com/spf13/afero v1.11.0 // indirect
123124
github.com/spf13/cast v1.6.0 // indirect
124125
github.com/spf13/pflag v1.0.5 // indirect
125126
github.com/tinylib/msgp v1.1.8 // indirect

‎go.sum

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
cdr.dev/slog v1.6.2-0.20240126064726-20367d4aede6 h1:KHblWIE/KHOwQ6lEbMZt6YpcGve2FEZ1sDtrW1Am5UI=
22
cdr.dev/slog v1.6.2-0.20240126064726-20367d4aede6/go.mod h1:NaoTA7KwopCrnaSb0JXTC0PTp/O/Y83Lndnq0OEV3ZQ=
3-
cloud.google.com/go v0.110.7 h1:rJyC7nWRg2jWGZ4wSJ5nY65GTdYJkg0cd/uXb+ACI6o=
3+
cloud.google.com/go v0.110.10 h1:LXy9GEO+timppncPIAZoOj3l58LIU9k+kn48AN7IO3Y=
44
cloud.google.com/go/compute v1.25.1 h1:ZRpHJedLtTpKgr3RV1Fx23NuaAEN1Zfx9hw1u4aJdjU=
55
cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc=
66
cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=
@@ -132,6 +132,8 @@ github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
132132
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
133133
github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk=
134134
github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
135+
github.com/go-chi/render v1.0.1 h1:4/5tis2cKaNdnv9zFLfXzcquC9HbeZgCnxGnKrltBS8=
136+
github.com/go-chi/render v1.0.1/go.mod h1:pq4Rr7HbnsdaeHagklXub+p6Wd16Af5l9koip1OvJns=
135137
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=
136138
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic=
137139
github.com/go-git/go-billy/v5 v5.5.0 h1:yEY4yhzCDuMGSv83oGxiBotRzhwhNr8VZyphhiu+mTU=
@@ -388,6 +390,8 @@ github.com/skeema/knownhosts v1.2.2 h1:Iug2P4fLmDw9f41PB6thxUkNUkJzB5i+1/exaj40L
388390
github.com/skeema/knownhosts v1.2.2/go.mod h1:xYbVRSPxqBZFrdmDyMmsOs+uX1UZC3nTN3ThzgDxUwo=
389391
github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI=
390392
github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
393+
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
394+
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
391395
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
392396
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
393397
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=

‎integration/integration_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,11 @@ func TestIntegration(t *testing.T) {
101101
assert.Equal(t, group.QuotaAllowance, 100)
102102
},
103103
},
104+
{
105+
name: "template-test",
106+
preF: func(t testing.TB, c *codersdk.Client) {},
107+
assertF: func(t testing.TB, c *codersdk.Client) {},
108+
},
104109
} {
105110
t.Run(tt.name, func(t *testing.T) {
106111
client := StartCoder(ctx, t, tt.name, true)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
a
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
variable "name" {
2+
type = string
3+
}
4+
5+
resource "local_file" "a" {
6+
filename = "${path.module}/a.txt"
7+
content = "hello ${var.name}"
8+
}
9+
10+
output "a" {
11+
value = local_file.a.content
12+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
name = "world"

‎integration/template-test/main.tf

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
terraform {
2+
required_providers {
3+
coderd = {
4+
source = "coder/coderd"
5+
version = ">=0.0.0"
6+
}
7+
}
8+
}
9+
10+
resource "coderd_template" "sample" {
11+
name = "example-template"
12+
versions = [
13+
{
14+
name = "v1"
15+
directory = "./example-template"
16+
}
17+
]
18+
}

‎internal/provider/logger.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package provider
2+
3+
import (
4+
"context"
5+
6+
"cdr.dev/slog"
7+
"github.com/hashicorp/terraform-plugin-log/tflog"
8+
)
9+
10+
var _ slog.Sink = &tfLogSink{}
11+
12+
type tfLogSink struct {
13+
tfCtx context.Context
14+
}
15+
16+
func newTFLogSink(tfCtx context.Context) *tfLogSink {
17+
return &tfLogSink{
18+
tfCtx: tfCtx,
19+
}
20+
}
21+
22+
func (s *tfLogSink) LogEntry(ctx context.Context, e slog.SinkEntry) {
23+
var logFn func(ctx context.Context, msg string, additionalFields ...map[string]interface{})
24+
switch e.Level {
25+
case slog.LevelDebug:
26+
logFn = tflog.Debug
27+
case slog.LevelInfo:
28+
logFn = tflog.Info
29+
case slog.LevelWarn:
30+
logFn = tflog.Warn
31+
default:
32+
logFn = tflog.Error
33+
}
34+
logFn(s.tfCtx, e.Message, mapToFields(e.Fields))
35+
}
36+
37+
func (s *tfLogSink) Sync() {}
38+
39+
func mapToFields(m slog.Map) map[string]interface{} {
40+
fields := make(map[string]interface{}, len(m))
41+
for _, v := range m {
42+
fields[v.Name] = v.Value
43+
}
44+
return fields
45+
}

‎internal/provider/provider.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ func (p *CoderdProvider) Resources(ctx context.Context) []func() resource.Resour
123123
return []func() resource.Resource{
124124
NewUserResource,
125125
NewGroupResource,
126+
NewTemplateResource,
126127
}
127128
}
128129

‎internal/provider/template_resource.go

Lines changed: 433 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
package provider
2+
3+
import (
4+
"context"
5+
"regexp"
6+
"strings"
7+
"testing"
8+
"text/template"
9+
10+
"github.com/coder/terraform-provider-coderd/integration"
11+
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
12+
"github.com/stretchr/testify/require"
13+
)
14+
15+
func TestAccTemplateResource(t *testing.T) {
16+
ctx := context.Background()
17+
client := integration.StartCoder(ctx, t, "group_acc", false)
18+
cfg := testAccTemplateResourceConfig{
19+
URL: client.URL.String(),
20+
Token: client.SessionToken(),
21+
Name: PtrTo("example-template"),
22+
Versions: []testAccTemplateVersionConfig{
23+
{
24+
Name: PtrTo("main"),
25+
Directory: PtrTo("../../integration/template-test/example-template/"),
26+
Variables: []testAccTemplateVariableConfig{
27+
{
28+
Name: PtrTo("var1"),
29+
Value: PtrTo("value1"),
30+
},
31+
},
32+
},
33+
},
34+
}
35+
resource.Test(t, resource.TestCase{
36+
IsUnitTest: true,
37+
PreCheck: func() { testAccPreCheck(t) },
38+
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
39+
Steps: []resource.TestStep{
40+
{
41+
Config: cfg.String(t),
42+
Check: resource.ComposeTestCheckFunc(
43+
resource.TestCheckResourceAttr("coderd_template.test", "name", "example-template"),
44+
resource.TestCheckResourceAttrSet("coderd_template.test", "id"),
45+
resource.TestMatchTypeSetElemNestedAttrs("coderd_template.test", "versions.*", map[string]*regexp.Regexp{
46+
"name": regexp.MustCompile("main"),
47+
"id": regexp.MustCompile(".*"),
48+
}),
49+
),
50+
},
51+
},
52+
})
53+
}
54+
55+
type testAccTemplateResourceConfig struct {
56+
URL string
57+
Token string
58+
59+
Name *string
60+
DisplayName *string
61+
Description *string
62+
OrganizationID *string
63+
Versions []testAccTemplateVersionConfig
64+
}
65+
66+
func (c testAccTemplateResourceConfig) String(t *testing.T) string {
67+
t.Helper()
68+
tpl := `
69+
provider coderd {
70+
url = "{{.URL}}"
71+
token = "{{.Token}}"
72+
}
73+
74+
resource "coderd_template" "test" {
75+
name = {{orNull .Name}}
76+
display_name = {{orNull .DisplayName}}
77+
description = {{orNull .Description}}
78+
organization_id = {{orNull .OrganizationID}}
79+
80+
versions = [
81+
{{- range .Versions }}
82+
{
83+
name = {{orNull .Name}}
84+
directory = {{orNull .Directory}}
85+
active = {{orNull .Active}}
86+
87+
var = [
88+
{{- range .Variables }}
89+
{
90+
name = {{orNull .Name}}
91+
value = {{orNull .Value}}
92+
},
93+
{{- end}}
94+
]
95+
96+
},
97+
{{- end}}
98+
]
99+
}
100+
`
101+
102+
funcMap := template.FuncMap{
103+
"orNull": PrintOrNull,
104+
}
105+
106+
buf := strings.Builder{}
107+
tmpl, err := template.New("test").Funcs(funcMap).Parse(tpl)
108+
require.NoError(t, err)
109+
110+
err = tmpl.Execute(&buf, c)
111+
require.NoError(t, err)
112+
113+
return buf.String()
114+
}
115+
116+
type testAccTemplateVersionConfig struct {
117+
Name *string
118+
Message *string
119+
Directory *string
120+
Active *bool
121+
Variables []testAccTemplateVariableConfig
122+
}
123+
124+
type testAccTemplateVariableConfig struct {
125+
Name *string
126+
Value *string
127+
}

‎internal/provider/util.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
package provider
22

33
import (
4+
"crypto/sha256"
5+
"encoding/hex"
46
"fmt"
7+
"os"
8+
"path/filepath"
59
)
610

711
func PtrTo[T any](v T) *T {
@@ -46,3 +50,29 @@ func PrintOrNull(v any) string {
4650
panic(fmt.Errorf("unknown type in template: %T", value))
4751
}
4852
}
53+
54+
func computeDirectoryHash(directory string) (string, error) {
55+
var files []string
56+
err := filepath.Walk(directory, func(path string, info os.FileInfo, err error) error {
57+
if err != nil {
58+
return err
59+
}
60+
if !info.IsDir() {
61+
files = append(files, path)
62+
}
63+
return nil
64+
})
65+
if err != nil {
66+
return "", err
67+
}
68+
69+
hash := sha256.New()
70+
for _, file := range files {
71+
data, err := os.ReadFile(file)
72+
if err != nil {
73+
return "", err
74+
}
75+
hash.Write(data)
76+
}
77+
return hex.EncodeToString(hash.Sum(nil)), nil
78+
}

0 commit comments

Comments
 (0)
Please sign in to comment.