Repository navigation
Exit 2 from a direct run that wrote no report - #52
Merged
stefoy merged 5 commits intoNov 25, 2026
Merged
Conversation
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.
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
# Conflicts: # README.md
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
…report-exit-code)
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Related to #22: a direct
ResourceInventory.ps1run that ends without writing its report zip now exits2with a redNo report was writtenline, instead of naming the missing zip as its output and exiting0. A run that stops during setupnow exits
1instead of0, 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 ofResourceInventory.ps1without having written thereport zip. It then prints the zip it did not write on the green
Reporting Data File:line and exits0, so automation thatchecks the exit code sees a successful run with no report.
Reproduced offline on
mainwith five collectors that throw, placed ahead of one that works (the collector circuit breakerstops collection after 5 failures in a row), using the real script with stand-ins for the Azure calls:
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:andReporting Data File: <out>/ResourcesReport_<timestamp>.zip.0.Why the run gets that far:
$ErrorActionPreferenceisSilentlyContinueunless-Debugis set, and under that setting athrowends only the top-level statement it is in. The breaker's throw ends thetry { ExecuteInventoryProcessing } finally { ... }statement before the Inventory JSON is written.Summary.ps1then fails,Compress-Archivefails because the HTMLfile is missing, and the last three lines print as they do after a good run.
The same ending follows when
Summary.ps1throws for another reason (reproduced with aSummary.ps1that throws: no HTML, nozip, exit
0) and, from reading thecatcharoundCompress-Archive, when the zip itself cannot be written.A run can also end with no report and exit
0much earlier, during setup. Each of these was reproduced offline onmainwiththe real script; the first, fourth and fifth also on Azure:
pwsh ./rda/ResourceInventory.ps1):Local Version.json not found. Clone the repo and execute the script from the root. Exiting., exit0. The script reads./Version.jsonfrom the current folder, while every otherfile it loads is found next to the script.
Azure CLI Not Found. Please install and run the script again., exit0.-TenantIDand-Appidbut no-Secret:You are trying to use Service Principal Authentication Method in a wrong way., exit0.-ResourceGroupwithout-SubscriptionID(as in the README's resource group example):Resource Group Name present, but missing Subscription ID., exit0.-OutputDirectorythat cannot be created:Pre-flight checks passed., thenWrong OutputDirectory Path! ..., exit0.The pre-flight write probe is meant to catch an unusable output folder, but it ends with a top-level
throw, which is ignoredfor the reason above. With a read-only
-OutputDirectorythe run printsPre-flight checks passed., signs in, collects thewhole subscription, and only then fails to write anything (with the change above, exit
2).Under
-RunAllSubsthe setup stops matter too: the wrapper calls the script in the same process and treats exit0as acompleted subscription, so a run that stopped in setup is recorded as completed and
-Resumedoes not collect it again.Change
ResourceInventory.ps1: just before theReporting 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-OutputDirectorythat does not resolve, the serviceprincipal sign-in without a secret,
-ResourceGroupwithout-SubscriptionID) print the same messages as before and exit1instead of
0.1is 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, therun prints
ERROR: Pre-flight: cannot write to <folder>: <reason>. ...in red and exits1before sign-in.Functions/ResourceInventory.Functions.ps1:Version.jsonis read from the script's folder, asRun-AllSubscriptions.ps1already does, so a run started from another folder runs normally. If
Version.jsonis really missing there, the run stopswith
Local Version.json not found at <path>. ...and exit1.These are behaviour changes. The exact conditions, all for a direct run unless stated:
-RunAllSubs, and at the end of the run$Global:ZipOutputFileis empty orTest-Path -LiteralPathfinds no filethere: exit
2(was0);1(was0); under-RunAllSubsthe script then also returns1to the wrapper,which records a failed subscription instead of a completed one;
1before sign-in (was: the whole run, then2; onmain,0);I decided this. There is no switch to keep the old exit codes.
2is the codeRun-AllSubscriptions.ps1already uses whena subscription's output zip is missing.
Every run that writes its zip ends as before, with
Reporting Data File:and exit0. That includes a subscription with noresources and a
-Servicefilter whose collectors find nothing. With-Debug, the breaker and a failingSummary.ps1stillstop at their
throwwith exit1, as before.Under
-RunAllSubsthe end-of-run check does not apply: all three places the wrapper callsResourceInventory.ps1treat anynon-zero exit as a failed subscription, and the wrapper already checks each subscription's zip (its own exit code
2). Thewrapper passes
-SubscriptionIDand no-OutputDirectory, signs in itself and checks for the Azure CLI first, so of thesetup stops only a missing
Version.jsoncan 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:2means no report was written, and4means the report was written but a collector failed. The two never overlap: thisPR's
exit 2fires only when the zip does not exist, #51'sexit 4only when it does. In the merged script this PR's checkcomes before the
Reporting Data File:line and #51'sexit 4after it. The merge conflicts inREADME.mdonly. Theresolution is one table with the rows below, where #51's
0row drops its sentence about checking that the zip exists:01-Servicematched no collector, the-ObfuscationDictionaryfile 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-ResourceGroupis given without-SubscriptionID.2No report was written; the errors printed before it give the cause.4Services/*/*.ps1collectors failed. Those resource types are missing (not empty) from the report; its "Incomplete collection" banner names them.followed by: "Under
-RunAllSubs, which is howRun-AllSubscriptions.ps1calls it, the script exits neither2nor4;the wrapper reports a missing zip with its own code
2and collector failures with its own code4above. A setup stop stillexits
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.ps1in a childpwshwith-SkipMetrics -SkipConsumptionand offline stand-ins for the Azure CLI and Az calls. It checks: five failing collectors ina row -> no zip, the last line is
No report was written: ..., after the lastCollector FAILEDline, noReporting Data File:line, exit2; aSummary.ps1that throws -> no zip, exit2; a normal run -> zip, last lineReporting Data File:, exit0; a subscription with no resources -> zip, exit0; five failing collectors under-RunAllSubs-> exit0and theReporting Data File:line as before. For setup: an output folder that cannot be written-> the
ERROR: Pre-flight: cannot write toline, noPre-flight checks passed., no collection, exit1; no Azure CLI onPATH, a service principal sign-in without a secret,-ResourceGroupwithout-SubscriptionID, and a copy withoutVersion.json-> their message and exit1; the same missingVersion.jsonunder-RunAllSubs->1returned to thecaller; a run started from another folder -> zip and exit
0, also under-RunAllSubs.On
main4 pass and 11 fail (Expected 2, but got 0.,Expected 1, but got 0.); on this branch all 15 pass. The harnessalso 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:
main269 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.mdconflicts as described above,ResourceInventory.ps1mergescleanly, 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:Local Version.json not found. ..., no zip, exit0; now the whole run, the reportand zip written, exit
0.-ResourceGroupwithout-SubscriptionID:Resource Group Name present, but missing Subscription ID.on both; exit0before,
1now.-OutputDirectorythat cannot be created (a folder under/): before,Pre-flight checks passed., thenWrong OutputDirectory Path! ..., exit0; nowERROR: Pre-flight: cannot write to ..., exit1.-OutputDirectory: before,Pre-flight checks passed., sign-in and a full collection, thenNo report was written: ..., exit2; nowERROR: Pre-flight: cannot write to ...and exit1after 2 seconds, beforesign-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
mainand once on this PR before the setup changes (-SkipMetrics -SkipConsumption): exit0both times, the HTML report andzip written both times, the same
Collector FAILED: VMSSline (the date bug that Fix VMSS collector failing on Flexible scale sets #39 fixes), and the same 452 inventoryrecords, 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 atemporary folder.
From the repository root:
main:Tests Passed: 4, Failed: 11, for exampleExpected 2, but got 0.,Expected 1, but got 0.andExpected regular expression 'No report was written: ' to match '[12345678] Reporting Data File: ...Tests Passed: 15, Failed: 0.(Of these steps, the two
Invoke-Pestercommands were run as written, on local exports ofmainwith the test file and ofthis branch; the
git fetchof 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 onlyread from Azure. Run them from the repository root unless a step says otherwise, on
mainand on this branch:main,Local Version.json not found. ...andexit code: 0with no zip; on this branch, the last line isReporting Data File: <out>/ResourcesReport_<timestamp>.zip, that zip exists, andexit code: 0.main,Resource Group Name present, but missing Subscription ID.andexit code: 0; on this branch the same lineand
exit code: 1.main,Pre-flight checks passed., the whole collection, andexit code: 0with no zip; on this branch,ERROR: Pre-flight: cannot write to <ro-out>: ...straight after the pre-flight lines, andexit code: 1.(These three cases were run on Azure through a small script that looks up the subscription and calls
ResourceInventory.ps1the 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
mainlines for 1 to 3 are from the previous head, whose setup code is the same asmain's, except that in 3the 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.ps1andRun-AllSubscriptions.Stream.ps1: no edits. Under-RunAllSubsthe inner script ends asbefore, apart from a setup stop now returning
1.-Debugits ownStopping: 5 collectors failed in a row ...message is still not printed, so in that case the lines beforeNo report was writtenare the fiveCollector FAILEDlines and the HTML report error.CheckPowerShellkeeps its bareExit: it sits after the dot-sourcedFunctions/ResourceInventory.Functions.ps1, which starts with#Requires -Version 7.0, and it was not reproduced here.throw, so it still does not stop the run. A runwith that little space can still complete for a small subscription; making it stop would be a new stop.