Run a task with Terraform
Set up a tenant only with Terraform, in two folders with two keys, and end with a running task. You make access, a secret, a task with its code and a hook, run it, change it, and clean up.
What this tutorial proves
- One owner key makes access (a user, a group and a key). A user key then manages the app. A user key cannot make access.
- The secret value never enters the Terraform state.
- A code change is one in-place change in the plan, and the hook URL stays.
- A secret rotates with no redeploy.
- You can import an object that already exists, and clean up in reverse order.
What you build
Two Terraform folders, each with its own state and its own key, and one task folder.
terraform-tutorial/
├── tasks/terraform-demo/ the task: task.yaml and index.ts
├── access/main.tf user, group, key (owner key)
└── app/main.tf secret, task, code, hook (user key)The access folder makes a user, a group with its permissions, and a key for the user. The app folder uses that key to make the secret, the task, its code (a deployment) and a hook. Keep the folders apart, so the daily job never holds the owner key. Manage a tenant with Terraform explains why.
1 · What you need
- Terraform 1.11 or later. The secret resource uses a write-only argument. OpenTofu works too, with the full source address (see Provider configuration).
- An owner key, from
ignitify login. See Install. - The
ignitifyCLI. Version 3.1.0 or later. This tutorial was run with 3.1.0, and 3.2.0 and 3.3.0 change no flag it uses. - A plan that allows webhooks and outbound calls. This tutorial uses Starter. If
ignitify_hookfails, runignitify whoamiand checkmay_use_webhooks.
Make the folders, and keep the path of the top folder in a variable:
$ mkdir -p terraform-tutorial/{tasks/terraform-demo,access,app}
cd terraform-tutorial
export ROOT="$PWD"2 · The task folder
The task has two files. It reads a secret, calls one host that egress_allow permits and one that it does not, and counts its runs. It returns a short hash of the secret, never the value.
schema_version: 1
slug: terraform-demo
runtime: node
secrets: [DEMO_TOKEN]
execution:
cardinality: many
state: across-runs
interaction: continuous
network:
type: egress
egress_allow: [example.com]
run:
payload: { mode: default }
preset: std.small
timeout_sec: 120// terraform-demo: reports the code version, a hash of its secret (never the value),
// its warm-process counters, and what an allowed and a blocked outbound call do.
import { createHash } from "node:crypto";
const VERSION = "A";
let initCount = 0;
let runCount = 0;
export async function init() {
initCount += 1;
}
type Ctx = {
secrets: Record<string, string>;
chunk: (data: unknown) => void;
metric: (name: string, value: number) => void;
};
async function allowedStatus(url: string): Promise<number | string> {
try {
return (await fetch(url, { signal: AbortSignal.timeout(10_000) })).status;
} catch (e) {
return errorCode(e);
}
}
async function blockedCode(url: string): Promise<string> {
try {
const res = await fetch(url, { signal: AbortSignal.timeout(10_000) });
return `reached:${res.status}`;
} catch (e) {
return String(errorCode(e));
}
}
function errorCode(e: unknown): string {
const err = e as { code?: string; cause?: { code?: string }; name?: string };
return err.cause?.code ?? err.code ?? err.name ?? "error";
}
export async function run(payload: Record<string, unknown>, ctx: Ctx) {
runCount += 1;
ctx.chunk({ step: 1 });
const token = ctx.secrets.DEMO_TOKEN ?? "";
const tokenSha256_8 = createHash("sha256").update(token).digest("hex").slice(0, 8);
const allowed = await allowedStatus("https://example.com");
const blocked = await blockedCode("https://github.com");
ctx.metric("demo_runs", 1);
ctx.chunk({ step: 2 });
return {
version: VERSION,
token_sha256_8: tokenSha256_8,
run_count: runCount,
init_count: initCount,
allowed,
blocked,
payload_echo: payload,
};
}Save them as tasks/terraform-demo/task.yaml and tasks/terraform-demo/index.ts. The slug in task.yaml must equal the slug of the ignitify_task resource below.
3 · Access, with the owner key
Save this as access/main.tf. It makes the user tf-ci, the group tf-app and a key. The group holds ten permissions. It has runs.write, because the user will start runs. A job that only deploys does not need it.
# Access: one user, one group and the user's key. Applied with the OWNER key.
terraform {
required_version = ">= 1.11"
required_providers {
ignitify = {
source = "ignitify-dev/ignitify"
version = "0.3.2"
}
}
}
provider "ignitify" {}
data "ignitify_whoami" "me" {}
check "owner_key" {
assert {
condition = data.ignitify_whoami.me.is_owner_key
error_message = "This configuration manages access and needs an owner key."
}
}
resource "ignitify_user" "ci" {
name = "tf-ci"
}
resource "ignitify_group" "app" {
name = "tf-app"
permissions = [
"tasks.read",
"tasks.write",
"deployments.read",
"deployments.write",
"secrets.read",
"secrets.write",
"hooks.read",
"hooks.write",
"runs.read",
"runs.write",
]
members = [ignitify_user.ci.name]
}
resource "ignitify_api_key" "ci" {
user = ignitify_user.ci.name
label = "tutorial"
}
output "app_key" {
value = ignitify_api_key.ci.raw_key
sensitive = true
}The check block warns when the key is not an owner key. Apply it:
$ export IGNITIFY_API_KEY=<your owner key> cd "$ROOT/access" terraform init terraform applyPlan: 3 to add, 0 to change, 0 to destroy.…Apply complete! Resources: 3 added, 0 changed, 0 destroyed.Outputs:app_key = <sensitive>
init installs the provider and checks its signature, and prints Installed ignitify-dev/ignitify v0.3.2 (self-signed, key ID 318F7795E174644F). With the owner key, ignitify user:list shows tf-ci, and ignitify group:list shows tf-app and its permissions.
Take the user key from the state into your shell, without printing it. From now on, you act as the user:
$ export IGNITIFY_API_KEY="$(terraform output -raw app_key)"Optional · A user key cannot make access
To see the split, make a folder refused/ with one user resource and apply it with the user key that is now in your shell.
terraform {
required_providers {
ignitify = {
source = "ignitify-dev/ignitify"
version = "0.3.2"
}
}
}
provider "ignitify" {}
resource "ignitify_user" "nope" {
name = "tf-nope"
}$ cd "$ROOT/refused" terraform init terraform applyPOST /users: HTTP 403: only an owner key manages users, groups and keys (reason: owner-required)
The message is part of the error that Terraform prints. Nothing was made. Delete the refused folder.
4 · The app, with the user key
Save this as app/main.tf. It makes the secret, the task, the code and the hook.
# App: a secret, a task, its code and a hook. Applied with the USER key from ../access.
terraform {
required_version = ">= 1.11"
required_providers {
ignitify = {
source = "ignitify-dev/ignitify"
version = "0.3.2"
}
}
}
provider "ignitify" {}
variable "demo_token" {
type = string
sensitive = true
ephemeral = true
}
variable "demo_token_version" {
type = number
default = 1
}
variable "task_dir" {
type = string
}
resource "ignitify_secret" "token" {
name = "DEMO_TOKEN"
value_wo = var.demo_token
value_wo_version = var.demo_token_version
}
resource "ignitify_task" "demo" {
slug = "terraform-demo"
}
resource "ignitify_deployment" "demo" {
task = ignitify_task.demo.slug
source_dir = var.task_dir
timeouts = {
create = "20m"
update = "20m"
}
}
resource "ignitify_hook" "demo" {
task = ignitify_task.demo.slug
}
output "hook_url" {
value = ignitify_hook.demo.url
}
output "hook_secret" {
value = ignitify_hook.demo.secret
sensitive = true
}- The secret variable is
sensitiveandephemeral, andvalue_wois write-only. The value is sent to the platform and never saved in the state. task_diris the absolute path of the task folder.- The deployment waits for the build. The timeouts of 20 minutes leave room for a large task.
Pass the secret in the environment, never in a file. Pass each -var as its own quoted word:
$ cd "$ROOT/app" export TF_VAR_demo_token=<a secret value> terraform init terraform apply -var "task_dir=$ROOT/tasks/terraform-demo"Plan: 4 to add, 0 to change, 0 to destroy.…ignitify_deployment.demo: Creation complete after 28s…Apply complete! Resources: 4 added, 0 changed, 0 destroyed.Outputs:hook_secret = <sensitive>hook_url = "https://…/hooks/trigger/<id>"
The build took about 28 s for this small task. Check the deployment, with the id from the apply:
$ ignitify deployment:get <deployment-id>It shows status READY, secrets ["DEMO_TOKEN"] and the execution block. Search the state for your secret value: there is no match.
$ grep -c "$TF_VAR_demo_token" terraform.tfstate0
5 · Run the task and read the result
Terraform made the task, so you have no local .ignitify state. The CLI finds the deployment on the server. --dir must name an existing folder that holds the task folder.
$ ignitify task:run terraform-demo --wait --json --dir "$ROOT/tasks"Using deployment <id> (resolved from the server — no local state).
The result of the first run:
{ "allowed": 200, "blocked": "ECONNRESET", "version": "A", "run_count": 1, "init_count": 1,
"payload_echo": { "mode": "default" }, "token_sha256_8": "<8 hex characters>" }allowed: 200is the call toexample.com, whichegress_allowpermits.blocked: "ECONNRESET"is the answer of the platform to a host outsideegress_allow.token_sha256_8is the first 8 hex characters of the SHA-256 of your secret. Check it yourself:
$ printf '%s' "$TF_VAR_demo_token" | shasum -a 256 | cut -c1-8Run it again, and a third time with a payload:
$ ignitify task:run terraform-demo --wait --json --dir "$ROOT/tasks"
ignitify task:run terraform-demo --wait --json --dir "$ROOT/tasks" --payload '{"mode":"custom"}'These runs return run_count 2 and 3 and init_count 1. They run on the same warm VM. ignitify run:logs <run-id> shows the task metric task_demo_runs, and never the secret.
6 · Update the code
In tasks/terraform-demo/index.ts, change const VERSION = "A"; to "B". Then plan:
$ terraform plan -var "task_dir=$ROOT/tasks/terraform-demo"Plan: 0 to add, 1 to change, 0 to destroy.
Only ignitify_deployment changes, in place. The plan sees the change through the hash of the files in the folder. Apply it:
$ terraform apply -var "task_dir=$ROOT/tasks/terraform-demo"The apply takes about 30 s. It waits for the new build, and then deletes the old deployment. The hook URL and the secret stay the same.
Run the task. The result now says "version": "B".
7 · Rotate the secret
The secret value is write-only, so Terraform cannot see that it changed. Change the value and raise demo_token_version:
$ export TF_VAR_demo_token=<a new value>
terraform apply -var "task_dir=$ROOT/tasks/terraform-demo" -var demo_token_version=2The plan changes only ignitify_secret.token. The deployment id stays the same, and there is no rebuild. ignitify secret:list shows a new updated_at, and the next run returns the new token_sha256_8. See ignitify_secret.
8 · Call the hook with a signed request
The hook is a URL that starts a run. A request must carry an HMAC-SHA256 signature of its body, made with the hook secret. Take both from the outputs. Send the body with --data-binary and the JSON content type. With -d, curl labels the body as a form, and the signature check answers 401 invalid-signature.
$ BODY='{"leg":"x"}' SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$(terraform output -raw hook_secret)" -binary | xxd -p -c256) curl -s -X POST "$(terraform output -raw hook_url)" \ -H "x-ignitify-signature: sha256=$SIG" -H "x-ignitify-delivery: $(date +%s)-1" \ -H 'content-type: application/json' --data-binary "$BODY"202 {"run_id": …, "resource_id": "run_…", "status": "PENDING"}
Each call needs a new x-ignitify-delivery value. A repeat is deduplicated. The answer holds the resource_id of the run. Wait until its status is COMPLETED, about 5 to 8 s, then read the result with the user key (runs.read is enough):
$ ignitify run:get <resource_id> --full --jsonThe result has "version": "B". See ignitify_hook.
9 · Import an object that already exists
Import lets Terraform own an object that it did not make. To try it, forget the hook and import it back. First read the hook's id:
$ terraform state show ignitify_hook.demoNote resource_id. Then:
$ terraform state rm ignitify_hook.demo terraform import -var "task_dir=$ROOT/tasks/terraform-demo" -var demo_token_version=2 ignitify_hook.demo terraform-demo/<resource_id> terraform plan -var "task_dir=$ROOT/tasks/terraform-demo" -var demo_token_version=2Import successful!…No changes.
After an import, the hook secret in the state is empty. The server shows it once. The hook still works with the secret you read earlier. The import id of each resource is on its page. See Recipes.
10 · Clean up, in reverse order
Destroy the app first, and then access. Access needs the owner key again.
$ cd "$ROOT/app"
terraform destroy -var "task_dir=$ROOT/tasks/terraform-demo" -var demo_token_version=2
export IGNITIFY_API_KEY=<your owner key>
cd "$ROOT/access"
terraform destroyThe first destroy removes the hook, the secret, the deployment and the task. The second removes the key, the group and the user. After both:
- The hook URL answers
404 {"error":"unknown hook","reason":"hook-not-found"}. GET /tasks/terraform-demoanswers404 task-not-found.- The user key is refused with
API key is unknown or has been revoked [key-invalid].
Keep these in mind
- The state holds secrets. The
accessstate holds the raw key of the user. Theappstate holds the hook secret. The secret value itself is never in it. Add.terraform/and*.tfstate*to.gitignore, and use an encrypted backend with limited access. - The CLI after a Terraform setup.
task:runandrun:getwork with the user key.task:getreads only the local task folder, so useignitify task:listfor the server side. - Pass the flags as separate quoted words, for example
-var "task_dir=$ROOT/tasks/terraform-demo". In zsh, an unquoted variable that holds several flags is not split, and Terraform answersflag provided but not defined. - Without the right permission, a run is refused. With
runs.readonly,task:runanswerspermission denied: this key needs the runs.write permission.
Next steps
- Read one page per resource: Provider configuration, ignitify_deployment, ignitify_group and the others in the Terraform section of the docs.
- Run the app module in CI with the user key: Recipes.
- When a plan or an apply fails, see Troubleshooting.
- Learn the permissions: Users, groups and permissions.