Skip to content

API: automation examples

Whole examples: a deploy that opens and closes a maintenance window, monitors kept as code with Ansible, cron heartbeats, status updates from a script.

Each example is complete: copy it, put your token in your CI’s secrets, and change the names. They need curl and jq.

A helper for scripts

One function that sends a request, waits when told to (429), stops on any other error with Heimdall’s message, and prints the answer:

heimdall.sh
#!/usr/bin/env bash
set -euo pipefail
: "${HEIMDALL:=https://heimdall.warewave.tech/api/v1}"
: "${HEIMDALL_API_TOKEN:?set HEIMDALL_API_TOKEN}"

# hd METHOD PATH [JSON]   (bash or zsh)
hd() {
  local method=$1 route=$2 body=${3:-} out code
  if [ -n "$body" ]; then set -- --data "$body"; else set --; fi   # the body, if any, as curl's arguments
  for try in 1 2 3 4 5; do
    out=$(mktemp)
    code=$(curl -sS -o "$out" -w '%{http_code}' -X "$method" "$HEIMDALL$route" \
      -H "Authorization: Bearer $HEIMDALL_API_TOKEN" -H "Content-Type: application/json" \
      -D "$out.h" ${1+"$@"})
    if [ "$code" = 429 ]; then
      sleep "$(awk 'tolower($1)=="retry-after:" {print $2+0}' "$out.h")"; rm -f "$out" "$out.h"; continue
    fi
    if [ "$code" -ge 400 ]; then
      echo "heimdall: $method $route: $code $(jq -r '.code + ": " + .message' "$out")" >&2
      rm -f "$out" "$out.h"; return 1
    fi
    cat "$out"; rm -f "$out" "$out.h"; return 0
  done
  echo "heimdall: $method $route: still rate limited" >&2; return 1
}

A deploy inside a maintenance window

Before the deploy, a window over the service’s monitors (found by tag) for at most 30 minutes; after it, the window is deleted — a running window that is deleted ends now. If the deploy breaks the service, the incident is there, and its alerts start when the window ends.

deploy.sh
#!/usr/bin/env bash
set -euo pipefail
source ./heimdall.sh

ids=$(hd GET "/monitors?tag=service:api&tag=env:prod" | jq -c '[.[].id]')
now=$(date -u +%Y-%m-%dT%H:%M:%SZ)
end=$(date -u -d '+30 min' +%Y-%m-%dT%H:%M:%SZ)    # macOS: date -u -v+30M …

window=$(hd POST /maintenances "$(jq -n --arg t "Deploy $GIT_SHA" --arg s "$now" --arg e "$end" \
  --argjson m "$ids" '{title: $t, starts_at: $s, ends_at: $e, monitor_ids: $m}')" | jq -r .id)
trap 'hd DELETE "/maintenances/$window" >/dev/null || true' EXIT   # ends it, whatever happens

./your-deploy-command
GitHub Actions
jobs:
  deploy:
    runs-on: ubuntu-latest
    env:
      HEIMDALL_API_TOKEN: ${{ secrets.HEIMDALL_API_TOKEN }}   # a write token
      GIT_SHA: ${{ github.sha }}
    steps:
      - uses: actions/checkout@v4
      - run: ./deploy.sh
GitLab CI
deploy:
  stage: deploy
  image: alpine:3.22
  before_script: [ "apk add --no-cache bash curl jq coreutils" ]
  variables:
    GIT_SHA: $CI_COMMIT_SHA          # HEIMDALL_API_TOKEN: a masked CI/CD variable
  script: [ "./deploy.sh" ]

Monitors as code with Ansible

The monitors live in your inventory; the play makes those that are missing, brings the others in line and deletes its own that the inventory no longer has. It finds its own monitors by a tag (managed-by:ansible), so the ones made by hand are left alone, and it sends nothing for a monitor that has not changed — run it twice and the second run reports changed=0.

group_vars/all/heimdall.yml
heimdall_url: https://heimdall.warewave.tech/api/v1
heimdall_monitors:
  - name: API
    type: http
    target: https://api.example.com/health
    interval_seconds: 60
    regions: [ist, fra, stc]
    conditions: ["[STATUS] == 200", "[RESPONSE_TIME] < 800"]
    tags: [env:prod, service:api]
  - name: Database
    type: tcp
    target: db.example.com:5432
    interval_seconds: 60
    regions: [ist]
    tags: [env:prod, service:db]
heimdall-monitors.yml
- name: Heimdall monitors
  hosts: localhost
  gather_facts: false
  vars:
    auth: { Authorization: "Bearer {{ lookup('env', 'HEIMDALL_API_TOKEN') }}" }
  tasks:
    - name: What Heimdall has (ours only)
      ansible.builtin.uri:
        url: "{{ heimdall_url }}/monitors?tag=managed-by:ansible"
        headers: "{{ auth }}"
      register: existing

    - name: Each monitor, made or brought in line
      vars:
        want: "{{ item | combine({'tags': item.tags + ['managed-by:ansible']}) }}"
        have: "{{ existing.json | selectattr('name', 'equalto', item.name) | first | default(None) }}"
        same: >-
          {{ have is not none and have.type == want.type and have.target == want.target and
             have.interval_seconds == want.interval_seconds and
             (have.regions | map(attribute='region') | sort) == (want.regions | sort) and
             (have.tags | sort) == (want.tags | sort) }}
      ansible.builtin.uri:
        url: "{{ heimdall_url }}/monitors{{ '/' ~ have.id if have else '' }}"
        method: "{{ 'PUT' if have else 'POST' }}"
        headers: "{{ auth }}"
        body_format: json
        body: "{{ want }}"
        status_code: [200, 201]
      changed_when: true
      when: not (same | bool)
      loop: "{{ heimdall_monitors }}"
      loop_control: { label: "{{ item.name }}" }

    - name: Ours that are no longer in the inventory
      ansible.builtin.uri:
        url: "{{ heimdall_url }}/monitors/{{ item.id }}"
        method: DELETE
        headers: "{{ auth }}"
        status_code: 204
      changed_when: true
      loop: "{{ existing.json | rejectattr('name', 'in', heimdall_monitors | map(attribute='name')) }}"
      loop_control: { label: "{{ item.name }}" }
Run it
HEIMDALL_API_TOKEN=hmd_… ansible-playbook heimdall-monitors.yml
  • The play compares what the list (GET /monitors) shows: type, target, interval, regions (the list gives each with its state, hence region) and tags. A change to a field the list does not show (conditions, http) is sent once you also change one of those — or compare against GET /monitors/{id} per monitor, which has everything.
  • The same pattern keeps status pages (by slug), rotations, teams and policies (by name) as code, with an admin token.

A cron job’s heartbeat

crontab
# every night at 03:00: ping when the backup succeeded, report the failure when it did not
0 3 * * * if /usr/local/bin/backup.sh; then curl -fsS -m 10 --retry 5 --retry-connrefused -o /dev/null https://heimdall.warewave.tech/hb/<token>; else curl -fsS -m 10 --retry 5 --retry-connrefused -o /dev/null https://heimdall.warewave.tech/hb/<token>/fail; fi

A ping needs no API token — the address is its own secret, so keep it out of repositories. A systemd timer does the same with ExecStartPost= and OnFailure=.

A status update from a script

status.sh
#!/usr/bin/env bash
# ./status.sh investigating "Slow API responses" "We are looking into it."
# ./status.sh resolved "" "Fixed."            (continues the open one)
set -euo pipefail
source ./heimdall.sh
page=01JC4QB7D2F6H9K3M5P8R1T4VW
open=$(hd GET "/status-pages/$page/incidents?active=true" | jq -r '.[0].id // empty')
body=$(jq -n --arg s "$1" --arg t "$2" --arg x "$3" --arg i "$open" \
  '{state: $s, text: $x} + (if $i == "" then {title: $t} else {incident_id: $i} end)')
hd POST "/status-pages/$page/updates" "$body" | jq -r '"\(.title): \(.state)"'

Incidents into your own tools

Every open incident, one line each
source ./heimdall.sh
hd GET "/incidents?active=true" | jq -r '.[] | "\(.ref)\t\(.severity)\t\(.state)\t\(.monitor_name)\t\(.opened_at)"'