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
| Phases | Runs around |
|---|---|
pre_init, post_init | tofu init |
pre_plan, post_plan | Plan, destroy, and refresh steps |
pre_apply, post_apply | Apply 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_FILEpoints to the plan file inpost_plan,pre_apply, andpost_apply. For example, usetofu 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 -jsonto 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_initand every later step are skipped. - If plan, destroy, or refresh fails,
post_planis skipped. No plan file is uploaded, and the run fails. - If apply fails,
post_applyis 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_initfailure happens after init, but before the main command. - A
post_planfailure happens after planning, but before the plan file is uploaded. The plan cannot be applied. - A
post_applyfailure 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"