Skip to main content
Version: 2.0

Jobs as Code

Clicking jobs and workflows together in the dashboard is fine for one environment. Once you have staging and production, or several teams, you want their definitions in Git: reviewed in pull requests, applied by CI, the same in every environment.

Milvaion offers two ways to do that. Both use the regular REST API with an api key, so they need nothing extra on the server.

milvaion CLITerraform provider
DefinitionsYAML files (apiVersion: milvaion/v1)HCL, milvaion_job resources; milvaion_workflow takes the same workflow YAML
StateNone. Jobs and workflows are matched by name on every runTerraform state
Good forTeams without Terraform, quick scripts, CI checksTeams that already manage infrastructure with Terraform
Also doesget, trigger, logs, exportData sources for jobs and workers

Pick one tool per job or workflow. If the CLI and Terraform both manage the same one, each will keep undoing the other's changes.

The Api Key​

Create a key under Settings → API keys with these permissions:

UsePermissions
apply, diff, TerraformScheduledJobManagement.List, .Detail, .Create, .Update, .Delete
Workflows in apply, diff, export, milvaion_workflowWorkflowManagement.List, .Detail, .Create, .Update, .Delete, plus ScheduledJobManagement.List to find the jobs steps run
Webhook triggers of workflowsWorkflowManagement.Trigger as well
get workers, milvaion_workerWorkerManagement.List, WorkerManagement.Detail
triggerScheduledJobManagement.Trigger
get occurrences, logsScheduledJobManagement.List, .Detail

A drift check in CI (milvaion diff --exit-code) only needs List and Detail.

An api key works in the project it was created in. Give each environment, and each project, its own key.

The milvaion CLI​

Install​

Download the archive for your platform from the GitHub releases tagged cli-v*, extract milvaion and put it on your PATH. Each release has a checksums file to verify the download.

With Go installed you can also build it from source:

go install github.com/Milvasoft/milvaion/tools/milvaion-cli@latest

That installs the binary as milvaion-cli; rename it to milvaion if you like.

Log In​

milvaion login --url https://milvaion.example.com --api-key "$KEY"

login checks the key and saves the URL and key to milvaion/config.yaml in your user config directory (~/.config on Linux, ~/Library/Application Support on macOS, %AppData% on Windows), readable only by you. Set MILVAION_CONFIG to use another file. To keep the key out of your shell history, pipe it in with --api-key-stdin.

In CI, skip login and set environment variables instead. They override the saved login:

export MILVAION_URL=https://milvaion.example.com
export MILVAION_API_KEY=...

Describe Jobs in YAML​

apiVersion: milvaion/v1
kind: Job
metadata:
name: nightly-invoice-report # the job's display name, and the key apply matches on
spec:
description: Sends yesterday's invoices to finance
tags: [billing, reports]
worker: reporter-worker # worker id
jobName: InvoiceReportJob # job type on that worker
cron: "0 0 2 * * *" # six fields, seconds first: 02:00 every day
concurrencyPolicy: Skip # Skip or Queue
jobData: # any YAML, sent to the job as JSON
recipients: [[email protected]]
format: pdf
executionTimeoutSeconds: 900
autoDisable:
enabled: true
threshold: 5
failureWindowMinutes: 60

Put several jobs in one file, either as YAML documents separated by ---, or as a list:

apiVersion: milvaion/v1
kind: JobList
items:
- metadata: {name: cleanup-temp-files}
spec:
worker: maintenance-worker
jobName: CleanupJob
cron: "0 30 3 * * *"
- metadata: {name: one-off-migration}
spec:
worker: sample-worker
jobName: MigrateJob
executeAt: 2026-12-01T22:00:00Z # one-time job
active: false

Run milvaion schema for the full field list. The fields are:

FieldNotes
descriptionFree text.
tagsList of tags.
workerWorker id. Changing it replaces the job (see below).
jobNameJob type on the worker.
cronRecurring schedule. Six fields, seconds first.
executeAtOne-time run, RFC 3339, in the future. Ignored when cron is set. Changed in place.
activeDefault true.
concurrencyPolicySkip (default) or Queue.
jobDataPayload. A YAML value or a JSON string.
zombieTimeoutMinutesLeave out to use the server default.
executionTimeoutSecondsLeave out to use the worker default.
autoDisable{enabled, threshold, failureWindowMinutes}. Leave it out and apply leaves the server's settings alone.
external, externalJobIdFor jobs reported by Hangfire or Quartz. Changing them replaces the job.

Leaving out any other field means "the default": removing description from the file clears it on the server.

Preview and Apply​

milvaion diff -f jobs/
~ update nightly-invoice-report (01a1d6f5-59e0-7465-9423-a145e95a45a1)
cron: "0 0 2 * * *" -> "0 0 3 * * *"
+ create cleanup-temp-files
worker: "maintenance-worker"
jobName: "CleanupJob"
cron: "0 30 3 * * *"
active: true
concurrencyPolicy: "Skip"

Plan: 1 to create, 1 to update, 0 to replace, 0 to delete, 4 unchanged.
milvaion apply -f jobs/

-f takes a file, a directory of .yaml/.yml files, or - for standard input, and can be repeated. Running apply twice with the same files changes nothing the second time.

How jobs are matched. metadata.name is the job's display name, and apply looks the job up by it. A name that does not exist yet is created. If two jobs on the server have the same name, apply stops and asks you to fix that first, rather than guess.

Renaming a job in the file creates a new job under the new name. The old one stays (and keeps its run history) until you run apply --prune. To keep the history on the renamed job, rename it in the dashboard first, then in the file.

Replacements. The API cannot change worker, external or externalJobId on an existing job. When one of them changes, apply creates the new job and then deletes the old one, which drops its run history. It refuses to do that unless you pass --allow-replace. If the create fails, the old job is left untouched.

The new job has a new id. Before deleting the old job, apply points every workflow step that runs it at the new one, in every workflow on the server, whether or not the workflow is in your files. Only the job of those steps changes: the steps keep their ids and keys, their run history stays attached, and the workflow's conflict fingerprint does not change. If a workflow has an unpublished draft, the draft still runs the old job and apply warns about it. If pointing a workflow at the new job fails, the old job is kept so nothing runs a deleted job; delete it by hand once the workflow is fixed.

Pruning​

Every job that apply creates or updates gets the tag managed-by:milvaion-cli. With --prune, apply deletes jobs that carry that tag but are no longer in the files:

milvaion apply -f jobs/ --prune

Jobs made in the dashboard do not have the tag, so --prune never touches them. When several repositories manage jobs on the same Milvaion, give each its own tag so one repository's prune cannot delete another's jobs:

milvaion apply -f jobs/ --prune --managed-tag managed-by:billing-repo

The tag shows up in the dashboard like any other tag. export and diff hide it.

Adopting Existing Jobs​

milvaion export > jobs.yaml
milvaion apply -f jobs.yaml

The export command writes the current jobs as milvaion/v1 YAML, leaving out defaults. The first apply of that file only adds the managed tag. From then on, edit the file instead of the dashboard.

The export command takes --kind job|workflow|all (default job), --name (repeatable), --tag, --managed, and -o file.yaml. Jobs reported by external schedulers are left out unless you pass --include-external.

Drift Detection in CI​

diff --exit-code exits 0 when the server matches the files and 2 when it does not:

# .github/workflows/milvaion-jobs.yml
name: Milvaion jobs
on:
pull_request:
paths: ['jobs/**']
push:
branches: [main]
paths: ['jobs/**']

jobs:
jobs:
runs-on: ubuntu-latest
env:
MILVAION_URL: ${{ vars.MILVAION_URL }}
MILVAION_API_KEY: ${{ secrets.MILVAION_API_KEY }}
steps:
- uses: actions/checkout@v4
- name: Install milvaion
run: |
curl -sSL https://github.com/Milvasoft/milvaion/releases/download/cli-v1.0.0/milvaion_1.0.0_linux_amd64.tar.gz | tar xz milvaion
sudo mv milvaion /usr/local/bin/
- name: Show changes
run: milvaion diff -f jobs/
- name: Apply
if: github.event_name == 'push'
run: milvaion apply -f jobs/ --prune

Everyday Commands​

milvaion get jobs                     # --tag, --search, -o json|yaml
milvaion get workers
milvaion get occurrences --job nightly-invoice-report --status Failed --limit 10

milvaion trigger nightly-invoice-report # prints the occurrence id
milvaion trigger nightly-invoice-report --follow # streams logs; exits 1 if the run fails
milvaion trigger nightly-invoice-report --data '{"format":"csv"}' --reason "rerun for audit"

milvaion logs 01a1d6f5-857c-7b21-995d-93ea2aea8ab5
milvaion logs --job nightly-invoice-report -f # newest run, follow until it finishes

Wherever a command takes a job, you can pass its name or its id.

Workflows as Code​

Workflows go in the same files as jobs. A kind: Workflow document holds everything the designer edits: the settings, the schedule, the input schema, the canvas notes, the steps and edges, and the webhook triggers.

apiVersion: milvaion/v1
kind: Workflow
metadata:
name: nightly-etl # the key apply matches on
spec:
description: Extract, wait for approval, load
tags: [etl]
failureStrategy: StopOnFirstFailure
schedule:
cron: "0 0 2 * * *"
timeZone: Europe/Istanbul
overlapPolicy: Skip
maxConcurrentRuns: 1
input: {day: yesterday}
inputSchema:
type: object
properties:
day: {type: string}
steps:
- key: extract # unique in the workflow: a-z, 0-9 and _
job: etl-extract # the job's display name, not its id
input: {day: "{{ input.day }}"}
policy: {maxAttempts: 3, backoff: exponential, backoffSeconds: 30}
- key: approve
type: Approval
config: {title: "Load the extracted data?", approverRoles: [Data Owners], channels: [email]}
- key: load
name: Load into the warehouse
job: etl-load
edges:
- {from: extract, to: approve}
- {from: approve, to: load, fromPort: approved}
triggers:
- name: from-ci
secret: ci_hook_secret # the name of a project secret, never its value
rateLimitPerMinute: 10

Nothing in the file is a server id, so the same file works on every server:

In the fileMatched by
The workflowmetadata.name
A stepkey. A step that keeps its key keeps its id, and the history of its runs, when the workflow changes.
The job a Task step runsjob, the job's display name. It must be unique on the target server.
An edgethe keys of the steps it connects
A webhook triggername
A secretits name. Each environment's project needs a secret with that name; its value never leaves the server.

milvaion schema lists the job fields. For workflows, milvaion export --kind workflow against a server where the workflow exists is the quickest way to get a correct file: every value equal to the API default is left out, so the export stays short.

Some things stay on the server when the file leaves them out:

Left out of the fileWhat apply does
position of a stepKeeps where the designer put the step.
notesKeeps the canvas notes. notes: [] removes them.
triggersLeaves the triggers alone. triggers: [] deletes them.

Everything else is managed: a setting missing from the file is set back to its default.

Webhook Trigger Tokens​

The server shows a trigger's token once, when the trigger is created, and every environment has its own. Tokens are never exported and never printed, and neither is the trigger's URL path, which contains the token. Pass --trigger-tokens-file to save the tokens of the triggers an apply creates to a file only you can read; otherwise rotate the token in the dashboard when you need it.

milvaion apply -f workflows/ --trigger-tokens-file ~/milvaion-tokens.json

Conflicts​

Apply never overwrites somebody else's change silently. It records a fingerprint of what it left on the server in a tag (milvaion-applied:..., hidden from exports), and refuses to change a workflow when:

  • the workflow was changed on the server since the last apply (moving steps in the designer, or editing notes or triggers the file does not manage, does not count),
  • the workflow was not created by apply and differs from the file, or
  • the workflow has unpublished draft edits in the designer.

Nothing is changed when any workflow is refused:

~ update workflow nightly-etl (01a239f5-328b-7f2c-b5f8-452f21698d78)
description: changed in the prod dashboard -> Extract, wait for approval, load
~ step extract: policy {"backoff":"exponential","backoffSeconds":30,"maxAttempts":3,"retryOn":"any"} -> {"backoff":"exponential","backoffSeconds":60,"maxAttempts":3,"retryOn":"any"}
! conflict: it was changed on the server since the last apply

Error: refusing to overwrite 1 workflow(s): "nightly-etl" (it was changed on the server since the last apply). Nothing was changed. Check the diff, then re-run with --force to overwrite

Look at the diff, bring the change into the file if it should stay, and run apply again; or pass --force to overwrite it. --force also discards a draft.

Dry Run, Order and Pruning​

apply --dry-run prints the plan and changes nothing, like diff. Apply creates and updates jobs first, so a new step can run a job from the same files, then workflows. With --prune it deletes managed workflows that are no longer in the files, and only then managed jobs, so no workflow is left pointing at a deleted job.

Projects​

An api key belongs to one project and always works there. --project (or MILVAION_PROJECT) sends the project's slug in the X-Milvaion-Project header as a safety check: when projects are enabled, the API refuses every request whose key belongs to another project, so a key mix-up cannot change the wrong project. Nothing is changed:

Error: listing jobs: forbidden (403): This api key belongs to another project.
milvaion --project billing apply -f billing/

Promoting from Test to Prod​

Because files hold names instead of ids, promotion is applying the same files to the next environment. A typical repository:

milvaion/
jobs.yaml # kind: JobList
workflows/
nightly-etl.yaml # kind: Workflow

1. Bring what exists in test under version control. Run once, against test:

export MILVAION_URL=https://milvaion-test.example.com MILVAION_API_KEY="$TEST_KEY"
milvaion export --kind all -o milvaion/all.yaml
milvaion apply -f milvaion/ # adopts them: only adds the bookkeeping tags

2. Change things in a pull request, or change them in the test dashboard and export again. diff shows what each environment would get:

MILVAION_URL=https://milvaion-test.example.com MILVAION_API_KEY="$TEST_KEY" milvaion diff -f milvaion/
MILVAION_URL=https://milvaion.example.com MILVAION_API_KEY="$PROD_KEY" milvaion diff -f milvaion/

3. Apply to test, then to prod, for example from GitHub Actions with one environment per stage, so prod waits for an approval:

# .github/workflows/milvaion.yml
on:
push:
branches: [main]
paths: ['milvaion/**']

jobs:
apply:
strategy:
max-parallel: 1
matrix:
stage: [test, prod]
environment: ${{ matrix.stage }} # MILVAION_URL and MILVAION_API_KEY are environment secrets
runs-on: ubuntu-latest
env:
MILVAION_URL: ${{ secrets.MILVAION_URL }}
MILVAION_API_KEY: ${{ secrets.MILVAION_API_KEY }}
steps:
- uses: actions/checkout@v4
- name: Install milvaion
run: |
curl -sSL https://github.com/Milvasoft/milvaion/releases/download/cli-v1.0.0/milvaion_1.0.0_linux_amd64.tar.gz | tar xz milvaion
sudo mv milvaion /usr/local/bin/
- run: milvaion apply -f milvaion/ --dry-run
- run: milvaion apply -f milvaion/ --prune

What has to exist in prod before the first apply:

  • The workers the jobs name, running. Jobs are created on the prod server from the same file; steps find them by name.
  • The secrets the triggers and steps name, in the prod project. Apply passes names only.
  • The roles and notification channels approval steps name.

A workflow that somebody changed in prod by hand stops the promotion with a conflict instead of being overwritten, and the next apply after --force (or after the change is in the files) goes through.

The Terraform Provider​

Configure the Provider​

terraform {
required_providers {
milvaion = {
source = "milvasoft/milvaion"
version = "~> 1.0"
}
}
}

provider "milvaion" {
url = "https://milvaion.example.com"
# api_key = var.milvaion_api_key # or set MILVAION_API_KEY
}

url and api_key fall back to MILVAION_URL and MILVAION_API_KEY. Keep the key out of .tf files.

Define Jobs​

data "milvaion_worker" "reporter" {
worker_id = "reporter-worker"
}

resource "milvaion_job" "invoice_report" {
name = "nightly-invoice-report"
description = "Sends yesterday's invoices to finance"
tags = ["billing", "reports"]
worker_id = data.milvaion_worker.reporter.worker_id
job_name = "InvoiceReportJob"
cron_expression = "0 0 2 * * *"

job_data = jsonencode({
recipients = ["[email protected]"]
format = "pdf"
})

execution_timeout_seconds = 900

auto_disable = {
threshold = 5
failure_window_minutes = 60
}

lifecycle {
# Fail the plan early if the worker does not offer this job type.
precondition {
condition = contains(data.milvaion_worker.reporter.job_names, "InvoiceReportJob")
error_message = "reporter-worker does not offer InvoiceReportJob."
}
}
}
AttributeNotes
nameRequired. Display name.
description, tags, job_name, cron_expression, execute_atUpdated in place.
worker_id, is_external, external_job_idChanging them replaces the job (see below).
is_activeDefault true.
concurrent_execution_policySkip (default) or Queue.
job_dataJSON string. Use jsonencode(). Key order and whitespace do not cause diffs.
zombie_timeout_minutes, execution_timeout_secondsLeave out to use the defaults.
auto_disableLeave it out to keep whatever the server has. Removing it later stops managing it; it does not reset it.

Terraform tracks jobs by id, not by name, so renaming a milvaion_job updates it in place and keeps its history.

Replacements. A change to worker_id, is_external or external_job_id shows in the plan as an update with a warning, and id becomes (known after apply). The provider does the replacement itself, the way milvaion apply does, rather than letting Terraform destroy the job and create it again: it creates the new job, points every workflow step that runs the old job at it (in every workflow on the server, whether Terraform manages it or not), and only then deletes the old job. Workflows keep running and milvaion_workflow shows no drift. Runs recorded under the old job are not moved. An unpublished workflow draft still runs the old job, and apply warns about it. If pointing a workflow at the new job fails, the old job is kept and apply fails with its id; delete it by hand once no workflow runs it. lifecycle { create_before_destroy = true } is not needed.

Define Workflows​

milvaion_workflow takes the same kind: Workflow YAML as the CLI, so a file can move between the two tools, and milvaion export --kind workflow --name ... writes one.

resource "milvaion_job" "extract" {
name = "etl-extract"
worker_id = "sql-worker"
job_name = "SqlQueryJob"
cron_expression = "0 0 0 1 1 *"
}

resource "milvaion_workflow" "nightly_etl" {
manifest = file("${path.module}/workflows/nightly-etl.yaml")

# Steps find jobs by name; make Terraform create the jobs first.
depends_on = [milvaion_job.extract]
}

output "nightly_etl_hook_token" {
value = milvaion_workflow.nightly_etl.trigger_tokens["from-ci"]
sensitive = true
}
AttributeNotes
manifestRequired. One kind: Workflow document. Positions, notes and triggers it leaves out stay as they are on the server.
forceDefault false: the apply fails when the workflow was changed outside Terraform since the last apply, or has a draft. true overwrites it.
trigger_tokensSensitive. Tokens of the triggers Terraform created, by trigger name.
id, nameComputed.

When the workflow drifts, the refresh puts the server's version of what the manifest manages into the state, so the plan shows the difference as a change of manifest. Import a workflow by id; its whole definition becomes the manifest in the state, which terraform state show prints for you to copy into a file.

Import Existing Jobs​

terraform import milvaion_job.invoice_report 01a1d6f5-59e0-7465-9423-a145e95a45a1

Or, with Terraform 1.5 and later:

import {
to = milvaion_job.invoice_report
id = "01a1d6f5-59e0-7465-9423-a145e95a45a1"
}

milvaion get jobs lists the ids.

Data Sources​

# Look a job up by name (it must be unique) or by id.
data "milvaion_job" "cleanup" {
name = "cleanup-temp-files"
}

# A registered worker: status, version, job_names, routing_patterns, instance_count.
data "milvaion_worker" "maintenance" {
worker_id = "maintenance-worker"
}

output "cleanup_schedule" {
value = data.milvaion_job.cleanup.cron_expression
}

Things to Know​

  • Cron has six fields. Milvaion cron expressions start with seconds: 0 */5 * * * * is every five minutes. Both tools reject five-field expressions before calling the API.
  • Workers must be running. Milvaion checks that the worker exists, is active and offers the job type when a job is created. Start the worker before you apply.
  • Times are UTC. executeAt / execute_at accept any offset and store UTC.
  • Edits in the dashboard are drift. For jobs, the next apply puts the file's values back. Pausing a job in the dashboard during an incident is fine, but expect the next deploy to switch it on again unless the file says active: false. For workflows, apply refuses instead (see Conflicts).
  • Renaming is a new workflow for the CLI. The CLI matches by name, so a renamed workflow is created again; delete the old one, or let --prune do it. Terraform tracks the id and renames in place.
  • A step key is its identity. Renaming a key replaces the step, and its earlier runs stay with the old one.
  • Applying publishes. The definition in the file becomes the published version at once. Runs that are in progress keep the version they started with.

Next Steps​

  • Api Keys: create and rotate the key the tools use
  • MCP Server: ask an AI assistant about the jobs you deployed
  • Workflows: what the steps, edges and settings in a workflow file mean