# How to add a custom generation action to an application model

> Write an @voxgig/model action that emits a Terraform variables file from every service and environment, under an explicit output root, with a byte-identical rerun.

Source: https://voxgig.com/howto/add-a-generation-action-to-a-model

- Audience: platform-team
- Level: intermediate
- Languages: typescript
- Verified: 2026-11-22
- Published: 2026-11-22

## Short answer

Write a CommonJS module that receives (model, build, ctx), declare it under sys: model: action in .model-config/model-config.aontu, and list it in sys.model.order.action after the existing actions. Derive its output root from build.path, write through build.fs, and refuse any path outside that root. Add a field, run voxgig-model, and assert the artifact gained it and a second run is byte identical.

---
## You will need

Node 22 or later, `@voxgig/model` 12.0.2 with its peer `pino` 10.4.0, and an application model in
`.aontu` files. The sample's model has two services, `orders` and `billing`, each with a `var` map,
and two environments, `dev` and `prod`. Its existing action, `services`, writes a Markdown table of
services and ports.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [@voxgig/model actions](https://github.com/voxgig/model/blob/v12.0.2/docs/reference.md#actions) | The artifact spans services, environments and entities held in one model | You write the renderer, its escaping and its write guard yourself | The artifact is about one schema your toolchain already reads |
| [NSwag](https://github.com/RicoSuter/NSwag/wiki/NSwag-Configuration-Document) | A .NET build that already runs `nswag run` from an MSBuild target | Its configuration document has no step for other files, so a second command follows it | You need data that is not in the OpenAPI document |
| [orval](https://orval.dev/docs/reference/configuration/hooks/) | A TypeScript client from one OpenAPI document, with one artifact derived from it | The hook sees the files it wrote, and your script reads the document itself | The artifact needs more than one service's document |
| [Prisma generator](https://www.prisma.io/docs/orm/v7/prisma-schema/overview/generators) | The artifact derives from the database schema, in a project that runs `prisma generate` | It gets the `datamodel`, plus string settings from its own generator block | Services and environments matter to the output |
| [Projen Component](https://projen.io/docs/concepts/components/) | The artifact is project configuration that Projen should own and keep read-only | Projen synthesizes its own bookkeeping files beside yours and replaces a hand-edited file | The repository is not a Projen project |
| [TypeSpec emitter](https://typespec.io/docs/extending-typespec/emitters-basics/) | API definitions in TypeSpec, and an output its standard emitters lack | An emitter is a library against the compiler's type graph and its API | The data lives outside the TypeSpec program |

Voxgig maintains `@voxgig/model`, the tool this page is about; the other five rows belong to other
projects.

Reach is the difference. The action gets the whole unified model, so one file can name every
service's variables and every environment. orval, NSwag, Prisma, and TypeSpec each hand you one
schema, and they plug into toolchains your team may already run. Projen sits between: its
component reads whatever your code loads, and it owns the files it writes.

## Declare the action beside the existing one

Add the action to the config file and set the order explicitly:

```aontu title="model/.model-config/model-config.aontu"
sys: model: action: {
  services: load: 'build/services.cjs'
  tfvars:   load: 'build/tfvars.cjs'
}
# Without this line the actions run in sorted key order.
sys: model: order: action: 'services,tfvars'
```

The action is called with the unified model object, `(build.model, build, ctx)`, in
[`local.ts` at line 74](https://github.com/voxgig/model/blob/v12.0.2/ts/src/producer/local.ts#L74);
it never reads `model.json`. The [config file reference](https://github.com/voxgig/model/blob/v12.0.2/docs/reference.md#the-config-file)
comments its example with "When omitted, every declared action runs in declaration order", but
the run disagrees. On 12.0.2 the order is
`Object.keys` of the action map (lines 28 to 30), and the unified map comes out sorted. A test
declares `tfvars` before `services` and sees `services` run first. The same order turned up in
[Emit TypeScript types and SQL from one application model](/howto/generate-typescript-types-and-sql-from-one-model),
which covers the types, the SQL, and the colored log in CI.

## Write under an explicit output root

The reference's first example writes `out/docs.html`, a path relative to the working directory.
Find the root from `build.path` instead, and send every write through one guard:

```js title="build/output.cjs"
// generated/ beside model/, found from the root model file rather than from
// the working directory, so the run writes to the same place wherever it starts.
function outputRoot(build) {
  return Path.resolve(build.path, '..', '..', 'generated')
}

// Write text to rel under the output root, through build.fs so --dryrun holds.
// Refuses a path that leaves the root, and refuses to replace a file that
// does not carry the generated header, which is how a hand-kept file looks.
function writeGenerated(build, rel, text) {
  if (typeof rel !== 'string' || rel === '' || Path.isAbsolute(rel) || rel.includes('\\')) {
    throw new Error(`output path must be relative to generated/: ${JSON.stringify(rel)}`)
  }
  const root = outputRoot(build)
  const target = Path.resolve(root, rel)
  const inside = Path.relative(root, target)
  if (inside === '' || inside.startsWith('..') || Path.isAbsolute(inside)) {
    throw new Error(`refusing to write outside generated/: ${rel}`)
  }
```

The renderer in `build/tfvars.cjs` sorts services and variables in code-point order, writes
`default = null` for an optional variable and `sensitive = true` for a secret, and refuses a name
that cannot be a Terraform identifier.[^1] Description text goes through an HCL string escape.

## Add a field and run it twice

`demo.mjs` runs `voxgig-model` three times on a scratch copy: as committed, after one line adds
`STRIPE_WEBHOOK_SECRET` to `billing`, and again with nothing changed.

```bash
node demo.mjs
```

```text output
run 1, the model as committed
  generated/ holds: SERVICES.md, terraform/variables.tf
  SERVICES.md: same as the committed file
  terraform/variables.tf: same as the committed file
run 2, STRIPE_WEBHOOK_SECRET added to billing
  SERVICES.md: 1 removed, 1 added
    - | billing | 8081 | ORDERS_URL, STRIPE_API_KEY |
    + | billing | 8081 | ORDERS_URL, STRIPE_API_KEY, STRIPE_WEBHOOK_SECRET |
  terraform/variables.tf: 0 removed, 6 added
    + variable "billing_stripe_webhook_secret" {
    +   type        = string
    +   description = "billing: Signing secret for Stripe webhooks"
    +   sensitive   = true
    + }
    +
run 3, the same model again
  SERVICES.md: byte identical to run 2: true
  terraform/variables.tf: byte identical to run 2: true
```

One field reached both artifacts in the same run. `record.sh` ran `terraform validate` 1.17.2 on
the committed file, which passed.

## Check it worked

Run the suite. It covers the renderer, the escape, the guard, the three runs, `--dryrun`, and the
run order:

```bash
node --test action.test.mjs
```

```text output
1..8
# tests 8
# suites 0
# pass 8
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

The `--dryrun` test leaves `generated/` empty with the guarded action, then swaps in a copy that
writes with `node:fs` and finds `terraform/variables.tf` on disk. The
[command line reference](https://github.com/voxgig/model/blob/v12.0.2/docs/reference.md#command-line-interface)
says a dry run will "redirect all file writes to an in-memory filesystem (nothing touches disk)".
It redirects `build.fs` alone, in [`model.ts` lines 47 to 51](https://github.com/voxgig/model/blob/v12.0.2/ts/src/model.ts#L47-L51).

## Derive the same table in orval and NSwag

A team that generates its SDK with orval adds the step through
[`hooks.afterAllFilesWrite`](https://orval.dev/docs/reference/configuration/hooks/), a command run
after orval writes, with the written paths appended. A team on NSwag has no such key: the
configuration document holds `runtime`, `documentGenerator`, and `codeGenerators`, so the step goes
after `nswag run` in the
[MSBuild target](https://github.com/RicoSuter/NSwag/wiki/NSwag.MSBuild) or the script. Both ran
`compare/env-table.mjs` on the billing document, once, in `record.sh`:

```bash
node compare.mjs
```

```text output
orval 8.48.0, hooks.afterAllFilesWrite running env-table.mjs
  exit 0; orval-out/ holds ENV.md, billing.ts
  variables it could name: BILLING_BASE_URL, BILLING_API_KEY
NSwag 14.8.0, nswag run nswag.json, then env-table.mjs
  exit 0; configuration document keys: runtime, documentGenerator, codeGenerators
  nswag-out/ holds ENV.md, billing.ts; variables it could name: BILLING_BASE_URL, BILLING_API_KEY
Prisma 7.10.1 / 7.10.1, a generator built with generatorHandler
  exit 0; it was handed: allowNoModels, datamodel, datasources, dmmf, generator, otherGenerators, schemaPath, version
  models: Order(id, total, note); generator block config: {"environments":"dev,prod"}
TypeSpec 1.18.0, an emitter's $onEmit
  exit 0; models in the program: Order(id, total, note)
Projen 0.105.7, a Component that reads model/model.json
  wrote .gitattributes, .gitignore, .projen/files.json, .projen/tasks.json, ENV.md; ENV.md has 4 rows, mode 444
  over a hand-written ENV.md: exit 0, first line now | Service | Variable | Secret |
```

Both generators read one service's OpenAPI document, so the table names its base URL and its API
key and nothing about `orders`. Prisma took the environment names only as a string in its own
generator block.

## When it goes wrong

The hand-kept `infra/variables.tf` is gone after a build that exited 0. The action wrote to a path
relative to the working directory. `pitfall.mjs` runs a naive copy of the action and the guarded
one:

```bash
node pitfall.mjs
```

```text output
naive action, run from the project root
  exit 0, infra/variables.tf overwritten, generated/: SERVICES.md
naive action, run from model/
  exit 1, infra/variables.tf kept, generated/: SERVICES.md
  ENOENT: no such file or directory, open 'infra/variables.tf'
guarded action, run from model/
  exit 0, infra/variables.tf kept, generated/: SERVICES.md, terraform/variables.tf
guarded action, -b "{tfvars:'../infra/variables.tf'}"
  exit 1, infra/variables.tf kept, generated/: SERVICES.md
  refusing to write outside generated/: ../infra/variables.tf
guarded action, a hand-kept file at generated/terraform/variables.tf
  exit 1, infra/variables.tf kept, generated/: SERVICES.md, terraform/variables.tf
  refusing to replace a file that was not generated: generated/terraform/variables.tf
```

A failed action still leaves the earlier action's `SERVICES.md`, so read the exit status before
the files.

A description holding `${` becomes a Terraform interpolation. The escape is `$${`, but an escape
written as the replacement string `'$${'` gives back `${`, because `$$` there means one `$`.[^2]
Pass a function to `replace`, as `hcl()` does, and test the escape with a `${` in the input.
`record.sh` ran `terraform validate` on both forms: escaped, it passed; spliced raw, it failed with
`Invalid character`.

## When not to do this

Do not write an action for an artifact your schema tool already owns. If the variables come from
one OpenAPI document and the client comes from orval, the `afterAllFilesWrite` hook does the job in
the toolchain you run, with no model to maintain. The same holds for NSwag inside an MSBuild
target.

Skip `@voxgig/model` when the services are not in one model already. Moving them there to get one
file is the larger project.

Do not let an action take its output path from a build argument without the guard. The page's
guard refuses `..`, an absolute path and a backslash, and it does not resolve symbolic links inside
`generated/`.

Prefer a Projen component when the artifact is project configuration and the team wants it
read-only, since Projen writes `ENV.md` with mode `444` and owns it.

## Related how-tos

- [Split an application model into entity and service files](/howto/split-an-application-model-into-aon-files)

- [Rebuild artifacts on model change with a watch loop](/howto/rebuild-artifacts-on-model-change)

- [Emit TypeScript types and SQL from one application model](/howto/generate-typescript-types-and-sql-from-one-model)

- [Vet an aontu model for contradictions before you generate](/howto/vet-a-model-file-before-you-generate)

## Last verified

Verified 2026-11-22 against Node 22.23.5, `@voxgig/model` 12.0.2, aontu 0.76.3, and `pino` 10.4.0.
Every output block is what the command before it printed. orval 8.48.0, NSwag 14.8.0 on the
ASP.NET Core 10 runtime, Prisma 7.10.1, TypeSpec 1.18.0, Projen 0.105.7 and Terraform 1.17.2 ran
once in `record.sh`, and `compare.mjs` reads what each recorded. The script sets
`CHECKPOINT_DISABLE=1`, which turns off the checkpoint calls of the Prisma command line and of
Terraform. npm listed no `@voxgig/model`
release after 12.0.2 on that day, so the sorted run order and the dry-run gap are on that release.

[^1]: The `environment` variable the action writes has the shape of the example on
[Terraform's variables page](https://developer.hashicorp.com/terraform/language/values/variables),
`contains` call and all. That example allows `dev`, `staging`, and `prod`; this model declares two
environments, and the list follows the model.

[^2]: The [table of replacement patterns on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
puts `$$` first, as the pattern that inserts a single `$`. Terraform's
[escape for a literal `${`](https://developer.hashicorp.com/terraform/language/expressions/strings)
is `$${`, so writing it through a replacement string takes four dollar signs, and writing it
through a function takes two.