Fixes two template builder bugs that caused AWS EC2 (Linux) template
imports to fail:
1. **Missing directory entries in tar archive**: `BundleTar` wrote
static files with nested paths (e.g.
`cloud-init/cloud-config.yaml.tftpl`) without emitting `TypeDir` entries
for parent directories. The provisioner's archive extractor requires
explicit directory entries and failed with "no such file or directory".
2. **Incorrect agent reference for counted resources**:
`ExtractAgentResourceName` returned `dev` for the AWS Linux base
template, but the agent uses `count =
data.coder_workspace.me.start_count`, so module templates need
`coder_agent.dev[0].id`. The function now detects `count`/`for_each` and
appends `[0]`.
> [!NOTE]
> Generated by Coder Agents (on behalf of @jeremyruppel)
Extract validation helpers to a dedicated file, add static file bundling
for base templates, and add Windows OS support.
**Commit 1: Extract validation to `validate.go`**
Move `validateVariableValue`, `validateStringValue`,
`validateNumberValue`, `validateBoolValue`, `toHCLLiteral`, `hclQuote`,
and `isSimpleJSONValue` from `compose.go` into `validate.go`.
Corresponding tests move to `validate_internal_test.go`. This keeps
`compose.go` focused on the compose pipeline.
**Commit 2: Static file bundling**
Add `StaticFiles` field to `ComposeResult` and a `collectStaticFiles`
helper that walks the base template FS to collect non-template files
(e.g. cloud-init `.tftpl` inputs). `BundleTar` now writes these files
into the output archive in sorted order for deterministic output. This
fixes `aws-linux`, whose cloud-init files were embedded but never
included in the tar.
**Commit 3: Windows OS support**
Add `BaseOSWindows` constant and register `"windows"` in `validBaseOS`
so that base templates with `os="windows"` can be loaded and used for
module compatibility filtering.
> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.
Surface base template prerequisites to admins before they create a
template in the Template Builder wizard.
Today, template prerequisites (Docker socket setup, Kubernetes auth, AWS
IAM policies) are only visible in the registry README after import.
Admins hit opaque provisioner errors and have to hunt for docs. This
change extracts the prerequisites from the README and serves them via
the API so the frontend can display them inline.
## How it works
Each base template README uses HTML comment markers (`<!--
prerequisites:start -->` / `<!-- prerequisites:end -->`) to delimit the
prerequisites section. At boot time, the base catalog loader reads the
README, extracts the content between markers via `strings.Index`, and
caches both the full README and the prerequisites string.
The prerequisites are served via a new `prerequisites` field on `GET
/api/v2/templatebuilder/bases`. The full README is included in the
composed template tar bundle and stored as the template version readme.
## Changes
- Add `README.md` with prerequisite markers to
`coderd/templatebuilder/bases/{docker,kubernetes,aws-linux}/`
- New `ExtractPrerequisites()` in `prerequisites.go` using literal
string matching
- `bases.go`: load README at boot, fail loudly if missing, extract
prerequisites
- `compose.go`: include README in `ComposeResult` and tar bundle
- `codersdk`: add `Prerequisites` field to `TemplateBuilderBase`
- Handler: populate prerequisites in bases response, set readme on
template version
<details>
<summary>Implementation notes</summary>
- Prerequisites extraction uses `strings.Index` for exact literal marker
matching; no regex or AST parser needed since we control the markers.
- YAML frontmatter is deliberately retained in the stored README. The
frontend `TemplateDocsPage` already strips it at render time via
`front-matter`.
- The prerequisite markers are HTML comments, invisible in rendered
markdown.
- The `RejectsMissingReadme` test enforces that every base template must
include a README.
- AWS Linux prerequisites span two H2 sections (`## Prerequisites` and
`## Required permissions / policy`), which is why heading-based parsing
was rejected in favor of explicit markers.
*Generated with the assistance of an AI coding agent. Reviewed by
@jeremyruppel.*
</details>
Relates to https://linear.app/codercom/issue/DEVEX-446
Part of the Template Builder wizard PR stack.
## Problem
The kubernetes base template used Terraform `variable` blocks and
`var.*` references for `use_kubeconfig` and `namespace`, but the
composed tar bundle never included a `.tfvars` file. This caused
`terraform plan` to fail with "required template variables need values:
namespace".
## Fix
Base templates now use Go template variables (`{{ .Variables.* }}`) just
like module templates do. Values are validated, HCL-quoted, and rendered
directly into the output HCL.
Also adds explicit "variable is required" validation to both
`mergeBaseVariables` and `mergeModuleVariables`, replacing the previous
reliance on `missingkey=error` at render time for clearer error
messages.
---
> [!NOTE]
> Generated by Coder Agents on behalf of @jeremyruppel
Part of the Template Builder wizard PR stack.
## Backend fixes
1. **Registry URL scheme fix**: Default
`CODER_TEMPLATE_BUILDER_REGISTRY_URL` was `https://registry.coder.com`
but Terraform module registry addresses must be scheme-less. Changed to
`registry.coder.com`.
2. **Sensitive variable defaults**: Module `.tf.tmpl` files for
claude-code, aider, amazon-q had sensitive `variable` blocks without
`default`, causing `terraform plan` to fail during template import. Also
fixed the `templatebuildermodulegen` script.
3. **Auto-quote string variables**: The backend now accepts raw string
values from callers and wraps them in HCL quotes automatically.
Previously callers were required to send pre-quoted HCL literals, which
is not a reasonable API contract.
---
> [!NOTE]
> Generated by Coder Agents on behalf of @jeremyruppel
Adds `POST /api/v2/templatebuilder/compose/template`, a synchronous
endpoint that composes a template from a base and modules, validates it
via a provisioner import job, and creates the template in a single
request.
The handler composes terraform files, bundles them as a tar, inserts the
file with hash-based dedup, creates a template version with an import
job, waits up to 2 minutes for the job to complete, classifies errors
for known failure modes (network-unreachable registry, DNS failures),
then creates the template on success. Canceled and failed jobs return
appropriate error responses.
Also adds `hclwrite.Format` to composed terraform output for canonical
HCL formatting.
Closes https://linear.app/codercom/issue/DEVEX-279
<details>
<summary>Implementation notes</summary>
- SDK types and client method in `codersdk/templatebuilder.go` with
validation tags matching the standard template creation path
(`template_display_name`, `lt=128`)
- `ClassifyProvisionerError` in `coderd/templatebuilder/errors.go`
detects DNS, connection refused, i/o timeout, and TLS handshake failures
and returns actionable messages
- `waitForProvisionerJob` polls with a ramp-up interval schedule (100ms,
200ms, 500ms, then 1s steady) and accepts an `onUpdate` callback for
future SSE streaming
- Audit logging for both template and template version creation
- TOCTOU name uniqueness: early check for fast feedback, DB unique
constraint catch for the race window (returns 409, not 500)
- Swagger annotations for all error responses (400, 404, 409, 504)
</details>
> 🤖 Generated by Coder Agents
Validates caller-supplied module variable keys and values in the
template builder compose endpoint before template rendering. Previously,
`mergeModuleVariables` accepted any caller-supplied key and value
without validation, allowing unknown keys, computed/sensitive variable
overrides, and malformed HCL literals (including injection payloads) to
pass through to rendered output.
Now `mergeModuleVariables` rejects unknown keys (those not in the
manifest's non-computed, non-sensitive variables) and type-checks
values: strings must be quoted HCL literals without interpolation
markers or unescaped newlines, numbers must be strict numeric literals,
and bools must be exactly `true` or `false`. The literal `null` is
accepted for any type.
Closes https://linear.app/codercom/issue/DEVEX-278
<details>
<summary>Implementation details</summary>
- Changed `mergeModuleVariables` signature from `map[string]string` to
`(map[string]string, error)` to surface validation failures
- Added `validateVariableValue`, `validateStringValue`,
`validateNumberValue`, `validateBoolValue` in `compose.go`
- String validation rejects: unquoted values, HCL interpolation (`${`,
`%{`), unescaped newlines/quotes, trailing backslashes (which would
escape the closing delimiter), and values exceeding 4096 bytes
- Errors wrap the module ID and variable name for clear diagnostics
(e.g. `module "code-server": variable "port": invalid number value`)
- Tests cover key validation, type validation, injection attempts, and
full Compose flow integration
> Generated with the help of [Coder Agents](https://coder.com) by
@jeremyruppel
</details>
> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.
Part 2 of DEVEX-277 (POST /api/v2/templatebuilder/compose).
Adds the core composition and bundling logic for the template builder.
`Compose` renders a base template and selected modules into Terraform source files. It validates modules before rendering (rejects duplicates, ConflictsWith violations, unknown IDs, OS incompatibility), then for each module merges manifest defaults with caller-supplied variable overrides and renders the module template.
`mergeModuleVariables` fills in defaults for non-computed, non-sensitive variables from the manifest (with basic JSON type validation via `isSimpleJSONValue`), uses `null` for non-required variables without defaults, and leaves required variables absent so `missingkey=error` catches omissions at render time.
`BundleTar` packages the result into a tar archive with reproducible timestamps. Writes `main.tf` always, `modules.tf` only when modules are present.
Conflict detection is bidirectional so module ordering in the request does not affect validation.