Skip to content
GantryCD

Hooks

Hooks run Bash scripts around OpenTofu commands. Use them for short steps such as opening a network tunnel, checking a plan, or sending a signal. Keep infrastructure changes in OpenTofu.

Add a hook

Add a hook block to a gantrycd_stack or gantrycd_context resource:

hook {
  name     = "check-plan"
  phase    = "post_plan"
  priority = 20
  script   = "./scripts/check-plan.sh"
}

The name appears in run logs.

Choose a phase

PhasesRuns around
pre_init, post_inittofu init
pre_plan, post_planPlan, destroy, and refresh steps
pre_apply, post_applyApply steps

Hooks do not run for raw commands.

Access run data

Hooks run from the stack’s working directory with the same variables and cloud credentials as OpenTofu.

  • Plan: GANTRYCD_PLAN_FILE points to the plan file in post_plan, pre_apply, and post_apply. For example, use tofu show -json "$GANTRYCD_PLAN_FILE" to read it.
  • State: GantryCD does not pass a state file to hooks. After init, a hook can use commands such as tofu show -json to read the current state through the configured backend.
  • Analysis: GantryCD does not pass its plan analysis or dependency data to hooks.
  • Other files: Files created by a hook remain available during that run but are not uploaded automatically. Output written to stdout or stderr appears in the run log.

Order hooks

Hooks from the stack and its contexts are combined for each phase. Priorities range from 1 to 99, and lower numbers run first. Use different priorities when the exact order matters.

Error handling

Hooks and OpenTofu commands both use fail-fast behavior.

When OpenTofu fails

A post_* hook runs only when the OpenTofu command before it succeeds:

  • If init fails, post_init and every later step are skipped.
  • If plan, destroy, or refresh fails, post_plan is skipped. No plan file is uploaded, and the run fails.
  • If apply fails, post_apply is skipped. The run fails, but any infrastructure changes already made by OpenTofu are not rolled back.

Exit code 2 from an OpenTofu plan means that changes were found. It counts as success, so post_plan runs.

When a hook fails

Hooks run with bash -e -o pipefail. An unhandled command or pipeline that exits with a non-zero status stops the current hook. GantryCD writes the error to the run log, skips every later hook and OpenTofu step, and marks the run as failed.

The point of failure matters:

  • A pre_* failure stops the OpenTofu command that follows it.
  • A post_init failure happens after init, but before the main command.
  • A post_plan failure happens after planning, but before the plan file is uploaded. The plan cannot be applied.
  • A post_apply failure happens after apply. The run fails, but infrastructure changes are not rolled back.

Handle an expected error inside the script when the hook is best effort:

script = "send-notification || true"