Skip to content

fix(tf): devops tf drift exits non-zero on drift or a failed check #5319

Description

@dan-petty

Problem Description

devops tf drift always exits 0. OpenTofu check blocks only give warnings. The drift plan takes the state lock (analysis.py:417).

Order 5 of the plan in #5311. The owner approved the plan on 2026-11-13.

Reproduction Steps

  1. Run devops tf drift <stack> in an initialized stack where a resource differs from the state.
  2. Read the exit code with echo $?.
  3. Add a check block that fails, and run devops tf drift <stack> again.

Expected vs Actual Behavior

Expected: exit 2 on drift, a non-zero exit on a failed or unknown check, and -lock=false passes to tofu so that the drift plan does not take the state lock.

Actual: tf_drift in src/devops_cli/commands/tf.py prints the drift table and returns, so the exit code is 0. read_plan_drift (src/devops_cli/tf/analysis.py:417) runs tofu plan -refresh-only -json with no way to add -lock=false, and it does not read the exit code of tofu.

Environment Diagnostics

devops-cli 0.124.0. Found by a read of the source on 2026-11-13. tofu is not installed in the devcontainer yet (#5317), so there is no live run.

Proposed Solution

Exit 2 on drift. Read .checks from 'tofu show -json' of the saved plan, and exit non-zero on a failed or unknown check. Pass extra arguments such as -lock=false to tofu.

Existing Tool Considered

tofu does all of the work. No open tool adds devops pacing, the agent refusal or a dry run with zero requests.

Cost: Build: about 2.0M tokens and 3 days in 3 PRs (pass-through 1.2M, drift fix 0.3M, guard 0.5M), test first. Keep: about 50k tokens a month. Fix: about 200k tokens for each break. This item is the drift part: about 0.3M tokens.

Acceptance Criteria

  • The PR cites a fail-to-pass run.
  • Tests use recorded plan JSON for four cases: clean, drift, failed check and unknown check.

Dependencies

#5318. Part of #5311.

Source: #5311

Alternatives check of 2026-11-22: in-use.
The repository already uses this tool.
Tool: opentofu/opentofu (https://github.com/opentofu/opentofu), MPL-2.0, last activity 2026-11-21, maintained.
Reason: Searches were degraded and returned no useful tool pages, but the repository facts and the issue's own read of OpenTofu show it supplies every needed primitive: detailed exit codes, unlocked refresh plans and saved-plan check results.

Covers:

  • -detailed-exitcode returns 2 when the plan holds changes
  • -lock=false runs the drift plan without the state lock
  • tofu show -json of the saved plan holds the check results

Lacks:

  • No CLI wiring that maps plan results to devops exit codes
  • No drift table or in-sync message for operators
  • No serialized --format json drift report

Proposed design

Problem statement

devops tf drift always exits 0. The command prints the drift table or the in-sync line and returns. The refresh-only plan takes the state lock and ignores the exit code of tofu. This change saves the plan and reads its checks. It exits 2 on drift and 1 on a failed or unknown check or a plan error. It runs the plan with -lock=false.

Acceptance criteria

Requirement: Drift plan command flags

The drift plan SHALL run tofu plan -refresh-only -detailed-exitcode -lock=false -out=<plan file> and SHALL NOT pass -json.

Scenario: Drift plan argv

  • WHEN the test calls read_plan_drift on an initialized directory whose process fake records the plan call
  • THEN the test asserts that the recorded argv holds plan, -refresh-only, -detailed-exitcode, -lock=false and one -out= argument, and holds no -json.

Requirement: Check results read from the saved plan

read_plan_drift MUST read the top-level checks array of tofu show -json <plan file>.

Scenario: Failed and unknown checks

  • WHEN the test gives read_plan_drift a process fake whose plan run succeeds and whose tofu show -json <plan file> answer holds one fail check and one unknown check
  • THEN the test asserts that failed_checks holds the failed check's address.to_display and unknown_checks holds the unknown check's address.to_display.

Requirement: Exit 2 on drift

devops tf drift SHALL exit 2 when the plan reports changes or the drift report holds any divergence.

Scenario: Recorded replay with drift

  • WHEN the test scripts the plan to return exit code 2 and the saved-plan show to hold one drifted address
  • THEN the test asserts result.exit_code == 2 and the output holds the drifted address and attribute changed.

Requirement: Exit 0 on a clean stack

devops tf drift SHALL exit 0 when the plan returns 0, each check passes and the drift report holds no divergence.

Scenario: No drift

  • WHEN the test scripts the plan to return exit code 0 and the saved-plan show to hold no resource_drift and only pass checks
  • THEN the test asserts result.exit_code == 0 and the output holds the in-sync message.

Requirement: Exit 1 on a failed check

devops tf drift SHALL exit 1 when a check result is fail or error.

Scenario: Failed and error checks

  • WHEN the test scripts the plan to return exit code 0 and the saved-plan show to hold one check with status fail and one check with status error
  • THEN the test asserts result.exit_code == 1 and the output holds both checks' address.to_display values.

Requirement: Exit 1 on an unknown check

devops tf drift SHALL exit 1 when a check result is unknown.

Scenario: Unknown check

  • WHEN the test scripts the plan to return exit code 0 and the saved-plan show to hold one check with status unknown
  • THEN the test asserts result.exit_code == 1 and the output holds the unknown check's address.to_display.

Requirement: Exit 1 on a plan error

devops tf drift SHALL exit 1 when tofu plan returns an exit code other than 0 or 2.

Scenario: Plan error

  • WHEN the test scripts tofu plan to return exit code 1 with stderr Error: backend unavailable
  • THEN the test asserts that read_plan_drift returns plan_returncode 1 and plan_error Error: backend unavailable. It asserts that the process fake recorded no tofu show of a plan file and that devops tf drift exits 1 with that error in the output.

Requirement: Exit 1 wins over drift

devops tf drift SHALL exit 1 when a check fails or is unknown even if the plan reports drift.

Scenario: Failed check with drift

  • WHEN the test scripts the plan to return exit code 2 and the saved-plan show to hold one fail check and one drifted address
  • THEN the test asserts result.exit_code == 1 and the output holds the failed check's address.

Requirement: Serialized output keeps the exit code

devops tf drift --format json MUST emit the report and then exit 2 on drift.

Scenario: JSON output on drift

  • WHEN the test runs devops tf drift --format json with a plan that returns exit code 2 and one drifted address
  • THEN the test asserts that the emitted payload holds the drifted address and that the command exits 2.

Requirement: Uninitialized directory result

read_plan_drift SHALL return an empty PlanDriftResult when the directory has no .terraform directory.

Scenario: Uninitialized directory

  • WHEN the test calls read_plan_drift on a directory without a .terraform directory
  • THEN the test asserts that drifted, failed_checks and unknown_checks are empty, plan_returncode is 0, and the process fake recorded no call.

Requirement: Exit codes in the command help

The devops tf drift help SHALL state the exit codes 0, 1 and 2 and their meanings.

Scenario: Help text

  • WHEN the test runs devops tf drift --help
  • THEN the output states that exit code 0 means no drift, 1 a failed check or plan error, and 2 drift.

Requirement: Generated documentation stays current

The generated command page MUST hold the revised devops tf drift help.

Scenario: Documentation freshness

  • WHEN the author runs uv run devops docs generate
  • THEN uv run devops ci --check --only docs passes.

Existing Tool Considered

opentofu/opentofu (MPL-2.0) is in use; the alternatives check in the issue body records what it covers and lacks. This item adds the CLI wiring that maps the plan return code and the saved-plan checks results to the devops exit codes. The command keeps the existing drift table and --format json report.

Key questions

  • Why does devops tf drift exit 0 today?: tf_drift prints the drift table or the in-sync line and returns. The serialized branch returns after emit_serialized. read_plan_drift runs tofu plan -refresh-only -json at line 417. It returns parse_plan_drift(res.stdout) at line 424 without reading res.returncode. [sources: src/devops_cli/commands/tf.py:609, src/devops_cli/commands/tf.py:615, src/devops_cli/commands/tf.py:617, src/devops_cli/commands/tf.py:623, src/devops_cli/tf/analysis.py:411, src/devops_cli/tf/analysis.py:417, src/devops_cli/tf/analysis.py:424]
  • How does the CLI learn that the plan holds drift?: Add -detailed-exitcode to the refresh-only plan and read exit code 2 as a drift signal. The command also exits 2 when the drift report's drift_detected is true. That covers a declared resource that is absent from state, which a refresh-only plan can return as 0. (best practice) [sources: src/devops_cli/tf/analysis.py:388, src/devops_cli/tf/analysis.py:417]
    • Chosen: detailed-exitcode and report divergence. OpenTofu returns 2 for a plan with changes. The report covers a declared resource that is absent from state, which the plan code alone misses.
    • Rejected: detailed-exitcode only. A refresh-only plan returns 0 for a declared resource that is absent from state. The command would then print a drift table and exit 0.
    • Rejected: Parse the tofu plan -json stream. The stream holds UI messages; the saved plan's resource_drift is the stable structure.
    • Rejected: Compare resources in Python. Only the provider refresh shows attribute drift, and the repository already runs it.
  • How does the CLI read the check results?: Save the plan with -out=<temporary file>. Run tofu show -json <file> in the stack directory. Read the top-level checks array. Each entry names the check at address.to_display and gives status as pass, fail, error or unknown. fail and error go to failed_checks; unknown goes to unknown_checks. Delete the temporary directory in a finally block. (best practice) [sources: src/devops_cli/tf/analysis.py:411]
    • Chosen: Saved plan and tofu show -json. The plan JSON representation holds the checks results and the exact plan that the exit code describes.
    • Rejected: Parse the tofu plan -json stream. The stream holds UI messages, not the checks array.
    • Rejected: Parse the text output of tofu plan. The warning text has no stable format and no check address.
  • Which exit codes does the command use, and which code wins when drift and a failed check occur together?: Use 0 when the plan returns 0, each check passes and the report holds no divergence. Use 1 for a failed or unknown check or a plan error. Use 2 for drift. A failed or unknown check wins over drift, because the plan cannot be trusted to describe the drift. The report is printed before the exit, as devops config audit-keys does. (best practice) [sources: openspec/changes/archive/2026-10-28-1469-audit-keys-leak-exit-code/design.md:20, openspec/changes/archive/2026-10-28-1469-audit-keys-leak-exit-code/design.md:32, src/devops_cli/commands/tf.py:615]
    • Chosen: 1 for a check, 2 for drift, check wins. It keeps OpenTofu's 0/1/2 plan codes, reports a check error before a drift finding, and follows the project's exit-1 gate of config audit-keys.
    • Rejected: 2 for both. It hides the difference between a drift finding and a check error.
    • Rejected: 3 for a check. No project convention gives 3, and OpenTofu's plan codes are 0, 1 and 2.
    • Rejected: 2 for drift even when a check fails. A failed check means the plan is not trustworthy; the error code must win.
  • How does the drift plan get -lock=false?: read_plan_drift adds -lock=false to the refresh-only plan each time. The drift plan reads state and changes nothing, so it must not hold the state lock. No command option exposes the lock. (best practice) [sources: src/devops_cli/tf/analysis.py:417]
    • Chosen: Always -lock=false. A drift plan is read-only, and no caller needs the lock.
    • Rejected: A --lock/--no-lock option on devops tf drift. The command never applies a plan, so the option has no use.
    • Rejected: A generic pass-through of tofu arguments. The parent item feat(gh): manage GitHub organization and repository settings as code #5311 plans the pass-through as its own pull request.
  • What does read_plan_drift return to tf_drift?: Add a PlanDriftResult model in src/devops_cli/models/tf.py. It holds drifted, failed_checks, unknown_checks, plan_returncode and plan_error. It follows the shape of TFLintResult and TFOutputResult. tf_drift passes drifted to detect_drift, prints the check lists and the plan error, and uses plan_returncode for the exit. (best practice) [sources: src/devops_cli/models/tf.py:91, src/devops_cli/models/tf.py:62, src/devops_cli/commands/tf.py:33, src/devops_cli/tf/analysis.py:411]
    • Chosen: A result model. The models file already holds the result types that tf.py imports, and the typed fields keep the plan return code, drift and checks apart.
    • Rejected: A tuple of lists. A caller cannot tell the fields apart.
    • Rejected: Raise on drift. Drift is data that the table shows, not an error.
  • Do the tests need a live tofu binary?: No. ADR 0007 requires a test of src/ to start no program. The test doubles the process edge with recorded JSON for the four cases: clean, drift, failed check and unknown check. The image and CI do install OpenTofu 1.13.9. A live run would need a provider and a live stack and would not be repeatable. (best practice) [sources: docs/adr/0007-tests-double-only-process-edges.md:10, docs/adr/0007-tests-double-only-process-edges.md:30, tests/tf/test_tf_analysis.py:756, .github/workflows/ci.yml:80]
    • Chosen: Offline tests with recorded JSON. ADR 0007 forbids a test of src/ from starting a program, and the fixtures make the four cases repeatable.
    • Rejected: A live tofu run in CI. It needs a provider and a live stack, and it is not repeatable offline.
  • How are the new exit codes documented?: The devops tf drift docstring states the 0, 1 and 2 meanings. The pull request regenerates the generated command page with uv run devops docs generate. The docs row of the gate proves freshness with uv run devops ci --check --only docs. (best practice) [sources: docs/adr/0025-generated-documents-stay-in-git-and-the-project-brain-cites-them.md:19, docs/adr/0014-required-checks-gate-the-merge-and-the-pre-push-hook-runs-the-fast-static-checks.md:78, docs/commands/tf.md:217, src/devops_cli/commands/tf.py:583]
    • Chosen: State the codes in the docstring and regenerate. The project's generated command pages come from the docstrings, and the docs row fails a stale page.
    • Rejected: Leave the help unchanged. A caller cannot learn the exit-code contract from the command, and the issue's point is a CI gate.

Fit

Fits in one pull request.

Suspected block

None.

Dependencies

#5318

Activity

  1. added
    source/agent
    on Nov 13, 2026
  2. added
    type/bug
    status/new
    value/medium
    effort/medium
    on Nov 13, 2026
  3. dan-petty commented on Nov 13, 2026

    @dan-petty
    OwnerAuthor
    • Scope: none. The title has the scope tf, and .github/labels.yml declares no scope/tf label. Add the label to the file to give the scope to this item.
    • Related: feat(infra): report drift of an infra repo #5127, which asks for a different change. Both report drift, but #5127 covers infra repo hosts while this covers terraform stacks via tf drift.
  4. added
    priority/p2-medium
    on Nov 13, 2026
  5. devops-cli-service commented on Nov 16, 2026

    @devops-cli-service
    Contributor

    Alternatives check: in-use

    Reason: The searches found that OpenTofu itself already provides every mechanism this item needs: tofu plan -refresh-only -detailed-exitcode returns exit code 2 when the plan holds changes (drift), -lock=false runs the plan without taking the state lock, and tofu show -json of a saved plan exposes the checks results the CLI can read to set a non-zero exit on a failed or unknown check. The issue already names tofu as the engine the project runs ("tofu does all of the work", "passes to tofu", "tofu show -json"), so the item is wiring OpenTofu's own flags and JSON output rather than adopting a new tool.

    The repository already uses this tool.

    Tool: opentofu/opentofu (https://github.com/opentofu/opentofu)

    • License: MPL-2.0
    • Last activity: 2026-11-16
    • Maintained: yes

    Covers:

    • tofu plan -refresh-only -detailed-exitcode returns exit code 2 when the plan contains changes (drift), distinct from 0 (clean) and 1 (error)
    • tofu plan -lock=false runs the refresh-only plan without taking the state lock
    • tofu show -json of the saved plan exposes the checks results (pass / fail / unknown) for the CLI to read and turn into a non-zero exit

    Tools considered:

    Searches run:

    • python library run tofu plan json parse checks exit code, results: 5
    • open source tool detect terraform drift exit non-zero CI, results: 5
    • OpenTofu plan -detailed-exitcode drift exit code 2, results: 5
    • tofu show -json checks output plan check blocks, results: 5
    • opentofu plan -detailed-exitcode -lock=false options documentation, results: 5
    • OpenTofu plan detailed-exitcode exit code 2 changes, results: 5
    • OpenTofu JSON output format checks section show -json, results: 5
    • OpenTofu CLI plan "-lock=false" state lock option, results: 5
    • OpenTofu JSON output format checks failed check status, results: 5

    Sources:

    Checked on 2026-11-16. A person decides what this means for the item. The check changes no label and closes no issue.

  6. devops-cli-service commented on Nov 17, 2026

    @devops-cli-service
    Contributor

    Refine cannot set this item to Ready at 1774ebf while the items below stay open. The next refine round looks at the item again when they close, or when a person replies in a comment or edits the body.

  7. added
    status/ready
    and removed
    status/new
    on Nov 25, 2026
  8. devops-cli-service commented on Nov 25, 2026

    @devops-cli-service
    Contributor

    Next step: the stage job writes the plan of the item. See the section Proposed design of the body.

  9. added
    status/in-review
    and removed
    status/ready
    on Nov 25, 2026
  10. removed
    status/in-review
    on Nov 25, 2026
  11. devops-cli-service commented on Nov 25, 2026

    @devops-cli-service
    Contributor
  12. devops-cli-service commented on Nov 25, 2026

    @devops-cli-service
    Contributor

    Live since 2026-11-25 17:24 UTC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    effort/mediumpriority/p2-mediumsource/agenttype/bugvalue/medium

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions