Repository navigation
Check read access and usage values up front for every subscription - #38
Open
pmorgenrood wants to merge 77 commits into
Open
pmorgenrood wants to merge 77 commits into
pmorgenrood wants to merge 77 commits into
Conversation
added 5 commits
October 22, 2026 23:05
ProcessResourceResult serialised the whole inventory with one ConvertTo-Json call and piped the string to Out-File. On a large estate that string, built on top of the collector objects already in memory, can run out of memory. - Add Write-InventoryJson, which writes the inventory object one property (collector) at a time through a single StreamWriter, and call it from ProcessResourceResult instead of the pipeline. - The output is unchanged: the file is byte-for-byte what the previous pipeline wrote (UTF-8 without BOM, a one-element collector still written as an array, Version last, trailing newline, same depth limit). - The whole inventory is no longer built as one JSON string; the largest string is now one collector's JSON. - The file is written to a temporary file in the same folder and moved into place only when complete, so a failed write leaves no cut-off inventory; the temporary file is removed and the error re-thrown. - Add Tests/InventoryWrite.Tests.ps1: byte equality with the previous output, array and encoding details, no whole-document ConvertTo-Json call, relative path, replacing an existing file, and that a failed write throws and leaves neither the inventory nor the temporary file.
On a large estate the HTML report step ran out of memory while the collector output ($Global:SmaResources) and the raw discovery rows ($Global:Resources) were still held, although nothing reads either once the inventory is written. - Release both after ProcessResourceResult and run a full collection. - Keep the discovered resource count in $Global:ResourceCount. It is reset with $Global:Resources at the start of each run and set when discovery finishes, so an early exit never reports the previous subscription's count. - Run-AllSubscriptions.ps1 and Run-AllSubscriptions.Stream.ps1 read the per-subscription count from $Global:ResourceCount instead of counting $Global:Resources. - Tests: the count after a normal run, after an early exit and after a run that stopped once discovery had finished; the data is released before the report step; each wrapper call site records the count.
Extension/Metrics.ps1 builds a request definition for every metric of the estate before it makes the first Azure Monitor call and keeps all of them until the metrics phase ends. Each one was a 14-property [PSCustomObject] of about 2,640 bytes, so 80,000 attached disks (320,000 definitions) held about 806 MiB before any call. With a 2,600 MiB memory limit such a run ran out of memory while building them and wrote no metrics. - Add RdaMetricDefinition, a PowerShell class with the same 14 fields, and build every definition with it (all 41 places). One definition now takes about 185 bytes: about 56 MiB for the same 320,000. - The fields are untyped, so a missing value stays $null; a [string] field would turn it into ''. Definitions are created on the main thread only; the parallel workers just read their properties. - The output is unchanged: definitions are only read for their values, never serialised. For every resource type the script defines metrics for, with and without obfuscation and across two output files, the metrics files match the previous version record for record and field for field. - Add Tests/MetricDefinitions.Tests.ps1, which runs the real Metrics.ps1 against a deterministic stand-in for Get-AzMetric with no Azure calls: every definition is an RdaMetricDefinition, a missing subscription name stays $null, the output files match Tests/Fixtures/MetricDefinitions.Output.json (recorded from the previous version), and 40,000 disk definitions take under 1,000 bytes each (about 240 here, about 2,640 before).
Every Azure Monitor call adds a diagnostics record to $MetricDiagnostics. Only the summary at the end of the metrics phase reads these records, but they were kept for the whole phase, so memory grew with the number of calls. With a stand-in Get-AzMetric, retained heap grew by 99 MB over 40,000 calls (about 2.5 KB per call); with this change it grows by 9 MB, and no longer with the number of calls. - After each batch, once all of its parallel calls have finished, fold the batch's records on the main thread into running state that holds what the summary prints: the call total, the count per outcome, every non-success record and the five slowest records. Then clear the collection. Metric results are already written out and cleared per batch in the same way. - The per-batch verbose line and the summary read that running state. - Output is unchanged: the verbose lines, the summary lines and the metrics files are the same as before for the same calls. Calls with equal rounded durations were, and still are, listed in no fixed order. - Add Tests/MetricsDiagnostics.Tests.ps1. It runs Metrics.ps1 over 800 calls (four batches) against a stand-in Get-AzMetric with throttled, invalid-metric-name, empty and slow calls, and checks the verbose lines, the outcome counts (including a status seen only in the first batch), the non-success and slowest lists across batches, that nothing is returned to the pipeline, and that the call records are not all kept until the end of the phase. A second case checks the summary when there are no metric definitions.
Two kinds of missing access went unnoticed and produced a report that looked complete: - Get-UsageAggregates answers an identity that lacks Microsoft.Commerce/UsageAggregates/read with success and zero rows. The previous gate probed only the first subscription for one day and treated "no error" as access, so runs could finish with an empty consumption sheet. - The Reader check listed the subscription's resource groups. Azure filters that list to what the caller may see instead of refusing, so an identity that can read nothing passed and the run ended with an empty report. Direct runs of ResourceInventory.ps1 had no check. Before any inventory or metrics work, Run-AllSubscriptions.ps1 and direct runs of ResourceInventory.ps1 now check every subscription the run will process. Under -RunAllSubs the inner script does not repeat the checks; on -Resume only the remaining subscriptions are checked. - Role check: the identity's own role assignments (assignedTo, so group grants count) and their role definitions, combined with Azure's caller-permissions answer (Microsoft.Authorization/ permissions). Read access needs */read that the same role's notActions do not remove; for a -ResourceGroup run a role on that resource group is enough. A disagreement, or an answer still missing after retries, stops the run. When role assignments are not visible to the identity, the caller-permissions answer decides. Whether the roles allow reading usage is reported for information. - Usage values check, when consumption is requested: same cmdlet, options and 31-day window as the billing phase (one helper, Get-ConsumptionWindow). A subscription passes when at least one usage row has a quantity above zero. Zero rows, only zero quantities, a permission error, or an error that persists after bounded retries stops the run. Subscriptions with no resources are not checked. A stop is exit code 1 with every failing subscription and the fix. -AllowPartialAccess skips subscriptions that fail the role check and does not bypass the usage check. The context switch for the usage check is process-scoped, so the saved default subscription is not changed. The shared checks live in Functions/Common.Functions.ps1 and replace Get-ConsumptionAccessOutcome, Test-ConsumptionAccess, Get-SubscriptionAccessState and Test-SubscriptionAccessAll.
This was referenced Oct 27, 2026
added 5 commits
October 27, 2026 14:47
…n is confirmed; cap usage paging A subscription that holds resources but has no usage above zero in the 31-day window (a new subscription, only free resources such as network security groups, paused resources) stopped the run with NoRows or NoPositiveQuantity, although nothing was wrong with access. The consumption data check now takes the up-front role check records (new optional -RoleCheck parameter of Invoke-ConsumptionDataCheck; both Run-AllSubscriptions.ps1 and direct runs of ResourceInventory.ps1 pass them). When the outcome would be NoRows or NoPositiveQuantity and the role check found Microsoft.Commerce/UsageAggregates/read at the subscription or above in BOTH answers (the identity's role assignments and Azure's caller permissions), the subscription passes with the new outcome NoUsage. It is printed in yellow with the role and scope, the window, the typical causes and that its consumption sheet will be empty, and it is listed again at the end of the run by both scripts (Write-NoUsageSummary). Exit codes and parameters are unchanged. Everything else still stops with exit 1 as before: Denied, Error, and NoRows/NoPositiveQuantity when the usage permission was confirmed by only one answer, by neither, with role assignments not visible, only below the subscription, or when no role check record exists for the subscription. Invoke-ConsumptionValueProbe followed ContinuationToken without a limit. It now stops after -MaxPages pages (default 50, as Invoke-RoleCheckGet in the same file). Reaching the cap without a row above zero is NoPositiveQuantity, and the detail says only the first N pages were read, so the rule above applies to it. README and docs/consumption-data.md describe the new pass and what still stops. The direct-run test that expects exit 1 on zero usage now uses role assignments that are not visible, because with Reader in both answers that run now passes with a warning.
The -RunAllSubs direct-run test now also asserts that the inner script makes no usage (Get-UsageAggregates) and no resource-count call, so it fails if the usage check runs under -RunAllSubs. The test title is updated to match.
'does not keep every call record until the end of the phase' read $MetricDiagnostics.Count once, after the phase, so code that folded and cleared the records only after the last batch would still pass. The test now records how many call records are held each time the script dispatches the next batch and when it ends the phase, which is once after each of the four batches, and expects 0 every time. It does this by wrapping Write-RdaProgress in the scope the script runs in; the wrapper passes every call on unchanged.
… front - Read access now needs one role that reads every resource type. A role whose notActions remove reads of some resource types (a not-action ending in '*' or 'read', outside Microsoft.Authorization, Microsoft.Commerce, Microsoft.Consumption and Microsoft.Billing) no longer counts, because Resource Graph leaves those resources out without an error. The stop reason names the role and the excluded pattern; in Run-AllSubscriptions.ps1 -AllowPartialAccess skips such a subscription. - The consumption window is computed once per run. A direct run uses it for the up-front check and the consumption phase; Run-AllSubscriptions.ps1 passes it to every ResourceInventory.ps1 it starts (-ConsumptionWindowStart and -ConsumptionWindowEnd), so a subscription collected after midnight collects the window that was checked. - A direct -ResourceGroup run checks that resource group: only its usage rows count, by the same test the consumption phase keeps rows with (Test-ConsumptionResourceUriInResourceGroup), and Resource Graph's count is of that resource group. - When the usage check stops at its 50-page cap, the NoUsage and stop texts say only that no usage above zero was found in the pages read. - The role assignment list is followed for up to 1000 pages, and the stop message gives the fix for each cause: grant Reader, re-run, or wait 5 minutes and re-run. - A role definition whose read is refused (HTTP 401, 403 or 404) is not read again for later subscriptions; after a transient failure it is read again.
A not-action now counts as removing reads of some resource types when, with '*' standing for any characters (as Test-RoleActionPatternMatch reads it), it can match an action that ends in '/read': without '*' when it ends in '/read'; with '*' when the text after its last '*' is empty, is the end of '/read' or itself ends in '/read'. Patterns such as 'Microsoft.Comp*', 'Microsoft.Compute/*/r*' and '*ad' were missed before. A not-action is allowed only when the text before its first '*' starts with one of the allowed namespaces and '/', so 'Microsoft.Authorization/*' stays allowed and 'Microsoft.Auth*' counts. Adds a test that a -ResourceGroup collection skips a usage row without a resource URI and keeps collecting the subscription. The README describes the rule.
This was referenced Oct 27, 2026
added 3 commits
October 27, 2026 21:33
Test-ConsumptionResourceUriInResourceGroup looked for '/<name>/' anywhere in the resource URI, so resource group 'web' also matched /subscriptions/<id>/resourceGroups/prod/providers/Microsoft.Web/sites/web/slots/staging. The consumption data check could then pass a -ResourceGroup run on another resource group's usage, and the consumption phase kept that row in the resource group's sheet. Compare the name after /subscriptions/<id>/resourceGroups/ instead, without case.
Both up-front checks went through the subscriptions one after another, so their wall clock grew with every subscription. They now run up to 8 subscriptions at a time with ForEach-Object -Parallel (the pattern Extension/Metrics.ps1 uses) and print one line per subscription in subscription order, as before. Nothing in the parallel part reads or changes the Azure context: - The role check already named the subscription in every request. Role definitions stay cached for the whole run; a definition not yet cached is read under the cache's lock, so each is still read once. - The usage check switched the process context to each subscription for Get-UsageAggregates, which reads the subscription of the current context; Az has no supported way to build a context for another subscription without selecting it for the whole process. The check now calls the API the cmdlet wraps (Microsoft.Commerce/UsageAggregates, api-version 2015-06-01-preview) through Invoke-AzRestMethod, with the subscription in the path and the same window and options. The next page is requested with the continuation token from nextLink, as the cmdlet does. Retries, the 50-page cap and the verdicts are unchanged. The consumption phase still uses the cmdlet. A subscription whose check fails unexpectedly gets a failing record (Unknown, or Error for the usage check) instead of being left out. -ThrottleLimit 1 runs the checks one subscription at a time in the caller's runspace; the tests that replace Azure with Pester mocks use it.
A subscription that fails the up-front role check no longer stops the run. It is skipped: listed with its reason and the fix right after the check, and again at the end of the run, because the report does not contain it. The other subscriptions are collected. This was Run-AllSubscriptions.ps1 -AllowPartialAccess; it is now the default in the wrapper and in a direct ResourceInventory.ps1 run over every visible subscription. A direct run leaves a skipped subscription out of the consumption check, its subscription list and the resources Resource Graph returned for it. When no checked subscription is readable the run still stops with exit 1 before any work, for example a direct run whose -SubscriptionID is not readable. Skipping does not change the exit code. The consumption data check is unchanged and only checks the readable subscriptions. -AllowPartialAccess is still accepted so existing command lines keep working; it changes nothing.
added 2 commits
October 27, 2026 23:36
Invoke-RoleCheckGet followed an answer's nextLink with Invoke-AzRestMethod -Uri, so the next request, and the access token with it, went to whatever host the answer named. It now asks for the link's path and query with -Path, on the context's Resource Manager endpoint, as every other call in the file does. This covers the role assignment list, role definitions and caller permissions. A nextLink that is not an absolute http(s) URL, or has no path (or one starting with '//'), counts as a missing answer: the role check for that subscription is inconclusive, so the subscription is not readable and is skipped with that reason. The link itself is not logged. The page cap and its outcome are unchanged.
…mary When the direct script also exits 4 for a run that lost a collector, that check sits after the no-usage and skipped-subscription lists, so the file no longer ends with the summary call. The test still requires both lists right after the report and zip logging, in that order, and allows only that exit 4 check (comment lines, the failure count and one exit line) after them, so it passes with or without the check. The wrapper assertion is unchanged.
added 2 commits
October 28, 2026 12:58
GetResorceConsumption sets the en-US culture and left UsageStartTime and UsageEndTime as DateTime values, so Export-Csv wrote them with the culture's own date and time pattern. That pattern comes from the host's culture data: on Linux .NET reads it from ICU, and with ICU 74 the en-US time pattern has a narrow no-break space (U+202F) before AM/PM, so the same usage row gave different bytes on different hosts. The two dates are now formatted as 'M/d/yyyy h:mm:ss tt' with the invariant culture, for example '10/1/2026 12:00:00 AM', with a plain space. On such a Linux host the only change is U+202F becoming a plain space. The clock value is written as it came from Get-UsageAggregates, with no time-zone conversion, as before. docs/consumption-data.md states the format.
Get-ConsumptionWindow took the window from the host's local date, so the same moment gave windows a day apart on hosts in different time zones: at 00:55 UTC on 28 October a host at UTC-7 collected 26 September to 26 October and a host at UTC 27 September to 27 October. Usage days are UTC days. The default clock is now [datetime]::UtcNow, so every host gets the same window for the same moment. The window is still midnight 31 days ago to midnight yesterday, sent with Kind=Unspecified as before. The up-front consumption check and the billing phase still share the one window each run computes (Run-AllSubscriptions.ps1 still passes it to every ResourceInventory.ps1 it starts). The comment, README and docs/consumption-data.md say the dates are UTC dates.
This was referenced Oct 29, 2026
added 5 commits
October 29, 2026 10:38
On -Resume the role check leaves out the subscriptions the resume state records as completed, and it stopped with exit 1 when every subscription it did check was unreadable. Each later -Resume stopped the same way, so the run never finished and the resume state was never cleared, although the reports of the completed subscriptions had been written. Resolve-AccessPreflight now takes the number of completed subscriptions in scope (-CompletedCount) and does not stop while it is above 0. The unreadable subscriptions are skipped and listed after the check and at the end of the run, as when readable ones are left, and the run finishes with nothing left to collect. A run without -Resume, and a -Resume run with no completed subscription in scope, still stop. On such a -Resume stop the fix ends in running -Resume again, and a last line says that a run without -Resume checks the same subscriptions and stops too. No script parameter or exit code is added. Tests: the rule, the wording, the wrapper's check block, and runs of the wrapper itself with stand-ins for Azure (two -Resume runs in a row after an interrupted run, the stop without -Resume, each way out of the -Resume stop, and every zip opened under -Obfuscate).
When every subscription a -Resume run has left to check is not readable and the others were completed by an earlier run, the run skips the unreadable ones and finishes. With -ParallelStreams 2 or more, also when the value is chosen automatically, it then collected the completed subscriptions again: the one-subscription path and the parallel streams do not read the parent's list of completed subscriptions, and these subscriptions were not part of this run's role check. The run now uses one stream in that case, so the sequential loop skips them, and the Parallelism line says why. A -Resume stop says a run without -Resume stops too only when every cause is a missing role; a check that could not finish, or answers that disagree after a role change, can pass on the next run, so for those it says only that a run without -Resume checks the same subscriptions. When the role check skipped a subscription that is on the retry list, the end-of-run Pending Retries lines name it and say Reader must be granted before -ResumeFailedOnly can retry it. -ResumeFailedOnly itself is unchanged. README: a role that leaves out some resource types makes the subscription not readable (it is skipped, as the paragraph already ends), and the -Resume paragraph describes the one-stream finish and the Pending Retries lines. Tests: the wording for each cause, the Pending Retries helper, and runs of the wrapper itself with -ParallelStreams 2 and the automatic value after one and after three completed subscriptions, and with a subscription on the retry list that can no longer be read.
…lect A parallel run keeps each stream's progress in its own state file and merges those files into the resume state at its end, deleting them. A -Resume run after an interrupted parallel run folds them in at startup and leaves them for that merge. When nothing is left to collect, the run uses one stream, so the merge does not run: it printed "Resume state cleared (clean run)." with the per-stream files still on disk, and every later -Resume recovered and skipped the same subscriptions again. When that run clears the resume state, it now also deletes the per-stream files it folded in, as the merge does, so the next -Resume starts fresh. Other one-stream -Resume runs keep them, as before. The Pending Retries lines gave the fix for a missing role whatever the reason a retry-list subscription was skipped. They now list each with its reason and give the fix for each cause, ending in running -ResumeFailedOnly: grant Reader, re-run after a check that could not finish, or wait 5 minutes after the two answers disagree. The fix text is shared with the role check's own report (Write-AccessRemedyLines). Tests: runs of the wrapper itself after a parallel run whose session ended while it was collecting, with -ParallelStreams 2, the automatic value and 1 on the -Resume (no main or per-stream state file left, and the next -Resume recovers nothing and collects again), and the Pending Retries lines for each cause and for mixed causes.
…on the retry list A -Resume or -ResumeFailedOnly run folds in the per-stream state files an interrupted parallel run left. A file that could not be parsed (an interrupted write can leave it cut short) was skipped with a verbose message only: the run went on as if it held nothing, a run that cleared the state deleted it while printing "Resume state cleared (clean run).", and with one stream it stayed and was skipped again on every -Resume. Such a file is now renamed in place to <name>.unreadable-<UTC time> with a warning naming it: no later run reads it, it does not end in .json, and it is kept for inspection. Its records are not used, so the subscriptions it listed are not counted as completed and the run collects them again. That run does not print the clean-run line: it says whether the state was cleared or kept and where the file went. When it clears the state it deletes the per-stream files it read, as the finish case already did, so the next -Resume starts with no state. Files that were read are deleted as before; the one moved aside is not. A subscription the up-front role check skips because the check could not finish, or because the two answers disagree while a role change takes effect, now stays on the retry list (FailedAttempts) as a failed run, with a reason naming the cause, and is taken off the completed list. The state is kept, -Resume and -ResumeFailedOnly check it again, and each run counts, also a run that stops because nothing it checks is readable, so the retry limit can end the retries. A subscription skipped for a missing role is not added. The Pending Retries line now says the subscriptions are on the retry list, not that they all come from a prior run. The state file keeps every other key it holds when the retry list is written (Update-ResumeStateRetryList). No script parameter, exit code or stop is added.
The lists of per-stream files read and moved aside are now plain arrays appended with @(...) + item, so the fold of per-stream state also works when it runs without the lines before it set them up. No change in what a run does.
added 9 commits
November 10, 2026 18:01
…empts null is not a list Read-StreamResumeStateFile let 'FailedAttempts': null through, and did not look inside the lists: an entry with no Id (or a non-object) was grouped under an empty id and saved, so the state never cleared, and under strict mode the fold threw on it every run. Write-StreamState always writes Completed as a list of ids and FailedAttempts as a list of Add-FailedAttempt records, so any other shape is a file that cannot be read (moved aside). Tests: 8 shapes refused (red before), the written shapes and an older file with no FailedAttempts still read.
119f01e refused a null entry, but Write-StreamState writes 'FailedAttempts': [null] for an empty retry list (@($null) of the list Remove-FailedAttempt returns), so every parallel run's stream file was moved aside as unreadable and its completions collected again (12 whole-wrapper tests red in the full suite). Null entries are skipped by every reader, so the check now refuses only an entry of another type: a Completed entry that is not a string, a FailedAttempts entry that is not an object with a non-empty string Id. FailedAttempts null itself stays refused (never written). Tests: the written [null] shape reads (red before), and the 12 whole-wrapper tests pass again.
…leted id is a file that cannot be read The start fold and the end-of-run merge added a stream file's FailedAttempts entries as they are, so the [null] Write-StreamState writes for an empty list counted as a failed record: the fold printed '2 completed, 2 failed subscription record(s)' for two streams with no failure (pre-existing on main; all-fixes-optimized filters them). Both now drop null entries. 9321827 had also let a null or empty Completed entry through, which Write-StreamState never writes; it is refused again, with its two test cases back. Tests: the two whole-wrapper fold lines now read '0 failed' (red before), and the two Completed cases are refused (red before).
…ents name the shape rule Read-StreamResumeStateFile let a retry entry with no LastFailedAt, or one that is not a date, through; Merge-FailedAttempts then converts it with [datetime], which fails (under strict mode the missing property throws), so the fold failed on every run instead of moving the file aside. As all-fixes-optimized does, LastFailedAt must be a [datetime] (ConvertFrom-Json's reading of ISO 8601 text) or text the cast parses (invariant culture). The function's header and the start fold's comment now say a file not in the written shape reads as one that cannot be read. Tests: no date, a word, a number (red before), and the missing-date case under Set-StrictMode -Version Latest returns no record instead of throwing (red before).
…was not a clean run Write-UnreadableStreamStateSummary ran only at the end of the run, so a run that exited early after the start-up fold moved a per-stream file aside (-ResumeFailedOnly with an empty retry list, or with retry ids no longer visible, or the output check's exit 2) never said the run was not clean, or whether the resume state was kept. Exit-Wrapper, which every such exit goes through, now says it when it was not said before (the summary records that it ran). Test: the -ResumeFailedOnly case with an empty retry list prints 'Resume state kept, but not a clean run: ...' once (red before). Full Pester: 0 new.
Exit-Wrapper read the list of per-stream state files it could not read as one object, so an empty list passed the filter. Every stop after the start-up fold then said the run was not clean, naming an empty file. The list is now read item by item, with a test.
It stops with code 7, which pwsh never gives on its own, and fails on any error text.
Two tests: the end-of-run line is not repeated at the stop after it, and a stop with no earlier line says it, with kept or cleared. The comment says when the variables are not set.
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Nov 12, 2026
added 14 commits
November 12, 2026 17:03
…nd-usage-check Brings in the three memory PRs awslabs main merged. The run counts the discovered resources into $Global:ResourceCount after this branch leaves out a skipped subscription's resources, and the end-of-run lines of awslabs#41 come first, then this branch's no-usage and skipped-subscription lists.
The awslabs#41 inventory-write harness stubs every Azure step of a direct run; this branch adds the up-front role check, so the harness stubs it too (no subscription reported unreadable) and the run still never loads Az.Accounts. The end-of-run order check reads the report line inside the if/else on $ZipWritten that awslabs#41 added, with the no-usage and skipped-subscription lists right after it.
Get-ConsumptionRowResourceUri read 'Microsoft.Resources'.resourceUri directly, so under Set-StrictMode a row whose InstanceData lacks either property stopped the consumption data check of a resource group run. It now returns nothing for such a row, as its comment says.
A direct run over every visible subscription that found none skipped the up-front checks and went on to write an empty report. It now stops with exit 1, as a run whose subscriptions are all unreadable does. The test harness can now start with no subscription at all.
The harness passed the up-front checks only because the setup's empty subscription value counts as one. Its sign-in stand-in now finds one placeholder subscription, as a real direct run does, so the harness does not depend on that value.
The comments and the README said a retry limit ends the retries of a subscription the role check could not finish, but this branch has no such limit. They now say it stays on the retry list, with its run count and reason, until a later check passes, as any failed subscription does.
A passing role check does not take the subscription off the retry list; the run that then collects it does. The comment and the README now say so, and the README names the list once.
When a per-stream state file cannot be read at the end of a parallel run, its records are set aside, and with them may go this run's failure of a subscription an earlier run completed. That completion stayed, so -Resume skipped the subscription and carried the older report. Of this run's subscriptions, only those a file that was read lists as completed now keep a completion; -Resume collects the others again.
A readable file an earlier run left can list a subscription whose failure this run's unreadable file held, so trusting the readable files could still keep a stale completion. Which stream's records were lost is not known, so when any file cannot be read at the end of a parallel run, none of this run's subscriptions keeps a completion and -Resume collects them all again.
…ole run Since the merge keeps no completion of a run's subscriptions when one per-stream file cannot be read, the warning and the README now say that a later -Resume collects all of that run's subscriptions again, not only those the file listed.
The comments on Move-UnreadableStreamStateFile and on the merge loop's unreadable branch still named only the file's own subscriptions for the end of a run; they now say none of that run's subscriptions counts as completed.
…am file The merge saved a state that keeps none of the run's subscriptions as completed, but the clean-up at the end of the run still removed the state when no failure was reported, and with it the completions of earlier runs. A run whose merge could not read a per-stream file now keeps the resume state, as the file may have held a failure.
The clean-up case passed the flag by hand, so it would still pass if the merge stopped setting it. It now reads the flag from the merge block's result and checks it is set.
The case reads its test-case values inside a child script block, so the analyzer saw the declared parameters as unused. Pester sets the values as variables, so the block is not needed.
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Nov 17, 2026
…access-and-usage-check)
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Nov 17, 2026
…rk remains Changes on the merged candidate (consolidated report): - loop trap (awslabs#68): a run that skipped a subscription for the retry limit and completed the rest cleared the resume state, so the count was forgotten and the next -Resume collected it again from the first attempt: fail x3, skip, clear, forever. Entries past the limit now keep the state, and a run that skips one ends with exit 2 (its report is missing from the bundle). They leave the state when a run collects them (the subscription on its own, or a run without -Resume), as the advice says. - loop trap (pre-existing): a retry-list entry for a subscription the identity no longer sees was never retried or counted and kept the state forever. -Resume and -ResumeFailedOnly now drop such an entry with a line naming it. A disabled subscription is still listed, so its entry stays. - (awslabs#62/awslabs#68): -ResumeFailedOnly kept the state and exited 0 while work remained (never-reached subscriptions, retry-list ids not in the current set, only entries past the limit), so a repeated command reported success forever. Those exits are now 2; 0 stays for nothing owed. - stale comment on the one-stream -Resume. The tests of awslabs#38, awslabs#62, awslabs#68 and the parallel -Resume fix that asserted the old exit 0 or the cleared state now expect the new behaviour, and the capped case traces the next two -Resume runs. A new case drops an entry for a subscription that is gone. README updated.
The comments, the console lines and the README now say what the usage values show and that a subscription with no resources has no usage to read. No check or exit code changes.
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Nov 18, 2026
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Nov 18, 2026
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Nov 18, 2026
…scan - The check looked only at the first and last bytes of the JSON files and the CSV header, so well-bracketed bad JSON, a metrics file with no Metrics list, or a consumption row with a cell that does not parse passed. The JSON files are now parsed (System.Text.Json: an object; the metrics file's Metrics is a list whose MetricCount, MetricValue, MetricPercentile are numbers and MetricError is true or false where given), and every row of the consumption file is read: the header names the needed columns, each row has every column, and Quantity, Cost, UnitPrice, UsageStartTime and UsageEndTime parse with culture-free rules (an empty cell is not checked: that row is dropped, not the file). - The scan ran a PowerShell loop over every byte (about 0.5 MB/s); the read to the end is the plain buffered read again, and the parsing runs in .NET. shortcut (in the code): the JSON is parsed in memory, so a report of several GB takes that much memory here. Note: on a branch without PR awslabs#38's culture-free usage text, a host whose culture writes a comma decimal mark writes cells that do not parse; such a report is then named as unreadable, not shipped. Tests: six more unreadable cases (6 red before), the file shape with a BOM and a quoted JSON cell reads, and a zip with a 20 MB inventory and a 20 MB consumption file is checked in under a minute.
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.
Problem
Two kinds of missing access go unnoticed today and produce a report that looks complete but is not:
Azure's usage API (
Get-UsageAggregates) does not reject an identity that lacksMicrosoft.Commerce/UsageAggregates/read; itanswers successfully with zero rows. The existing up-front check only stops on a permission error, probes only the first
subscription for a single day, and treats "no error" as access. The run then finishes with an empty consumption sheet and no
message. Direct runs of
ResourceInventory.ps1have no check at all.Run-AllSubscriptions.ps1lists the subscription's resource groups and treatsany successful answer as access. Azure filters that list to what the caller may see instead of refusing, so an identity that can see
a subscription but read none of its resources gets an empty list, passes, and ends with an empty report labelled "GENUINELY EMPTY -
access confirmed". Direct runs have no check.
Change
Before any inventory or metrics work,
Run-AllSubscriptions.ps1and direct runs ofResourceInventory.ps1now run two checks onevery subscription the run will process (on
-Resumeonly those still to do; under-RunAllSubsthe inner script does not repeatthem).
through a group, and those at a management group or the tenant root) and the permissions of each role, and separately asks Azure
for the caller's effective permissions on the subscription. It needs one role that reads every resource type: an action such as
*/reador*, and nonotActionsin that same role that remove reads of some resource types (a not-action that, with*standing for any characters, can match an action ending in
/read, for exampleMicrosoft.Compute/*/readorMicrosoft.Comp*),because Resource Graph leaves out the resources of a type the caller cannot read without an error. Not-actions confined to
Microsoft.Authorization,Microsoft.Commerce,Microsoft.ConsumptionorMicrosoft.Billingare allowed: the inventory reads noresources of those namespaces. Each role is judged on its own, as Azure
does, so Reader next to a narrower custom role passes. Both answers must agree:
(for example
role 'Custom reader' at subscription excludes 'Microsoft.Compute/*/read'; the inventory would miss those resources);A subscription that is not readable is skipped (new in this revision): it is listed with its reason right after the check
and again at the end of the run, and the other subscriptions are collected. When no checked subscription is readable the run
stops with exit 1 (on
-Resume, only when no subscription in the run is recorded as completed; see the latest updatebelow). The list gives the fix for each cause: grant Reader (no read access, or a resource group that is not found), re-run (an
answer still missing after retries), or wait about 5 minutes and re-run (the answers disagree, usually because roles were just
changed and take a few minutes to apply). The role assignment list is followed for at most 1000 pages; past that the answer
counts as missing. Each role definition is read once per run, and one whose read is refused (HTTP 401, 403 or 404) is not read
again for later subscriptions; after throttling, a server error or a timeout it is read again.
For a direct run with
-ResourceGroup, a role on that resource group is enough. When consumption is requested, the check alsoreports whether the roles on the subscription allow reading usage (
Microsoft.Commerce/UsageAggregates/read, counted only at thesubscription or above). The usage check below uses that answer for subscriptions that return no usage, and adds it to the fix
text when it refuses.
nextLink), on the ResourceManager endpoint of the signed-in context, so no request goes to a host the answer names. A
nextLinkthat is not anhttp(s) URL, or has no path (or one starting with
//), counts as a missing answer, so the subscription is not readable andis skipped with that reason.
-SkipConsumption), for the readable subscriptions. Same usage API,options and 31-day window as the billing phase: the API that the billing phase's
Get-UsageAggregateswraps(
Microsoft.Commerce/UsageAggregates, api-version2015-06-01-preview), called throughInvoke-AzRestMethodwith thesubscription in the request path (new in this revision, see below). The window is worked out once per run and the billing phase collects that same window: a direct run computes it
before the check;
Run-AllSubscriptions.ps1computes it before its check and passes it to everyResourceInventory.ps1it starts(internal parameters
-ConsumptionWindowStartand-ConsumptionWindowEnd, asyyyy-MM-dd), so a subscription collected aftermidnight still collects the window that was checked. A subscription passes when at least one usage row has a quantity above zero;
pages are followed until one is found, for at most 50 pages. Reaching 50 pages without one counts as only zero quantities, and the
output says only the first 50 pages were read.
A direct run with
-ResourceGroupchecks that resource group: only usage rows whose resource is in it count (the same test thebilling phase uses to keep rows for such a run), the resource count is of that resource group, and the messages name it.
That test now compares the name after
/subscriptions/<id>/resourceGroups/(new in this revision). Before, it looked for/<name>/anywhere in the resource URI, so for resource groupweba usage row of/subscriptions/<id>/resourceGroups/prod/providers/Microsoft.Web/sites/web/slots/stagingcounted: the check could pass on anotherresource group's usage, and the billing phase put that row in the
websheet. Main's billing phase has the same expression.Under
-ResourceGroupthe billing phase now skips a usage row without a resource URI, instead of stopping that subscription'sconsumption collection with an error.
A subscription that holds resources but returns no usage above zero (a new subscription, only free resources, paused resources)
passes with a yellow warning (outcome
NoUsage) when the role check found the usage permission at the subscription or abovein both answers. The warning names the role and scope, the window, the typical causes, and that the subscription's
consumption sheet will be empty; both scripts list these subscriptions again at the end of the run. The exit code is unchanged.
When the 50-page limit was reached, the warning and the end-of-run list say only that no usage above zero was found in the first
50 pages, not that the sheet will be empty (the billing phase reads every page).
Otherwise zero rows, only zero quantities, a permission error, or an error that persists after bounded retries (throttling,
timeouts, 5xx; backoff 2, 4, 8 s; a 400 is not retried) stops the run. Subscriptions with no resources are not checked (no usage
to read); the role check has already confirmed they are readable.
8 subscriptions at a time
Both checks now run up to 8 subscriptions at a time (
ForEach-Object -Parallel -ThrottleLimit 8, the patternExtension/Metrics.ps1uses) and print their lines in subscription order, as before. Nothing in the parallel part reads or changesthe Azure context: every request names its subscription. The role check already did. The usage check used to switch the process
context to each subscription for
Get-UsageAggregates, which reads the subscription of the current context, and Az has no supportedway to build a context for another subscription without selecting it for the whole process. It now calls the API the cmdlet wraps,
with the same parameters, and asks for the next page with the continuation token from
nextLink, as the cmdlet does. Retries(backoff 2, 4, 8 s), the 50-page limit and the verdicts are unchanged; the billing phase still uses the cmdlet. Each role definition
is still read once per run (a definition not yet read is read under a lock). A subscription whose check fails unexpectedly gets a
failing record (not readable, or
Errorfor the usage check) instead of being left out. Neither check changes the saved defaultsubscription.
Stops, and the stop this revision removes
Removed in this revision: a subscription the identity cannot read no longer stops the run. It is skipped: listed with its reason
and the fix right after the check, and again at the end of the run, because the report does not contain it; the other subscriptions
are collected. This was
Run-AllSubscriptions.ps1 -AllowPartialAccess; it is now the default in the wrapper and in a direct run ofResourceInventory.ps1over every visible subscription (a direct run also leaves the skipped subscription out of its subscriptionlist and out of the resources Resource Graph returned for it). Skipping does not change the exit code: as with
-AllowPartialAccessbefore, a run whose collected subscriptions all succeed exits 0. I decided this.
The remaining stops end the run with exit code 1, before any inventory or metrics work, listing every failing subscription with its
reason and the fix. A report without read access or without usage values is incomplete. A run stops when:
-SkipConsumption): no checked subscription is readable. Not readable means the two answers donot both show read access - both say no; role assignments are not visible and Azure says no; the two answers disagree; an answer is
still missing after retries; or, for a direct
-ResourceGrouprun, the resource group is not found. A direct run with-SubscriptionIDchecks only that subscription, so it stops when that one is not readable. An identity with Reader on only partof a subscription therefore gets that subscription skipped (or a direct run of it stopped) instead of a partial report. On
-Resumeonly the subscriptions still to do are checked; when none of them is readable,-Resumestops only if no subscriptionin the run is recorded as completed (latest update, see below). A run without
-Resumestops whenever none of the subscriptionsit checks is readable.
(or, for a direct
-ResourceGrouprun, at that resource group) allows reading resources without a not-action that removes readsof some resource types. A not-action counts when, with
*standing for any characters (including/) and ignoring case, it canmatch an action that ends in
/read: without a*, when it ends in/read; with a*, when the text after its last*is empty,is the end of
/read(read,ad,d) or itself ends in/read. So*/read,Microsoft.Compute/*,Microsoft.Comp*,Microsoft.Compute/*/r*,*adandMicrosoft.Compute/virtualMachines/readcount, andMicrosoft.Compute/*/delete,*/writeand
Microsoft.Compute/*reado not. A not-action is allowed when the text before its first*(or all of it) starts withMicrosoft.Authorization/,Microsoft.Commerce/,Microsoft.Consumption/orMicrosoft.Billing/:Microsoft.Authorization/*isallowed, but
Microsoft.Auth*, which can also match other namespaces, counts. Two narrower roles that together cover every resource typedo not count either. Such a subscription is not readable, so it is skipped like any other (in this revision; before, it stopped
the run). I decided this: a report that silently misses whole resource types is incomplete.
Denied); fails after theretries (
Error); or returns no rows (NoRows) or only zero quantities (NoPositiveQuantity, including 50 pages without a value)while the usage permission was not found by both role-check answers (for example role assignments not visible, the answers
disagreeing, or the permission granted only on a resource group). For a direct
-ResourceGrouprun this now applies to thatresource group's usage rows: a run whose resource group has no usage above zero stops (before this revision it passed when other
resource groups of the subscription had usage), unless the usage permission is confirmed by both answers, in which case it passes
with the
NoUsagewarning. I decided this too.Bypasses:
-SkipConsumptionskips the usage check (and the collection of consumption data). The role check has no bypass.-AllowPartialAccessis still accepted, so existing command lines keep working, but skipping is now the default and the switchchanges nothing.
Cost
Per subscription, the role check makes 2 Azure calls (the role assignment list, plus pages up to 1000, and Azure's effective
permissions; 3 for a direct
-ResourceGrouprun with consumption) and reads each distinct role definition once per run. The usagecheck makes one Resource Graph count query per 1,000 subscriptions, then, for each subscription with resources, usage pages until a
value above zero is found (usually 1, at most 50). A
-ResourceGrouprun looks for a value in that resource group, so on asubscription with much usage elsewhere it can read more of those 50 pages. Both checks run up to 8 subscriptions at a time.
Measured live, normal user sign-in (Owner), the 3 subscriptions of a small test tenant,
Run-AllSubscriptions.ps1 -SkipMetrics,two runs each, check time read from the console timestamps:
With 3 subscriptions the role check gains little: each parallel runspace first loads Az.Accounts and this tool's functions, about
2-3 s, once per runspace. The wrapper process held 231 MB at the end of the checks before and 250-252 MB with this revision (3
runspaces); its peak over the whole run was the same before and after, 261-266 MB.
Offline, with stand-ins that take 1.0 s per Azure call and one role definition shared by all subscriptions:
Before, the usage check also switched the context once per subscription (counted as one Azure call). At most 8 Azure calls were
in flight at any time, and the per-subscription results were the same before and after for every size. The stand-in memory figures
leave out loading Az.Accounts in each runspace.
Projected from these numbers, not measured: each round of 8 subscriptions takes about one subscription's check time. With the live
per-subscription times above (role check 0.8-1.8 s after the first subscription, usage check 0.7-1.4 s, plus about 3 s to start
the runspaces), about 100 subscriptions wait roughly 25-50 s for both checks before the run starts (one after another:
about 4.5-7 minutes), and about 1,000 subscriptions roughly 3.5-7 minutes (one after another: about 45-70 minutes). Azure throttling
at that scale was not tested; throttled calls are retried with backoff (2, 4, 8 s). The role check cannot be skipped;
-SkipConsumptionskips the usage check.Replaces
Get-ConsumptionAccessOutcome,Test-ConsumptionAccess,Get-SubscriptionAccessStateandTest-SubscriptionAccessAll;the shared checks live in
Functions/Common.Functions.ps1. README: required roles (Reader at the subscription or above; Reader andBilling Reader include the usage permission, Cost Management Reader does not), the two checks, the wait after a role change, and
troubleshooting entries.
Consumption sheet: usage dates and window (previous update)
The previous update adds two changes to the consumption sheet (
Consumption_ResourcesReport_<timestamp>.csv). It does not changethe checks. Elsewhere in this description, "this revision" means the revision before the previous update.
GetResorceConsumptionsets the en-US culture and leftUsageStartTimeandUsageEndTimeasDateTimevalues, soExport-Csvwrote them with the culture's own date and time pattern. That pattern comesfrom the host's culture data. On Linux .NET reads it from ICU; with the ICU of the test host (ICU 74, PowerShell 7.6) the en-US
time pattern has a narrow no-break space (U+202F) before
AM/PM, so the host wrote10/1/2026 12:00:00<U+202F>AM(seen liveon
mainon that Linux host, in every usage date). Both dates are now formatted asM/d/yyyy h:mm:ss ttwith the invariant culture:10/1/2026 12:00:00 AM, with aplain space, on every host. The clock value is written as it came from
Get-UsageAggregates, with no time-zone conversion, asbefore.
docs/consumption-data.mdstates the format.Get-ConsumptionWindowtook the window from the host's local date, so the same momentgave windows a day apart on hosts in different time zones. In a live run at 00:55 UTC on 28 October, a host at UTC-7 collected
26 September to 26 October and a host at UTC 27 September to 27 October; each sheet matched Azure for its own window. Usage
days are UTC days. The default clock is now
[datetime]::UtcNow, so every host collects the same days at the same moment. Thewindow is still midnight 31 days ago to midnight yesterday, sent with
Kind=Unspecifiedas before, and the up-front check andthe billing phase still share the one window each run computes (
Run-AllSubscriptions.ps1still passes it to everyResourceInventory.ps1it starts). The README anddocs/consumption-data.mdsay the dates are UTC dates.No column, exit code or stop is added or changed, and there are no extra Azure calls.
-Resumewhen every subscription left to check is not readable (latest update)On
-Resumethe role check leaves out the subscriptions the resume state records as completed: an earlier run wrote theirreports. Before this update, when every subscription it did check was not readable, the run stopped with exit 1, for example after
a run that was interrupted while it collected a subscription the identity can no longer read. Each later
-Resumestopped the sameway, so the run never finished and the resume state was never cleared.
What changes, exactly:
-Resumeno longer stops when at least one subscription in the run is recorded as completed and every subscription itchecks is not readable. Recorded as completed means the subscriptions this run skips as already completed: in the resume state
and in this run's scope. The run lists each unreadable subscription with its reason right after the check and again at the end of
the run, skips it, and finishes with nothing left to collect, as a run that skips some unreadable subscriptions does: the exit
code is the one the run would have without the skipped subscriptions (0 for a clean run), and the resume state is cleared when
nothing failed and nothing is left on the retry list. A subscription skipped because its check could not finish, or because its
two answers disagree, is put on the retry list (see below), so the state is kept for it. The check prints:
That run uses one stream, whatever
-ParallelStreamsis, also when the value is chosen automatically (for example 2 on ahost with 4 vCPU). The sequential loop skips the completed subscriptions; the parallel streams and the path for a single
subscription left do not read the list of completed subscriptions, so with 2 or more streams they collected them again, without
a role check in this run. The
Parallelism:line says why:With
-ParallelStreamspassed it ends... instead of the 2 passed), .... In both casesRunSummary.loglists the streamsas
1 (nothing left to collect). When one stream was passed or chosen already, nothing is reduced: theParallelism:line andRunSummary.logkeepexplicitorauto.When that run clears the resume state, it also deletes the per-stream state files an interrupted parallel run left
(
.resume-state-<tenant>-stream-<N>.json). A-Resumefolds those files in at startup and leaves them for the merge at the endof a parallel run, which deletes them; with one stream that merge does not run, so the run printed
Resume state cleared (clean run).with the files still on disk, and every later-Resumerecovered and skipped their subscriptions again. It deletes onlythe files it read; one it could not read is moved aside instead (see below). When the run keeps the state (a subscription is
still on the retry list), it keeps those files too, as any one-stream
-Resumedoes.A run without
-Resumestill stops with exit 1 when none of the subscriptions it checks is readable, also when the resumestate records completed subscriptions (without
-Resumethey are checked like the others). Its lines are unchanged.-Resumewith no subscription in the run recorded as completed still stops with exit 1. The fix now ends in running-Resumeagain, and a last line says that a run without-Resumechecks the same subscriptions (with nothing recorded ascompleted, it does). When every subscription has no read role, the line adds that such a run stops too; when a check could not
finish, or the two answers disagree after a role change, a later run can pass, so the line says only the first part. Granting
Reader and running
-Resumeagain collects them and clears the state.For a check that could not finish:
A skipped subscription on the retry list is named under
Pending Retries. When a run that ends with no new failure hassubscriptions on the retry list (
FailedAttempts) and its role check skipped some of them as not readable, the end of the runnames them with their reason and gives the fix for each cause, as the start of the run does, ending in running
-ResumeFailedOnly: grant Reader (no read role), run it again (the check could not finish), or wait 5 minutes (the two answersdisagree, usually right after a role change).
-ResumeFailedOnlyruns the same check before it retries, so until the cause isfixed it skips them, and when they are all it has to retry it stops with exit 1. Its exit codes are unchanged. The first line
now says
on the retry list (FailedAttempts)instead offrom a prior run still in FailedAttempts, because a subscription thisrun skipped can be on it (next bullet):
With several causes the fixes are one line per cause, naming the subscriptions:
A subscription skipped for a cause that can pass later stays on the retry list. When the role check skips a subscription
because its check could not finish (
Unknown, for example an answer still missing after retries) or because the two answersdisagree (
Disagree, usually right after a role change), the run puts it on the retry list (FailedAttempts) as a failed run,with the reason
skipped by the up-front role check: <reason>, and takes it off the completed list. It does this also when therun stops because nothing it checks is readable: the failed run is recorded before the exit. A subscription skipped because the
identity has no read role is not put on the retry list (it needs Reader first). So the resume state is kept, every
-Resumeand-ResumeFailedOnlychecks it again, each such run adds one to its count, and the run that collects it takes it off the list.The exit codes are unchanged: the run ends with the code it would have without the skipped subscription, and
-ResumeFailedOnlystill stops with exit 1 when nothing on its retry list is readable. The retry list is written into the state file with every
other key it holds kept as it is. A separate change that stops retrying a subscription after 3 failed runs in a row ends these
retries: the third such run reaches the limit, and the next
-ResumeprintsNot retried: <name> (<id>) failed 3 runs in a row; last reason: skipped by the up-front role check: ...and clears the state once nothing else is pending (a-ResumeFailedOnlyinstead prints
ResumeFailedOnly: nothing left to retry; ...and exits 0; the next-Resumeafter the state is cleared startswith no state and checks the subscription again). Without that limit, a subscription whose check keeps failing
keeps the state, and every
-Resumeand-ResumeFailedOnlychecks it and lists it again.A per-stream state file that cannot be read is moved aside. A
-Resumeor-ResumeFailedOnlyrun folds in the per-streamstate files an interrupted parallel run left. One that could not be parsed (an interrupted write can leave it cut short) was
skipped with a verbose message only: none of its records were used, a
-Resumewith nothing left to collect deleted it whileprinting
Resume state cleared (clean run)., and with one stream it stayed and was read again, silently, by every later-Resume. Now therun prints a warning naming the file (never its content), renames it in place to
<name>.unreadable-<yyyyMMdd-HHmmss>(UTC) andkeeps it for inspection. Its records are not used: the subscriptions it listed are not counted as completed, so a
-Resumeruncollects them again, those it can read;
-ResumeFailedOnlyretries only its retry list, so after it a later-Resumecollectsthem, and its warning says so. The renamed file does not end in
.jsonand does not match the pattern for per-stream files, so nolater run reads it, and neither the wrapper's zips nor a zip step that takes
*.jsonfiles picks it up. The run never printsResume state cleared (clean run).; a run that reaches its end prints a last state line saying whether the state was cleared orkept and where the file went. A run that ends early, for example
-ResumeFailedOnlywith nothing to retry or a run that stopswith exit 1, prints no such line; the warning at the start is then the only line about the file. The state is cleared or kept by
the usual rule (cleared when nothing failed and nothing is left on the retry list): the run collected
again what the file listed and nothing reads the moved file, so keeping the state would only make the next
-Resumeskip what thisrun collected. When it clears the state, it also deletes the per-stream files it read, so the next
-Resumestarts with no state.Under
-ResumeFailedOnlythe warning ends... the subscriptions it lists are not counted as completed and a later -Resume collects them (-ResumeFailedOnly retries only the retry list). It was moved aside to .... When the state is kept, the last line startsResume state kept, but not a clean run: .... If the rename fails, the run now stops (see the strict-mode update below):ERROR: The per-stream state file <name> could not be read, and it could not be moved aside: <reason>, named with the commandthat removes it, and exit 1 before it collects anything.
A resume state file that cannot be removed is named, and the run does not say it cleared the state. At the end of a run
that clears the resume state, the per-stream state files it read and the resume state file were removed with
Remove-Item,whose errors do not stop the script, so the run printed
Resume state cleared (clean run).even when a file stayed on disk (forexample with the inventory root read-only, seen with all three files left). Now the per-stream files are removed first, then the
resume state file, each with
-ErrorAction Stop, and each is checked to be gone (Remove-ResumeStateFiles). A file that is leftgets a warning naming it and the reason, and the run does not print the clean-run line. While a per-stream file is left, the
resume state file is kept too, so the next
-Resumereads the same state and that file again; the warning asks for the namedfiles to be removed once the folder can be written, because only some runs remove per-stream files (a
-Resumewith nothingleft to collect, one that moved a file aside, and the merge at the end of a parallel run; see Limitations). The exit codes are
unchanged.
When the resume state file itself cannot be removed:
WARNING: Could not remove the resume state file <name>: <reason>, thenThe next run reads it again and retries the removal.The end-of-run clean-up of a parallel run, which deletes the per-streamfiles after merging them, is described in the strict-mode update below.
On this branch alone a
-Resumerun builds its consolidated zip only from the reports it writes, so when nothing is left tocollect it prints
No per-subscription zip files found under <inventory root> to consolidate., leaves the earlier reports in theirfolders and clears the state, as a
-Resumewhose every subscription is already completed does. With #48 the run carries theearlier reports into its consolidated zip. With #48 and #62, two
-Resumeruns in a row both end with exit 0 and no resume state,after a sequential or a parallel interruption: the first carries the reports the interrupted run wrote and clears the resume state,
per-stream files included, and the second, which finds no state, collects those subscriptions again.
The unreadable subscriptions are named only in the console output and the wrapper's transcript; no report zip holds them, with or
without
-Obfuscate. No script parameter is added, no exit code is added except the exit 1 for a per-stream file that cannot bemoved aside (strict-mode update below), and there are no extra Azure calls:
Resolve-AccessPreflighttakes the number of completed subscriptions in scope (
-CompletedCount),Write-AccessPreflightReporttakes-Resumefor thewords, and
Write-PendingRetrySkippedSummaryprints thePending Retrieslines; both take the fix for each cause fromWrite-AccessRemedyLines, so the fixes read the same.Add-RoleCheckRetryAttemptsandUpdate-ResumeStateRetryListkeep theretry list, and
Move-UnreadableStreamStateFileandWrite-UnreadableStreamStateSummaryhandle a per-stream file that cannot beread;
Remove-ResumeStateFilesremoves the resume state files with a check. The README's parallel section describes aper-stream file that cannot be read and a resume state file that cannot be removed, and its role-check section describes the
-Resumecase, and its paragraph on roles that leave out some resource types now says such a subscription is not readable (it isskipped, as the paragraph's last sentence says) instead of saying it stops the run.
Strict mode and per-stream resume files (November 2026 update)
nextLink, a check result withoutFailed, a failed call's status, and a usage rowwithout
additionalInfoare now read safely underSet-StrictMode -Version Latest, so a caller running strict mode no longerstops the run. The consumption sheet is byte for byte the same.
does what the start of a
-Resumerun does: it warns, renames the file to<name>.unreadable-<UTC time>(with-2,-3andso on when that name is taken), and a later
-Resumecollects its subscriptions.of
-Resumeor-ResumeFailedOnlythe run stops there with exit 1, before it collects anything. Found by the end-of-runmerge, the run ends with exit 1 in place of 0 and 3-5 (exit 2 keeps its code). The README's parallel section and exit code
table say so.
whose records were not saved, or that cannot be removed, and compares whole entries when it reads the state back. The writer
of the retry list stops on any write error, so a file cut short never replaces the state.
nullentry aswritten is fine); each retry entry needs a
LastFailedAtdate; a null or empty completed id makes the file unreadable.there are none.
Tested: new
Tests/StreamStateFileRead.Tests.ps1andTests/StrictModeArmPages.Tests.ps1, and new cases in the existingfiles; full Pester suite, test by test, with no new failure; PSScriptAnalyzer one file at a time, with no new finding. Live
runs, plain and with
-Obfuscate, were made with this PR on top of the Az PowerShell-only PR (#66), because the test host hasno Azure CLI; inventory, consumption and metrics were the same as that base. Not run live against
main, and not run onWindows.
Testing
New Pester tests for the role check (role evaluation, scopes, the combination of the two answers, retries, call sites,
-AllowPartialAccess,-Resume, end-of-run labels) and for the usage values check (verdicts, paging, page cap, retries, window,empty subscriptions, failure message, the
NoUsagepass for each combination of the two role-check answers, the end-of-run list,both call sites passing the role-check results); they fail against the code before each change and pass on this branch.
The tests that pin unchanged stops (
Denied,Error, and no usage without both answers) pass before and after the second commit.Tests added in this revision: a role that leaves out some resource types (each not-action form, the allowed namespaces, not-actions
that are not reads, Reader beside such a role, both answers, the wrapper with and without
-AllowPartialAccess, a direct run),the fix text per cause, the 1000-page limit of the role assignment list, a refused role definition read once per run, one window
per run (written culture-independently, invalid values ignored with a warning, a collection after midnight, all three places the
wrapper starts
ResourceInventory.ps1), resource group runs (rows of other resource groups, matching without case, the resourcegroup count and exemption, an invalid name, a usage row without a resource URI, direct runs) and the wording at the 50-page
limit. Against the previous head 82 of them fail and 7 pass; the 7 pin behaviour that is meant to stay (Reader beside a narrower
role, the fix text for no access, not visible and resource group not found, reading a role definition again after a server
error, and every place the wrapper starts
ResourceInventory.ps1passing the same argument set).Tests added or changed in this revision:
provider namespace) and against URIs that are not resource URIs: all fail on the previous head and pass now;
nextLink, an answer outside 2xx with Azure's message(403
Denied, 400 not retried, 429 and 503 retried), and malformed answers (a 200 that is not JSON, anextLinkthat is not aURL or has no token), each stopping that subscription;
UpFrontChecksParallel.Tests.ps1: the same stand-in answers checked one at a time and 8 at a time give the same records,results and lines; two subscriptions checked at the same time each get their own usage answer; the lines stay in subscription
order when an earlier subscription finishes last; a shared role definition is read once; nothing that runs in parallel can
call a context cmdlet; a check that throws becomes a failing record;
with exit 1 when none is readable; a direct run leaves the skipped subscription's resources out;
nextLinkthat names another host is asked for by its path and query, with no request to thathost; a
nextLinkthat is not a URL, is a relative path, is not http(s), has no path or a path starting with//counts as amissing answer, and that subscription is skipped with the reason while the other is collected; the 1000-page limit and a lower
page limit still end the list, each page asked for by its path. All fail on the previous head and pass now. Live, a resource
list of 12 pages read through the role check's request function gave the same resource ids as following
nextLinkdirectly,every page asked for by its path.
The tests that expected the old stop (an unreadable subscription stopping the run, the
-AllowPartialAccesshint) now expect theskip. The usage tests that replaced
Get-UsageAggregatesandSet-AzContextnow replace the usage API call, with the sameexpected outcomes.
The test of the direct script's last lines still requires the no-usage and skipped-subscription lists right after the report
and zip logging, and now also accepts Report: name failed collectors, count consolidated subscriptions #51's exit 4 check after them (its comment lines, the failure count and one exit line,
nothing else), so it passes with or without Report: name failed collectors, count consolidated subscriptions #51.
Full suite: the same set of failures before and after this change (none added); lint clean on every changed script.
Previous revision: 413 passed / 162 failed / 22 skipped before, 500 / 162 / 22 after, the same 162 failures (pre-existing, in
other test files). This revision: 500 passed / 162 failed / 22 skipped before, 544 / 162 / 22 after, the same failures.
Previous update: 544 / 162 / 22 before, 550 / 162 / 22 after, the same 162 failures by name; lint clean on every changed script.
Latest update: 550 / 162 / 22 before, 604 / 162 / 22 after, the same 162 failures by name; lint clean on every changed file.
Tests added in the previous update: in
ConsumptionDataCheck.Tests.ps1, the usage date text (M/d/yyyy h:mm:ss ttwith a plainspace and no non-ASCII byte in the file; the same clock value for every
DateTimekind); andConsumptionWindowClock.Tests.ps1(with no clock passed the window is taken from the UTC date; two child
pwshprocesses withTZ=Pacific/Kiritimati(UTC+14) andTZ=Pacific/Pago_Pago(UTC-11), whose local dates always differ, get the same window; a clock that is passed still decides thewindow; the up-front check's default window is still
Get-ConsumptionWindow). The two-zone test is skipped on Windows, whereTZdoes not set a process's time zone. Against the previous head 3 of the 6 fail: both date tests (on a host whose en-US timepattern has U+202F, Linux here) and the two-zone test. The other 3 pass before and after: a passed clock, the up-front check's
default, and the default clock on a host that runs at UTC.
Tests added in the latest update, in
ReaderAccessCheck.Tests.ps1: the rule (Resolve-AccessPreflightwith and withoutcompleted subscriptions in scope); the words (
-Resumewith nothing left to collect, a-Resumestop with one cause and withthree, and the last line for each cause); the
Pending Retrieslines (Write-PendingRetrySkippedSummaryfor each cause and formixed causes, and where the wrapper calls it); the helpers for the retry list and for a per-stream file that cannot be read
(
Add-RoleCheckRetryAttempts,Update-ResumeStateRetryListkeeping other keys,Move-UnreadableStreamStateFileincluding arename that fails and the
-ResumeFailedOnlywords,Write-UnreadableStreamStateSummary, andRemove-ResumeStateFileswith aremoval that fails, a per-stream file that fails, and a file still there after the removal); the wrapper's check block (a subscription whose check could not finish,
or whose answers disagree, put on the retry list, also before a stop and taken off the completed list; none without a read role,
and no state written when nothing is skipped for such a cause); (
-Resumewith a completed subscription and the rest unreadable, a stop without-Resumealthough the state records completed subscriptions, a
-Resumestop when the only completed subscription is out of scope); andruns of
Run-AllSubscriptions.ps1itself, each its ownpwshprocess, with stand-ins forResourceInventory.ps1and Azure:after an interrupted run, two
-Resumeruns in a row end with exit 0, list the skipped subscription, clear the state, and thefirst ends its output like a
-Resumewith nothing left to collect; a run without-Resumestops; a-Resumewith no completedsubscription stops with the new words, a run without
-Resumethen stops too, and after Reader is granted-Resumecollects thesubscription and clears the state; under
-Obfuscateno zip (every entry opened, nested zips too) holds the skippedsubscription's id or name; with
-ParallelStreams 2and with the automatic value (the process is given 4 vCPU withDOTNET_PROCESSOR_COUNT), after one completed subscription and after three (a two-stream run, then-Resume), the finish caseprints the one-stream
Parallelism:line, skips every completed subscription (noProcessing subscription:or[stream-N] processingline for them) and leaves no resume state; and a subscription on the retry list that can no longer be read is namedunder
Pending Retriesby a run without-Resumeand by-Resume,-ResumeFailedOnlystill stops with exit 1 until Reader isgranted, then retries it and clears the state; and after a two-stream run whose session ended while it collected the last
subscription, which then cannot be read,
-Resumewith-ParallelStreams 2, the automatic value and-ParallelStreams 1recovers the per-stream state, skips both completed subscriptions, and leaves no main or per-stream state file, and the next
-Resumeprints no recovery line and collects both again; after such a run whose stream file for one subscription was cut short,-Resumewith-ParallelStreams 1,2and the automatic value prints the warning, moves the file aside, collects thatsubscription again, ends with the cleared-but-not-clean line and no state, and the next
-Resumeends clean with no warning andno recovery line, and with nothing left to collect the run deletes only the file it read; a subscription whose check cannot
finish, or whose answers disagree, stays on the retry list through a run without
-Resumeand then a-Resume, or a-ResumeFailedOnlythat stops (count 1, 2), then is collected by the same kind of run once its check passes and the state clears;one without a read role is not put on it; under
-ResumeFailedOnly, a cut-short stream file gets the-ResumeFailedOnlywords andthe next
-Resumecollects the subscription it named; and with the inventory root made read-only during a-Resumewithnothing left to collect, the run names both per-stream files it could not remove, keeps the resume state and does not print the
clean-run line, and the next
-Resume, with the folder writable again, ends withResume state cleared (clean run).and noresume state file (that test first checks that a write into the read-only folder is refused, and is skipped when it is not, for
example as root). If the host's memory makes the automatic value one stream, the
automatic cases of the earlier test are reported as inconclusive. Against the head before this update (
pr-38~7) 49 of the 54 fail: there the end-to-end tests of the finish case, with anystream count, fail at the stop, for example
Expected $null or empty, but got ' No subscription is readable. Stopping before any work. Grant the identity Reader on these subscriptions, then re-run.'orExpected 0, but got 1.(the exit code), and thecut-short and retry-list tests fail, for example with
Expected 'Resume state cleared (clean run).' to not be found in collection. The 5 that pass pin behaviour that is meant to stay: the two stops without-Resume, the-Obfuscatecase with areadable subscription left, no retry-list entry for a subscription without a read role, and no state written when nothing is
skipped for a cause that can pass later. Against the first commit of this update (
pr-38~6) 41 fail; the cases with 2 streamsand the automatic value fail there, for example with
Expected 'Processing subscription: Sub A (sub-a)' to not be found in collection(one completed subscription) orExpected 'Skipping (already completed): Sub A (sub-a)' to be found in collection(three completed, or an interrupted parallel run). Against the second (
pr-38~5) 31 fail, and against the third (pr-38~4) 23:the cut-short stream file, for example
Expected 1, but got 0.for the warning line, the retry list, for exampleExpected 'sub-c|1|skipped by the up-front role check: role check inconclusive after retries (caller permissions: HTTP 429)', but got $null., and the new firstPending Retriesline. Against the sixth (pr-38~1) 6 fail: the-ResumeFailedOnlywords of thewarning, the removal helper (
The term 'Remove-ResumeStateFiles' is not recognized ...), and the read-only folder, where thatcommit printed the clean-run line with the files still there (
Expected 'Resume state cleared (clean run).' to not be found in collection).ConsumptionDataCheck.Tests.ps1: the direct-run tests startResourceInventory.ps1from the repository root, as those inReaderAccessCheck.Tests.ps1do.ResourceInventory.ps1reads./Version.jsonfrom the current folder and ends with exit 0without it, so 4 of them failed when Pester was started from another folder (98 / 4 from
/tmpbefore, 102 / 0 from/tmpandfrom the repository root now).
With Carry earlier reports into the -Resume bundle #48 and Keep the resume state while -ResumeFailedOnly leaves a subscription not collected #62 merged (with and without Keep the -Resume completed-ids list an array #49), Keep the resume state while -ResumeFailedOnly leaves a subscription not collected #62's
ResumeStateNotReadable.Tests.ps1passes 8 of 8; its two tests of a-Resumewith only unreadable subscriptions left failed before this update. On the same merges, the finish case with-ParallelStreams 2and with the automatic value carries every earlier report into the consolidated zip and collects none ofthose subscriptions again, after one, two (with Keep the -Resume completed-ids list an array #49) and three completed subscriptions; after an interrupted two-stream run it
carries both reports, leaves no main or per-stream state file, and the next
-Resumerecovers nothing and collects both again(also after the removal failed once with the folder read-only);
after such a run whose stream file for one subscription was cut short, the first
-Resume(one stream, two, automatic) carriesthe report recorded in the file it read, collects the other subscription again, and ends with no state, and the second ends
clean. With the retry limit of 3 failed runs merged as well, a subscription whose check keeps failing (
UnknownorDisagree)is skipped and counted by a run without
-Resume, by-Resumeand by a stopped-ResumeFailedOnly, is no longer retried afterthe third, and the next
-Resumeclears the state; no zip holds its id, name or retry reason under-Obfuscate.Live, the same two changes on a Linux host (a test branch that also carries other fixes, the small test tenant, default
settings): every usage date value had a plain space and no other non-ASCII character, and a run under
TZ=America/Los_Angelesat 04:21 UTC, when the Los Angeles date was still the day before, collected the same window as theUTC run (27 September to 27 October). This branch itself was not run live.
Live in this revision, normal user sign-in (Owner), the 3 subscriptions of a small test tenant,
Run-AllSubscriptions.ps1 -SkipMetrics(consumption on), previous head and this revision, two runs each: the same verdicts (all 3 readable; 2 with usagevalues, 4 and 534 rows on the first page; 1 with no resources, not checked), the same 3 subscriptions processed, 11,037 resources
and 538 consumption records, and exit 4 in all four runs from the scale set collector failure fixed in Fix VMSS collector failing on Flexible scale sets #39. The saved default
subscription did not change. Check times are under Cost.
Skipping an unreadable subscription was not tested live (it needs a second identity). Offline, with the wrapper's own statements
from the up-front check to the exit code, the real
ResourceInventory.ps1, and stand-ins for Azure, 3 subscriptions with 1unreadable: both skip it and list it after the check, the wrapper lists it again at the end, both collect the other 2, and the
wrapper exits 0, as
-AllowPartialAccessdid on the previous head. All 3 unreadable, or a direct run whose-SubscriptionIDisunreadable: exit 1. A readable subscription with no usage values whose usage permission only Azure confirms: exit 1, as before.
With
-AllowPartialAccess: the same as without it.Live, on a test subscription, with one test service principal whose role was changed between runs (previous revisions; in
this revision the rows that stopped with "no read access" skip that subscription instead, and stop with exit 1 only because it is
the only one):
Microsoft.Commerce/*-ResourceGrouprun: passes and collects that groupMicrosoft.Authorization/*Live, normal user sign-in (Owner), on an otherwise empty test subscription holding one network security group (free, so no usage):
ResourceInventory.ps1 -SubscriptionID <that subscription>[NoRows] <subscription-name> - the query succeeded but returned no usage rows[NoUsage]warning namingOwner at subscription, the run completes, the subscription is listed again at the endRun-AllSubscriptions.ps1on the tenant (this subscription and two with usage)NoUsage) and are processed; the summary lists theNoUsagesubscription; exit 4 from the scale set collector failure fixed in Fix VMSS collector failing on Flexible scale sets #39Not run on
mainfor this case.Live, normal user sign-in (Owner), direct runs with
-ResourceGroupon a test subscription whose only usage comes from oneresource in another resource group:
ResourceInventory.ps1 -SubscriptionID <that subscription> -ResourceGroup <new group with one network security group>[Pass] <subscription-name> - usage values found (4 row(s) read over 1 page(s)); the consumption sheet has 0 rows[NoUsage] <subscription-name> - the query succeeded but returned no usage rows for resource group '<new group>'; the usage permission is confirmed by the role assignments and by Azure (Owner at subscription)and the warning that this resource group's sheet will be empty; the run completes; 0 rows... -ResourceGroup <group that holds the resource with usage>[Pass] <subscription-name> - usage values found for resource group '<group>' (4 row(s) read over 1 page(s)); the consumption sheet has 4 rowsSeen live without the change: the identity that can only see the subscription got exit 0 and an empty report from both scripts,
and on main the identity without
Microsoft.Commerce/*got "Consumption access confirmed", "Records found: 0" and an emptyconsumption sheet.
With a normal user sign-in (Owner) on a small tenant: both checks pass for every subscription and the run completes; 20
back-to-back readings of both answers agreed every time. The usage check also passed under UTC, Los Angeles and Sydney time zones.
Limitations
usage permission in both answers, it now passes with the
NoUsagewarning (empty consumption sheet) instead of stopping; otherwiseit stops with
NoRows. Not tested; the warning and the README troubleshooting entry mention it.assignments, role conditions, and access delegated from another tenant (Azure Lighthouse). The group-membership path was verified
live separately and is covered by a unit test.
stops when it is the only one), and the list asks to wait and re-run.
the test tenant, which was not done for this revision), a run crossing midnight, the 50-page limit wording, the fix text per cause,
the role assignment list limit and the refused role definition read. Only the resource group runs were repeated live.
Microsoft.*/read)instead of a role with
*/readis treated as unable to read that subscription, so the subscription is skipped (the run stops whenno subscription is readable), where
maincollects what those roles can read. Add Reader instead.normal user sign-in: Resource Graph's
resourcestable held no row of those namespaces across every visible subscription, and amanagement lock created on a test resource group did not appear there within 3 minutes (the lock was then removed).
the times for 100 and 1,000 subscriptions are projections. A direct run's end-of-run list of skipped subscriptions is covered by a
unit test and a check that the script ends with it, not by an offline run to the end.
Get-UsageAggregates. The dates are sent as UTC midnights; in thelive runs above it returned the same first-page rows (4 and 534) as the cmdlet did for the same window.
ResourceInventory.ps1: both add lines right afterResourceInventoryAvd. Keep both, theskipped-resource filter first, so Memory 1/4: write the inventory per collector and release its data #41's resource count leaves the skipped subscriptions out.
-Resumechange of the latest update was not tested against Azure: it needs an identity that loses read access to asubscription between two runs. Its end-to-end tests run the wrapper with
-ParallelStreams 1,2and the automatic value.-ParallelStreams2 or more (also when it is chosen automatically), any other-Resumerun still gives the subscriptionsrecorded as completed to the parallel streams, or to the path for a single subscription left, which collect them again: they read
only each stream's own state file from an interrupted parallel run, not the main resume state. This happens when readable
subscriptions are left to collect, and when every subscription in scope is already completed and none was skipped as not
readable. It is the same on
main; this PR does not change it. Only the case this PR adds, where every subscription left to checkis not readable, runs one stream and skips them.
-Resume(readable subscriptions left,-ParallelStreams 1)or
-ResumeFailedOnly(its retry list, collected one at a time), clears the main resume state at its end but leaves theper-stream state files it read, so every later
-ResumeprintsRecovered per-stream state from an interrupted parallel runandskips the subscriptions they list again. It is the same on
main; this PR does not change it. The finish case this PR adds, anda run that moved a per-stream file aside, delete the files they read when they clear the state, and keep them when they keep the
state.
fails it can still print
Resume state cleared (clean run)., and a later-Resumerecovers that file again. It is the same onmain; this PR does not change that merge. The clean-up this PR adds checks each removal and names any file it could not remove.Build-MainSummaryFromZip.ps1 -PackageZipwith-OutputDirectoryset to the inventory root zips every file there,the resume state file and a per-stream file moved aside included (a leading dot does not hide a file on Windows). It is the same
on
mainfor the resume state file; this PR does not change that script. On Linux neither file is taken. The open PR Zip only the summary and this call's report folders with -PackageZip #67limits that zip to the summary and the report folders the call reconstructs.
-ResumeFailedOnlywhose retry list holds only subscriptions without a read role still stops with exit 1 on every run untilReader is granted; those runs are not counted toward a retry limit. Only skips for a cause that can pass later are counted.
Recovered per-stream state from an interrupted parallel run: N completed, M failed subscription record(s).line counts theempty failure entry each stream file holds when nothing failed, so it can say
2 failedwhen nothing failed. It is the same onmain; this PR does not change it.UTC only offline (the two-zone test). Not run on macOS.
How to test
Quick check (no Azure)
Needs PowerShell 7 and Pester 5 (
Install-Module Pester -MinimumVersion 5.0 -Scope CurrentUser).The tests define their own stand-ins for the Az cmdlets they call (
Get-AzContext,Set-AzContext,Get-AzAccessToken,Invoke-AzRestMethod), so no Azure sign-in is needed.UpFrontChecksParallel.Tests.ps1writes a small stand-in module to its test folder, so the checks' parallel runspaces load it instead of Az.From the repository root:
mainReaderAccessCheck.Tests.ps1Tests Passed: 2, Failed: 220Tests Passed: 222, Failed: 0ConsumptionDataCheck.Tests.ps1Tests Passed: 0, Failed: 102Tests Passed: 102, Failed: 0RunAllSubscriptionsReconciliation.Tests.ps1Tests Passed: 32, Failed: 4Tests Passed: 36, Failed: 0UpFrontChecksParallel.Tests.ps1Tests Passed: 0, Failed: 8Tests Passed: 8, Failed: 0ConsumptionWindowClock.Tests.ps1Tests Passed: 0, Failed: 4Tests Passed: 4, Failed: 0On
main:ReaderAccessCheck: the role check does not exist, so most tests fail withThe term 'Get-RoleCheckAction' is not recognized as a name of a cmdlet, function, script file, or executable program.(or the same for another role-check function), and the call-site tests fail becauseResourceInventory.ps1andRun-AllSubscriptions.ps1never call it.The 2 that pass cover runs where no check is expected (
-RunAllSubs, and-ResourceGroupwithout-SubscriptionID).ConsumptionDataCheck: stops in setup withExpected function 'Get-ConsumptionWindow' to be defined by Functions/Common.Functions.ps1.RunAllSubscriptionsReconciliation:no longer defines the first-subscription consumption gatefails withExpected $null or empty, but got Get-ConsumptionAccessOutcome.The three
Resolve-AccessPreflighttests about skipping fail too, becausemainstops on any unreadable subscription, for exampleExpected $false, because the run skips the unreadable sub and collects the readable one, but got $true.UpFrontChecksParallel: stops in setup withThe term 'Get-ConsumptionWindow' is not recognized as a name of a cmdlet, function, script file, or executable program.ConsumptionWindowClock: the same message forGet-ConsumptionWindow, and the two-zone test fails withExpected '14', because the child must really run at UTC+14, but got $null.Usage dates and window (no Azure)
The two consumption-sheet changes of the previous update, against the head before that update (
pr-38~9). The date tests inConsumptionDataCheck.Tests.ps1show the date text; on the Linux test host both fail on that head, the first withExpected strings to be the same, but they were different.(the text has U+202F beforeAM). The window, on Linux:At 12:57 UTC on 28 October that head printed
2026-09-28 to 2026-10-28and2026-09-27 to 2026-10-27(the hosts' localdates); this branch printed
2026-09-27 to 2026-10-27twice (the UTC date). The two zones are 25 hours apart, so on that head thelines always differ by one or two days.
-Resumewith only unreadable subscriptions left (no Azure)The latest update (seven commits), against the head before it (
pr-38~7), with this PR'sReaderAccessCheck.Tests.ps1:The head before the update gives
Tests Passed: 173, Failed: 49and this branchTests Passed: 222, Failed: 0. The end-to-end testsstart
Run-AllSubscriptions.ps1as its ownpwshprocess from a copy of the tool in the temp folder, with stand-ins forResourceInventory.ps1and Azure, and are skipped on Windows; the cases with 2 streams and the automatic value take a fewseconds more each, and the interrupted parallel runs end their first run themselves once both streams have recorded a completed
subscription; the cut-short case then removes the last
}from one stream file. On the head before the update the first of them fails withExpected $null or empty, but got ' No subscription is readable. Stopping before any work. Grant the identity Reader on these subscriptions, then re-run.'.(Not run exactly as written: the two commits were tested from exported copies instead of a
git worktree.)Reproduce on Azure (test subscription)
No cost: a service principal and custom roles are free, and the runs only read.
Needs the Azure CLI and PowerShell 7 with the Az modules, signed in as yourself with rights to create app registrations and role assignments (for example Owner) on the test subscription.
The test identity signs in under a throwaway home folder, so your own sign-ins are not touched.
After every role change, wait about 5 minutes before running (role changes take a few minutes to apply).
For the Reader control in step 6 the subscription needs some usage in the last 31 days (any resource that has run).
Create the test identity and two custom roles:
(Not run exactly as written: the identity, secret and roles were created with equivalent commands that were not recorded verbatim, under other names.)
A helper that runs a command as the test identity (bash):
Run
signinagain after each role change. If it reports that no subscriptions were found, the role has not applied yet; wait and retry.(Not run exactly as written: the sign-in used the same two logins in a throwaway home folder, from a longer script.)
Read access, identity that can only see the subscription:
Run the two tool commands from the repository root, once with
mainchecked out (git checkout --detach origin/main) and once on this branch (git checkout pr-38).On
mainboth scripts end withexit 0and an empty report. The wrapper's existing check passes, because Azure answers the resource-group list with an empty list instead of refusing:(The
mainpart was not run exactly as written: these lines come from runs of an earlier commit of this change whose wrapper access check ismain's code unchanged; a direct run onmainhas no up-front check at all.)On this branch both scripts stop before any inventory work with
exit 1, because the only subscription is not readable:With more than one subscription in scope, the ones that are not readable are listed the same way, followed by
Skipping them and continuing with the <n> readable subscription(s). To include them: ..., and the run continues; they are listedagain at the end under
Subscriptions skipped (not readable by the signed-in identity).(Not run exactly as written: step 3 was run live on an earlier commit of this change, which printed the same lines with
Stopping before any work. ...instead ofNo subscription is readable. Stopping before any work. ...; this revision's linescome from the offline runs and tests.)
Usage values, identity with Reader minus
Microsoft.Commerce/*:On
main(git checkout --detach origin/main), run the wrapper:Nothing fails: the usage API answers this identity with success and zero rows, and the existing check treats that as access.
The run completes with no error about usage data:
Consumption_ResourcesReport_<timestamp>.csvholds only its header line and the end summary has no consumption line.(The recorded run ended with exit 4, which came from the unrelated scale set collector failure fixed in Fix VMSS collector failing on Flexible scale sets #39.)
Same identity on this branch (
git checkout pr-38), direct run:The role check passes and the usage values check stops the run with
exit 1, before any inventory work:The wrapper (
Run-AllSubscriptions.ps1 -TenantID "$TENANT") runs the same two checks before its own work.(Not run exactly as written for the wrapper: with this identity it was run on an earlier commit of this change, where it stopped with the same
[NoRows]refusal and exit 1.)Control, built-in Reader on the subscription, this branch:
Both checks pass and the run continues:
The run ends with
exit 0. Run the same command onmain: the inventory records and the consumption rows are the same.(Not run exactly as written: the recorded comparison was against an earlier commit of this change instead of
main.)Zero usage with the usage permission confirmed, signed in as yourself (Owner or Reader at the subscription), this branch.
Use a test subscription with no resources and no usage, and add one network security group (free):
The usage check passes the subscription with a yellow warning and the run continues:
At the end of the run:
The run ends with
exit 0. On the first commit of this PR the same command stopped withexit 1and[NoRows] <subscription-name> - the query succeeded but returned no usage rows.If the subscription has never used
Microsoft.Network, the CLI registers that resource provider first (free).(Not run exactly as written: the resource group name had a UTC timestamp suffix, and the resource count was read from the
query's JSON output instead of with
--query.)Clean up:
az group delete --subscription "$SUB" -n "$RG" --yes, thenaz group exists --subscription "$SUB" -n "$RG"printsfalse.Resource group run, signed in as yourself, this branch. Use a subscription that has usage in one resource group
(
<group-with-usage>) and add a new resource group with one network security group (free):The first run passes the resource group with a yellow warning and completes; its consumption sheet has no rows:
The second passes with
[Pass] <subscription-name> - usage values found for resource group '<group-with-usage>' (<n> row(s) read over 1 page(s))and its consumption sheet has rows. On the previous head of this PR the first run printed
[Pass] <subscription-name> - usage values found (<n> row(s) read over 1 page(s))from usage elsewhere in the subscription andwrote an empty consumption sheet.
(Not run exactly as written: the resource group name had a UTC timestamp suffix, and the resource count was read with a
summarize count()query.)Clean up:
az group delete --subscription "$SUB" -n "$RG2" --yes, thenaz group exists --subscription "$SUB" -n "$RG2"printsfalse.Clean up (signed in as yourself):
(Not run exactly as written: the same objects were removed, purged and each checked with a fresh query, using equivalent commands that were not recorded verbatim.)
What to look for
-Resumelists them, printsSkipping them and finishing the run: ..., thenParallelism: -ParallelStreams 1 (nothing is left to collect, ...)when more than one streamwas asked for or chosen, skips each completed subscription and ends instead of stopping; with no completed subscription it stops
and says to run
-Resumeagain.Pending Retrieslines at the end name it with itsreason and the fix for that cause before
-ResumeFailedOnly.-ResumeprintsWARNING: The per-stream state file ... could not be read ..., a.resume-state-*-stream-*.json.unreadable-*file is left inInventoryReports, thesubscriptions that file listed are collected again, and the run ends with
Resume state cleared, but not a clean run: ...; the-Resumeafter it prints no warning and ends withResume state cleared (clean run).Pending Retriesat the end, thestate file keeps it in
FailedAttemptswithAttemptsone higher after each run that skips it, also after a-ResumeFailedOnlythat stops with exit 1.
InventoryReports): aWARNING: Could not remove ...line names it, and there is noResume state cleared (clean run)..-ResumeprintsRecovered per-stream state ...andResume state cleared (clean run)., and no.resume-state-*file is left inInventoryReports; the next-Resumeprints no recovery line.
[NoUsage]line with the role and scope, theWARNING: no usage above zero ...line, the run continues, and the subscription is listed again underSubscriptions with no usage valuesat the end.Consumption_ResourcesReport_<timestamp>.csv: onmain, the identity withoutMicrosoft.Commerce/*gets a file with only the header line and no error; on this branch that run does not start.-ResourceGrouprun: the usage lines name the resource group, and a pass needs usage in that resource group.Inventory_ResourcesReport_<timestamp>.jsononmainhas no records and the wrapper labels the subscriptionGENUINELY EMPTY; on this branch the run stops before any inventory file is written.