Skip to content

Exit 2 from a direct run that wrote no report - #52

Merged
stefoy merged 5 commits into
awslabs:mainfrom
pmorgenrood:upstream-pr/no-report-exit-code
Nov 25, 2026
Merged

stefoy merged 5 commits into
awslabs:mainfrom
pmorgenrood:upstream-pr/no-report-exit-code

Conversation

@pmorgenrood

@pmorgenrood pmorgenrood commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Related to #22: a direct ResourceInventory.ps1 run that ends without writing its report zip now exits 2 with a red
No report was written line, instead of naming the missing zip as its output and exiting 0. A run that stops during setup
now exits 1 instead of 0, and a run whose output folder cannot be written stops before sign-in instead of after collection.

Problem

On main, a direct run (without -RunAllSubs) can reach the last line of ResourceInventory.ps1 without having written the
report zip. It then prints the zip it did not write on the green Reporting Data File: line and exits 0, so automation that
checks the exit code sees a successful run with no report.

Reproduced offline on main with five collectors that throw, placed ahead of one that works (the collector circuit breaker
stops collection after 5 failures in a row), using the real script with stand-ins for the Azure calls:

  • Console, in order: five Collector FAILED: ... lines,
    HTML report generation FAILED: Summary.ps1: Inventory JSON not found at '<out>/Inventory_<timestamp>.json'.,
    The Inventory/Metrics/Consumption data files were still written to <out>/, but no HTML report or zip was produced for this run.,
    then Execution Time: ..., Reporting Time: and Reporting Data File: <out>/ResourcesReport_<timestamp>.zip.
  • Output folder: no HTML report, no zip. Exit code 0.

Why the run gets that far: $ErrorActionPreference is SilentlyContinue unless -Debug is set, and under that setting a
throw ends only the top-level statement it is in. The breaker's throw ends the try { ExecuteInventoryProcessing } finally { ... } statement before the Inventory JSON is written. Summary.ps1 then fails, Compress-Archive fails because the HTML
file is missing, and the last three lines print as they do after a good run.

The same ending follows when Summary.ps1 throws for another reason (reproduced with a Summary.ps1 that throws: no HTML, no
zip, exit 0) and, from reading the catch around Compress-Archive, when the zip itself cannot be written.

A run can also end with no report and exit 0 much earlier, during setup. Each of these was reproduced offline on main with
the real script; the first, fourth and fifth also on Azure:

  • Started from another folder (pwsh ./rda/ResourceInventory.ps1): Local Version.json not found. Clone the repo and execute the script from the root. Exiting., exit 0. The script reads ./Version.json from the current folder, while every other
    file it loads is found next to the script.
  • No Azure CLI on the machine: Azure CLI Not Found. Please install and run the script again., exit 0.
  • A service principal sign-in with -TenantID and -Appid but no -Secret: You are trying to use Service Principal Authentication Method in a wrong way., exit 0.
  • -ResourceGroup without -SubscriptionID (as in the README's resource group example): Resource Group Name present, but missing Subscription ID., exit 0.
  • An -OutputDirectory that cannot be created: Pre-flight checks passed., then Wrong OutputDirectory Path! ..., exit 0.

The pre-flight write probe is meant to catch an unusable output folder, but it ends with a top-level throw, which is ignored
for the reason above. With a read-only -OutputDirectory the run prints Pre-flight checks passed., signs in, collects the
whole subscription, and only then fails to write anything (with the change above, exit 2).

Under -RunAllSubs the setup stops matter too: the wrapper calls the script in the same process and treats exit 0 as a
completed subscription, so a run that stopped in setup is recorded as completed and -Resume does not collect it again.

Change

  • ResourceInventory.ps1: just before the Reporting Data File: line, a direct run whose zip does not exist prints, in red,
    No report was written: <out>/ResourcesReport_<timestamp>.zip was not created. See the errors above, fix the cause and re-run.
    and exits 2.

  • ResourceInventory.ps1: the setup stops above (Azure CLI not found, an -OutputDirectory that does not resolve, the service
    principal sign-in without a secret, -ResourceGroup without -SubscriptionID) print the same messages as before and exit 1
    instead of 0. 1 is the code the other pre-flight stops (-Service, -ObfuscationDictionary) already use.

  • ResourceInventory.ps1: when the pre-flight write probe cannot write, read back or delete its file in the output folder, the
    run prints ERROR: Pre-flight: cannot write to <folder>: <reason>. ... in red and exits 1 before sign-in.

  • Functions/ResourceInventory.Functions.ps1: Version.json is read from the script's folder, as Run-AllSubscriptions.ps1
    already does, so a run started from another folder runs normally. If Version.json is really missing there, the run stops
    with Local Version.json not found at <path>. ... and exit 1.

  • These are behaviour changes. The exact conditions, all for a direct run unless stated:

    • no -RunAllSubs, and at the end of the run $Global:ZipOutputFile is empty or Test-Path -LiteralPath finds no file
      there: exit 2 (was 0);
    • one of the setup messages above: exit 1 (was 0); under -RunAllSubs the script then also returns 1 to the wrapper,
      which records a failed subscription instead of a completed one;
    • the write probe fails: exit 1 before sign-in (was: the whole run, then 2; on main, 0);
    • the current folder is not the script's folder: the run now proceeds instead of stopping.

    I decided this. There is no switch to keep the old exit codes. 2 is the code Run-AllSubscriptions.ps1 already uses when
    a subscription's output zip is missing.

  • Every run that writes its zip ends as before, with Reporting Data File: and exit 0. That includes a subscription with no
    resources and a -Service filter whose collectors find nothing. With -Debug, the breaker and a failing Summary.ps1 still
    stop at their throw with exit 1, as before.

  • Under -RunAllSubs the end-of-run check does not apply: all three places the wrapper calls ResourceInventory.ps1 treat any
    non-zero exit as a failed subscription, and the wrapper already checks each subscription's zip (its own exit code 2). The
    wrapper passes -SubscriptionID and no -OutputDirectory, signs in itself and checks for the Azure CLI first, so of the
    setup stops only a missing Version.json can occur under it.

  • README.md: a short "Exit Codes 1 and 2 (ResourceInventory.ps1, direct run)" section under the wrapper's exit-code table.

How this combines with #51, which adds a table of the direct run's exit codes (0, 1, 4) at the same place in the README:
2 means no report was written, and 4 means the report was written but a collector failed. The two never overlap: this
PR's exit 2 fires only when the zip does not exist, #51's exit 4 only when it does. In the merged script this PR's check
comes before the Reporting Data File: line and #51's exit 4 after it. The merge conflicts in README.md only. The
resolution is one table with the rows below, where #51's 0 row drops its sentence about checking that the zip exists:

Code Meaning
0 Completed and the report and zip were written; no collector failed.
1 A pre-flight or setup check stopped the run before collection, and the red error line printed before it gives the cause: for example -Service matched no collector, the -ObfuscationDictionary file is missing or not valid JSON, the output folder cannot be written, the Azure CLI is not installed, a service principal sign-in has no -Secret, or -ResourceGroup is given without -SubscriptionID.
2 No report was written: the run ended without its zip, for example because 5 collectors failed in a row and collection stopped, or because the HTML report or the zip could not be written. The last console line says No report was written; the errors printed before it give the cause.
4 Completed and the report and zip were written, but one or more Services/*/*.ps1 collectors failed. Those resource types are missing (not empty) from the report; its "Incomplete collection" banner names them.

followed by: "Under -RunAllSubs, which is how Run-AllSubscriptions.ps1 calls it, the script exits neither 2 nor 4;
the wrapper reports a missing zip with its own code 2 and collector failures with its own code 4 above. A setup stop still
exits 1, and the wrapper counts that subscription as failed."

Testing

  • Tests/NoReportExitCode.Tests.ps1 (15 tests). It copies the script to a temporary folder, adds small collectors there
    (one returns a record, the others throw) and runs the real ResourceInventory.ps1 in a child pwsh with
    -SkipMetrics -SkipConsumption and offline stand-ins for the Azure CLI and Az calls. It checks: five failing collectors in
    a row -> no zip, the last line is No report was written: ..., after the last Collector FAILED line, no
    Reporting Data File: line, exit 2; a Summary.ps1 that throws -> no zip, exit 2; a normal run -> zip, last line
    Reporting Data File:, exit 0; a subscription with no resources -> zip, exit 0; five failing collectors under
    -RunAllSubs -> exit 0 and the Reporting Data File: line as before. For setup: an output folder that cannot be written
    -> the ERROR: Pre-flight: cannot write to line, no Pre-flight checks passed., no collection, exit 1; no Azure CLI on
    PATH, a service principal sign-in without a secret, -ResourceGroup without -SubscriptionID, and a copy without
    Version.json -> their message and exit 1; the same missing Version.json under -RunAllSubs -> 1 returned to the
    caller; a run started from another folder -> zip and exit 0, also under -RunAllSubs.
    On main 4 pass and 11 fail (Expected 2, but got 0., Expected 1, but got 0.); on this branch all 15 pass. The harness
    also stands in for the up-front read-access check that Check read access and usage values up front for every subscription #38 adds (the token, role assignment, role definition and
    permissions requests answer as for a Reader assignment on the subscription, and any other Resource Manager call fails), so
    the test passes with or without Check read access and usage values up front for every subscription #38.

  • Full Pester suite: main 269 passed / 162 failed / 22 skipped; this branch 284 / 162 / 22, the same failing tests by name.
    PSScriptAnalyzer with the repository settings reports nothing on the changed files.

  • Trial merge with Report: name failed collectors, count consolidated subscriptions #51's head, in both orders: README.md conflicts as described above, ResourceInventory.ps1 merges
    cleanly, and both orders give the same tree. On the merge, this PR's tests (15) and Report: name failed collectors, count consolidated subscriptions #51's Tests/DirectRunExitCode.Tests.ps1
    (9) and Tests/CollectorFailureBanner.Tests.ps1 (8) all pass.

  • Live, direct runs on a test subscription (read-only, metrics and consumption on), on this PR's previous head (the same setup
    code as main) and on this branch:

    • started from another folder: before, Local Version.json not found. ..., no zip, exit 0; now the whole run, the report
      and zip written, exit 0.
    • -ResourceGroup without -SubscriptionID: Resource Group Name present, but missing Subscription ID. on both; exit 0
      before, 1 now.
    • an -OutputDirectory that cannot be created (a folder under /): before, Pre-flight checks passed., then
      Wrong OutputDirectory Path! ..., exit 0; now ERROR: Pre-flight: cannot write to ..., exit 1.
    • a read-only -OutputDirectory: before, Pre-flight checks passed., sign-in and a full collection, then
      No report was written: ..., exit 2; now ERROR: Pre-flight: cannot write to ... and exit 1 after 2 seconds, before
      sign-in.

    The Azure CLI and service principal cases were reproduced offline only. Earlier, for the end-of-run check alone: a direct run
    once on main and once on this PR before the setup changes (-SkipMetrics -SkipConsumption): exit 0 both times, the HTML report and
    zip written both times, the same Collector FAILED: VMSS line (the date bug that Fix VMSS collector failing on Flexible scale sets #39 fixes), and the same 452 inventory
    records, compared record by record.

How to test

Quick check (no Azure)

Needs PowerShell 7 and Pester 5 (Install-Module Pester -MinimumVersion 5.0 -Scope CurrentUser). The tests write only to a
temporary folder.

From the repository root:

git fetch origin main pull/52/head:pr-no-report-exit

# main's code with this PR's test file
git worktree add ../rda-main origin/main
git -C ../rda-main checkout pr-no-report-exit -- Tests/NoReportExitCode.Tests.ps1
(cd ../rda-main && pwsh -NoProfile -Command "Invoke-Pester -Path ./Tests/NoReportExitCode.Tests.ps1 -Output Detailed")
git worktree remove --force ../rda-main

# this PR
git checkout pr-no-report-exit
pwsh -NoProfile -Command "Invoke-Pester -Path ./Tests/NoReportExitCode.Tests.ps1 -Output Detailed"
  • On main: Tests Passed: 4, Failed: 11, for example Expected 2, but got 0., Expected 1, but got 0. and
    Expected regular expression 'No report was written: ' to match '[12345678] Reporting Data File: ...
  • On this branch: Tests Passed: 15, Failed: 0.

(Of these steps, the two Invoke-Pester commands were run as written, on local exports of main with the test file and of
this branch; the git fetch of the PR head and the worktree steps were not.)

Check on Azure (read-only)

Needs PowerShell 7 with the Az modules signed in (Connect-AzAccount) and the Azure CLI signed in (az login). The runs only
read from Azure. Run them from the repository root unless a step says otherwise, on main and on this branch:

# 1. a normal run, started from another folder
(cd /tmp && pwsh -NoProfile -File "$OLDPWD/ResourceInventory.ps1" -SubscriptionID <sub-id> -SkipMetrics -SkipConsumption -OutputDirectory <out> < /dev/null; echo "exit code: $?")

# 2. -ResourceGroup without -SubscriptionID
pwsh -NoProfile -File ./ResourceInventory.ps1 -ResourceGroup <resource-group> -OutputDirectory <out> < /dev/null; echo "exit code: $?"

# 3. an output folder that cannot be written
mkdir -p <ro-out> && chmod 555 <ro-out>
pwsh -NoProfile -File ./ResourceInventory.ps1 -SubscriptionID <sub-id> -SkipMetrics -SkipConsumption -OutputDirectory <ro-out> < /dev/null; echo "exit code: $?"
  • 1: on main, Local Version.json not found. ... and exit code: 0 with no zip; on this branch, the last line is
    Reporting Data File: <out>/ResourcesReport_<timestamp>.zip, that zip exists, and exit code: 0.
  • 2: on main, Resource Group Name present, but missing Subscription ID. and exit code: 0; on this branch the same line
    and exit code: 1.
  • 3: on main, Pre-flight checks passed., the whole collection, and exit code: 0 with no zip; on this branch,
    ERROR: Pre-flight: cannot write to <ro-out>: ... straight after the pre-flight lines, and exit code: 1.

(These three cases were run on Azure through a small script that looks up the subscription and calls ResourceInventory.ps1
the same way, with metrics and consumption on, on this PR's previous head and on this branch; the commands above were not run
as written. The main lines for 1 to 3 are from the previous head, whose setup code is the same as main's, except that in 3
the previous head already ends with exit code: 2.)

The no-report case needs 5 collectors to fail in a row, which the offline test sets up; it has not been reproduced on Azure.

Not changed

  • Run-AllSubscriptions.ps1 and Run-AllSubscriptions.Stream.ps1: no edits. Under -RunAllSubs the inner script ends as
    before, apart from a setup stop now returning 1.
  • The collector circuit breaker: it still stops collection before the inventory is written. Without -Debug its own
    Stopping: 5 collectors failed in a row ... message is still not printed, so in that case the lines before
    No report was written are the five Collector FAILED lines and the HTML report error.
  • The PowerShell 7 check in CheckPowerShell keeps its bare Exit: it sits after the dot-sourced
    Functions/ResourceInventory.Functions.ps1, which starts with #Requires -Version 7.0, and it was not reproduced here.
  • The pre-flight free-space check (under 100 MB) still ends with a top-level throw, so it still does not stop the run. A run
    with that little space can still complete for a small subscription; making it stop would be a new stop.

Peter-John Morgenrood added 2 commits October 28, 2026 09:04
A direct ResourceInventory.ps1 run can reach its last line without writing
the report zip, for example when 5 collectors failed in a row and collection
stopped, or when the HTML report could not be built. It then printed the
missing zip on its "Reporting Data File:" line and exited 0. It now ends
with a red "No report was written" line and exits 2, the code
Run-AllSubscriptions.ps1 already uses for a missing output zip.

A run that writes its zip, including one over a subscription with no
resources, still exits 0. Under -RunAllSubs nothing changes: the wrapper
treats any non-zero exit as a failed subscription and checks each
subscription's zip itself.

README documents the direct run's exit code 2.
Tests/NoReportExitCode.Tests.ps1 runs the real script with offline
stand-ins for Azure.
A direct run that checks read access up front through Resource Manager
before any collector runs found no answer for those calls in the harness,
so every direct run stopped with exit 1 before collection. The harness now
answers the token, role assignment, role definition and permissions requests
as for a Reader assignment on the subscription, so the subscription is
readable and the run reaches the collectors. Any other Resource Manager call
fails in the harness. A run without that check makes none of these calls,
so the test passes with or without it.
Peter-John Morgenrood added 2 commits October 28, 2026 17:59
Five setup stops ended with a bare Exit, which gives exit code 0 and no
report: Version.json not found, the Azure CLI not installed, an
-OutputDirectory that does not resolve, a service principal sign-in with
no secret, and -ResourceGroup without -SubscriptionID. They now exit 1,
the code the other pre-flight stops already use.

The pre-flight write probe ended with a top-level throw, which the
default SilentlyContinue preference ignores, so a run whose output folder
could not be written printed "Pre-flight checks passed.", signed in,
collected everything and only then ended with no report. It now prints
the error in red and exits 1 before sign-in.

Under -RunAllSubs a setup stop now returns 1 to the wrapper, which counts
that subscription as failed instead of completed.
GetLocalVersion read ./Version.json from the current folder, so a run
started from any other folder (for example pwsh ./rda/ResourceInventory.ps1)
stopped with "Local Version.json not found" and no report, and a wrapper
started that way did the same for every subscription. Every other file the
script loads is already found next to the script, and Run-AllSubscriptions.ps1
already reads Version.json next to itself; the version is now read the same
way. A Version.json that is really missing still stops the run with exit 1.
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Oct 29, 2026
…ep state on a zip failure, no browser without a console

Review council findings on the merged candidate (gpt-5.6-sol, claude-opus-5.5):

- MAJOR, loop trap (awslabs#48 x awslabs#52 x awslabs#68): a subscription whose run wrote no
  report zip was taken off the completed list but never put on the retry
  list, so every -Resume collected it again, ended with exit 2 and kept the
  state; the retry limit never counted it. The sequential loop, the
  one-subscription path and the stream worker now record it as a failed run
  ("the run wrote no report zip"), so -ResumeFailedOnly retries it and the
  retry limit ends a cause that does not go away. awslabs#48's tests that asserted
  the old behaviour now expect the retry entry.
- MAJOR, pre-existing: Get-WrapperExitCode ignored $FailedSubscriptions, so
  a run with failed subscriptions exited 0 ("clean run"). It now returns 2
  (a report is missing from the bundle) and the README says so.
- MAJOR/MINOR (awslabs#63 x awslabs#48): the resume state was cleared even when the
  consolidated zip could not be built, so the next -Resume collected every
  subscription again. The state is now kept while $BundleBuildError is set.
- MAJOR (awslabs#66): the wrapper sign-in opened a browser with no console
  (scheduled task, CI). It now stops with exit 1 and advice, as a direct run
  does; -DeviceLogin and a reusable sign-in still work.

Each change has a test that failed before it (RetryLimit, WrapperSignIn,
RunAllSubscriptionsReconciliation).
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Oct 30, 2026
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Oct 30, 2026
…wslabs#59/awslabs#61/awslabs#64/awslabs#53/awslabs#56): run the offline harnesses on the Az PowerShell path

The child-process harnesses of these PRs answered sign-in, the subscription
list and Resource Graph through an 'az' stand-in. awslabs#66 drops the Azure CLI, so
that stand-in is never called. Tests/Helpers/AzPsStandIns.ps1 now gives every
harness Get-AzSubscription, Get-AzAccessToken -TenantId, a signed-in context
and Resource Graph paging through Invoke-AzRestMethod with skip tokens, and
answers each page from the harness's own graph stand-in (renamed
Invoke-StandInGraph). Discovery queries go through Invoke-DiscoveryGraphQuery
(awslabs#59), so the -HideRawOutput check reads those calls. awslabs#59's unparsable page is
now a cut-off page (an empty property name is kept since awslabs#66), and awslabs#52's setup
stop is shown with a missing Az module instead of a missing Azure CLI.
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Oct 30, 2026
…ep state on a zip failure, no browser without a console

Review council findings on the merged candidate (gpt-5.6-sol, claude-opus-5.5):

- MAJOR, loop trap (awslabs#48 x awslabs#52 x awslabs#68): a subscription whose run wrote no
  report zip was taken off the completed list but never put on the retry
  list, so every -Resume collected it again, ended with exit 2 and kept the
  state; the retry limit never counted it. The sequential loop, the
  one-subscription path and the stream worker now record it as a failed run
  ("the run wrote no report zip"), so -ResumeFailedOnly retries it and the
  retry limit ends a cause that does not go away. awslabs#48's tests that asserted
  the old behaviour now expect the retry entry.
- MAJOR, pre-existing: Get-WrapperExitCode ignored $FailedSubscriptions, so
  a run with failed subscriptions exited 0 ("clean run"). It now returns 2
  (a report is missing from the bundle) and the README says so.
- MAJOR/MINOR (awslabs#63 x awslabs#48): the resume state was cleared even when the
  consolidated zip could not be built, so the next -Resume collected every
  subscription again. The state is now kept while $BundleBuildError is set.
- MAJOR (awslabs#66): the wrapper sign-in opened a browser with no console
  (scheduled task, CI). It now stops with exit 1 and advice, as a direct run
  does; -DeviceLogin and a reusable sign-in still work.

Each change has a test that failed before it (RetryLimit, WrapperSignIn,
RunAllSubscriptionsReconciliation).
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Nov 17, 2026
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Nov 17, 2026
… failure, no browser without a console

Changes on the merged candidate:

- loop trap (awslabs#48 x awslabs#52 x awslabs#68): a subscription whose run wrote no
  report zip was taken off the completed list but never put on the retry
  list, so every -Resume collected it again, ended with exit 2 and kept the
  state; the retry limit never counted it. The sequential loop, the
  one-subscription path and the stream worker now record it as a failed run
  ("the run wrote no report zip"), so -ResumeFailedOnly retries it and the
  retry limit ends a cause that does not go away. awslabs#48's tests that asserted
  the old behaviour now expect the retry entry.
- pre-existing: Get-WrapperExitCode ignored $FailedSubscriptions, so
  a run with failed subscriptions exited 0 ("clean run"). It now returns 2
  (a report is missing from the bundle) and the README says so.
- (awslabs#63 x awslabs#48): the resume state was cleared even when the
  consolidated zip could not be built, so the next -Resume collected every
  subscription again. The state is now kept while $BundleBuildError is set.
- (awslabs#66): the wrapper sign-in opened a browser with no console
  (scheduled task, CI). It now stops with exit 1 and advice, as a direct run
  does; -DeviceLogin and a reusable sign-in still work.

Each change has a test that failed before it (RetryLimit, WrapperSignIn,
RunAllSubscriptionsReconciliation).
@stefoy
stefoy merged commit 30deec0 into awslabs:main Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants