## Summary Adds the **Coder Quickstart** template as a selectable base in the [template builder](coderd/templatebuilder) guided wizard. It is a Docker-based starter that lets a user pick languages and optionally clone a repo. ## What changed - **New base package** `coderd/templatebuilder/bases/quickstart/`: - `base.json`: `id: "quickstart"`, `display_name: "Coder Quickstart"`, `os: "linux"`. - `main.tf.tmpl`: a Docker workspace with a language selector, a single language-install script, an optional Git clone, and workspace presets. Editors are added via the builder's module step rather than baked into the base. - `install-languages.sh.tftpl` and `README.md` (with prerequisites markers so the builder can extract the prerequisites section). - **Placement**: the bases endpoint returns a plain list sorted by display name (with ID as a deterministic tiebreak). The wizard's base-infra select step prioritizes the Quickstart and Docker starters to the front on the client, mirroring the existing client-side module prioritization in `ModuleSelectStep` (shared `sortByPriority` helper). - **Base/module collision guard**: a base's bundled catalog modules are derived from its rendered Terraform (`ExtractModuleNames`, cached with `sync.OnceValues` and filtered to catalog IDs). `validateModules` seeds its seen-set from that derived set, so a wizard-selected module the base already renders is rejected with a clear error, and the modules endpoint omits it so the wizard never offers a colliding module. The base's Terraform is the single source of truth, so there is no separate manifest list that can drift. ## Testing - `go test ./coderd/` (template builder handler: bases ordering, the `baseSpec` table, the modules-endpoint base filter): pass. - `go test ./coderd/templatebuilder/` (all-bases render/snapshot, the collision guard, `TestBaseIncludedModules`, the selector/install-script drift test): pass. - `gofmt`, `go vet`, `golangci-lint`: clean. - Frontend `tsc`, `biome`, and `knip`: clean. ## Review decisions - **Template scope**: trimmed to infrastructure, a language selector, and an optional Git clone. The IDE selector was removed; editors are added via the builder's module step. - **Placement**: base ordering is presentational, so it lives on the client base-infra select step rather than in the API. - **git-clone in the base**: kept for the build-time clone affordance. The base renders its module source verbatim, so it currently pins the public registry and does not yet honor a deployment's registry mirror; that fix is tracked in DOCS-610 and delivered as a stacked follow-up PR (an in-code note documents the current behavior). - **Container image**: left hardcoded (`codercom/enterprise-base:ubuntu`). The quickstart base is the opinionated path; the Docker base covers custom images. Revisiting a `container_image` variable is tracked in DOCS-611. ## Review updates (@jeremyruppel) - **Ordering moved to the client**: deleted the server-side Quickstart-before-Docker grouping (and its position test); the base-infra select step now prioritizes bases client-side via a shared `sortByPriority` helper, following the `ModuleSelectStep` precedent. The API just returns a stable, name-sorted list. - **Derive included modules from render**: dropped the `included_modules` manifest field and the `IncludedModules` struct field; `BaseIncludedModules` now derives from the rendered base (single source of truth). Removed `TestBaseIncludedModulesMatchRendered` and added a direct `TestBaseIncludedModules`. - **Kept the PR scoped to "add quickstart base"**: reverted `ExtractAgentResourceName`/`ExtractModuleNames` to the pre-`hclsyntax` regex extraction and removed the option/preset HCL extractor family; the selector↔install-script drift test now uses a small regex. The broader templatebuilder HCL migration and the preset-language subset guard are tracked in DOCS-735. - Branch rebased onto `origin/main` (no content changes beyond the above). --- Linear: [DOCS-558](https://linear.app/codercom/issue/DOCS-558/add-coder-quickstart-template-to-template-builder) > This PR was created with AI assistance (Coder Agents).
157 lines
5.4 KiB
Go
157 lines
5.4 KiB
Go
package templatebuilder
|
|
|
|
import (
|
|
"bytes"
|
|
"io/fs"
|
|
"regexp"
|
|
"text/template"
|
|
|
|
"golang.org/x/xerrors"
|
|
)
|
|
|
|
// ImageOption represents a container image choice for base template parameters.
|
|
type ImageOption struct {
|
|
Name string
|
|
Value string
|
|
}
|
|
|
|
// BaseRenderContext is the data passed to base template .tf.tmpl files.
|
|
type BaseRenderContext struct {
|
|
ContainerImage string
|
|
ImageOptions []ImageOption
|
|
Variables map[string]string
|
|
}
|
|
|
|
// ModuleRenderContext is the data passed to module .tf.tmpl files.
|
|
type ModuleRenderContext struct {
|
|
// RegistryBase is the module registry URL from the deployment config
|
|
// (CODER_TEMPLATE_BUILDER_REGISTRY_URL).
|
|
RegistryBase string
|
|
// PinnedVersion is the module version from the catalog manifest.
|
|
PinnedVersion string
|
|
// AgentResourceName is the Terraform resource name of the coder_agent
|
|
// declared in the base template (e.g. "main" or "dev").
|
|
AgentResourceName string
|
|
// Variables maps variable names to their HCL expressions.
|
|
Variables map[string]string
|
|
}
|
|
|
|
// RenderBaseTemplate executes a pre-parsed .tf.tmpl template for the given
|
|
// base, applying the provided render context. Templates are parsed once at
|
|
// first access via sync.OnceValues, so parse errors surface early instead
|
|
// of at render time.
|
|
func RenderBaseTemplate(exampleID, templatePath string, renderCtx BaseRenderContext) ([]byte, error) {
|
|
if renderCtx.Variables == nil {
|
|
renderCtx.Variables = make(map[string]string)
|
|
}
|
|
|
|
bases, err := loadBases()
|
|
if err != nil {
|
|
return nil, xerrors.Errorf("load base catalog: %w", err)
|
|
}
|
|
|
|
base, ok := bases[exampleID]
|
|
if !ok {
|
|
return nil, xerrors.Errorf("unknown base template %q", exampleID)
|
|
}
|
|
|
|
tmpl, ok := base.Templates[templatePath]
|
|
if !ok {
|
|
return nil, xerrors.Errorf("template %s not found in base %q", templatePath, exampleID)
|
|
}
|
|
|
|
var buf bytes.Buffer
|
|
if err := tmpl.Execute(&buf, renderCtx); err != nil {
|
|
return nil, xerrors.Errorf("execute template %s: %w", templatePath, err)
|
|
}
|
|
|
|
return buf.Bytes(), nil
|
|
}
|
|
|
|
// RenderModuleTemplate parses and executes a module .tf.tmpl file from
|
|
// the given filesystem, applying the provided render context.
|
|
func RenderModuleTemplate(fsys fs.FS, templatePath string, renderCtx ModuleRenderContext) ([]byte, error) {
|
|
if renderCtx.Variables == nil {
|
|
renderCtx.Variables = make(map[string]string)
|
|
}
|
|
return renderTemplate(fsys, templatePath, renderCtx)
|
|
}
|
|
|
|
// renderTemplate is the shared implementation for module template rendering.
|
|
// It sets missingkey=error so that references to undefined variable keys fail
|
|
// loudly instead of producing "<no value>".
|
|
func renderTemplate(fsys fs.FS, templatePath string, data any) ([]byte, error) {
|
|
raw, err := fs.ReadFile(fsys, templatePath)
|
|
if err != nil {
|
|
return nil, xerrors.Errorf("read template %s: %w", templatePath, err)
|
|
}
|
|
|
|
tmpl, err := template.New(templatePath).Option("missingkey=error").Parse(string(raw))
|
|
if err != nil {
|
|
return nil, xerrors.Errorf("parse template %s: %w", templatePath, err)
|
|
}
|
|
|
|
var buf bytes.Buffer
|
|
if err := tmpl.Execute(&buf, data); err != nil {
|
|
return nil, xerrors.Errorf("execute template %s: %w", templatePath, err)
|
|
}
|
|
|
|
return buf.Bytes(), nil
|
|
}
|
|
|
|
// agentResourcePattern matches `resource "coder_agent" "<name>"` in HCL.
|
|
var agentResourcePattern = regexp.MustCompile(`resource\s+"coder_agent"\s+"(\w+)"`)
|
|
|
|
// agentCountPattern detects whether a coder_agent block uses count or
|
|
// for_each, which means references to it require an index (e.g. [0]).
|
|
var agentCountPattern = regexp.MustCompile(
|
|
`resource\s+"coder_agent"\s+"\w+"\s*\{[^}]*\b(?:count|for_each)\s*=`,
|
|
)
|
|
|
|
// ExtractAgentResourceName finds the coder_agent resource declaration in
|
|
// rendered HCL and returns the reference form to use in module templates.
|
|
// When the agent uses count or for_each, the returned name includes an
|
|
// index suffix (e.g. "dev[0]") so that module templates can reference it
|
|
// as coder_agent.<name>.id. Returns an error unless exactly one
|
|
// coder_agent resource is found; the builder only supports single-agent
|
|
// templates. The input is expected to be rendered output from our own
|
|
// curated base templates, not arbitrary user HCL.
|
|
func ExtractAgentResourceName(hcl []byte) (string, error) {
|
|
matches := agentResourcePattern.FindAllSubmatch(hcl, -1)
|
|
switch len(matches) {
|
|
case 0:
|
|
return "", xerrors.New("no coder_agent resource found in rendered template")
|
|
case 1:
|
|
name := string(matches[0][1])
|
|
if agentCountPattern.Match(hcl) {
|
|
name += "[0]"
|
|
}
|
|
return name, nil
|
|
default:
|
|
names := make([]string, 0, len(matches))
|
|
for _, m := range matches {
|
|
names = append(names, string(m[1]))
|
|
}
|
|
return "", xerrors.Errorf("expected exactly one coder_agent resource, found %d: %v",
|
|
len(matches), names)
|
|
}
|
|
}
|
|
|
|
// moduleBlockPattern matches a `module "<name>"` block declaration anchored to
|
|
// the start of a line in HCL.
|
|
var moduleBlockPattern = regexp.MustCompile(`(?m)^[ \t]*module[ \t]+"([^"]+)"`)
|
|
|
|
// ExtractModuleNames returns the labels of every module block declared in
|
|
// rendered HCL, in declaration order. Matching is anchored to the start of a
|
|
// line so commented-out references or string literals are ignored. The input
|
|
// is expected to be rendered output from our own curated base templates, not
|
|
// arbitrary user HCL.
|
|
func ExtractModuleNames(hcl []byte) []string {
|
|
matches := moduleBlockPattern.FindAllSubmatch(hcl, -1)
|
|
names := make([]string, 0, len(matches))
|
|
for _, m := range matches {
|
|
names = append(names, string(m[1]))
|
|
}
|
|
return names
|
|
}
|