#!/usr/bin/env bash # Trimline read-only Azure waste scan, release h19. # # What it does # Uses the az CLI login you already have (Azure Cloud Shell, or any shell after `az login`) to read # inventory, 30 days of utilization metrics, 30 days of actual cost and Azure Advisor cost # recommendations, then writes a JSON bundle and a summary into a new folder in your home directory. # # What it never does # - It never creates, changes, stops or deletes anything in Azure. Every az call goes through # az_allowed() below, which refuses any command that is not on a short read-only allowlist. # The same check is installed as a temporary `az` wrapper in front of the real az, so the # Python scanner it runs is held to the same list. # - It never sends your data anywhere. Output stays in your home directory. Two outbound reads happen: # the scanner download from the URL below (sha256-pinned) and, for list prices, the public # Azure Retail Prices API at prices.azure.com (GET, SKU and region names only). --no-prices skips # that, and with it the areas 2 to 4 savings engine, which needs list prices. # - It does not use sudo, install packages, install az extensions or change your az configuration. # # Allowed az commands (everything else is refused before az starts) # az account show | az account list | az graph query | az monitor metrics list # az monitor log-analytics query | az monitor activity-log list # az advisor recommendation list (without --refresh) # az rest GET on https://management.azure.com/ only # az rest POST only to three query endpoints, which take the query in a POST body and cannot change # any resource: # - Resource Graph (resources query, with paging) # - Cost Management query at a subscription, management group, billing account, # billing profile, department or enrollment account scope, and its next pages # - Azure Monitor metrics:getBatch on .metrics.monitor.azure.com (up to 50 # resources a call, with --resource https://metrics.monitor.azure.com) # az storage blob list | az storage blob download # only with --auth-mode login (your Microsoft Entra login, no keys, SAS or connection # strings), only for --focus with a storage URL: reads your cost export files. # # Usage # curl -fsSL https://singularity.foundationalit.net/finops/scan.sh -o scan.sh # less scan.sh # read it first # bash scan.sh # current subscription # bash scan.sh --all-subscriptions # every enabled subscription you can read # bash scan.sh --management-group ID --cost-scope ba:BILLING_ACCOUNT_ID # large estates, see --help # bash scan.sh --help # # Needs: bash, az (logged in), curl, sha256sum, tar, python3 3.9+ (Cloud Shell has all of these). # Falls back to a smaller bash + jq scan (janitor rules only) when python3 3.9+ is not available. set -euo pipefail umask 077 SCAN_VERSION="h19" SCANNER_TGZ="finops-scanner-h19.tar.gz" SCANNER_SHA256="95308338c09b3a6418b235cff15b388353e693605bd839a411dd089cfbae1ac2" az_allowed() { # Returns 0 only for read-only az invocations. Command words are the arguments before the first flag. local -a words=() local a for a in "$@"; do case "$a" in -*) break ;; esac words+=("$a") done local cmd="${words[*]:-}" case "$cmd" in "account show" | "account list" | "graph query" | "monitor metrics list" | \ "monitor log-analytics query" | "monitor activity-log list" | "version") return 0 ;; "storage blob list" | "storage blob download") local auth="" prev="" for a in "$@"; do case "$prev" in --auth-mode) auth="$a" ;; esac case "$a" in --auth-mode=*) auth="${a#*=}" ;; --account-key | --account-key=* | --sas-token | --sas-token=* | --connection-string | --connection-string=*) echo "scan.sh: refused az storage with a key, SAS token or connection string" >&2; return 1 ;; esac prev="$a" done if [ "$auth" = "login" ]; then return 0; fi echo "scan.sh: refused az $cmd without --auth-mode login" >&2 return 1 ;; "advisor recommendation list") for a in "$@"; do case "$a" in --refresh | -r) echo "scan.sh: refused az advisor --refresh (it triggers a new evaluation)" >&2; return 1 ;; esac done return 0 ;; "rest") local method="get" url="" prev="" res="" for a in "$@"; do case "$prev" in --method | -m) method="$a" ;; --url | --uri | -u) url="$a" ;; --resource) res="$a" ;; esac case "$a" in --method=*) method="${a#*=}" ;; --url=* | --uri=*) url="${a#*=}" ;; --resource=*) res="${a#*=}" ;; esac prev="$a" done local ba='([0-9]+|[Pp][Cc][Nn]\.[A-Za-z0-9]+|[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}(:[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}_[0-9]{4}-[0-9]{2}-[0-9]{2})?)' local scope="(subscriptions/[0-9a-fA-F-]{36}|providers/Microsoft\.Management/managementGroups/[A-Za-z0-9._()-]{1,90}|providers/Microsoft\.Billing/billingAccounts/$ba(/billingProfiles/[A-Za-z0-9_-]{1,128}|/departments/[A-Za-z0-9_-]{1,64}|/enrollmentAccounts/[A-Za-z0-9_-]{1,64})?)" local mgmt_post="^https://management\.azure\.com/(providers/Microsoft\.ResourceGraph/resources\?api-version=[0-9-]+(-preview)?|$scope/providers/Microsoft\.CostManagement/query\?api-version=[0-9-]+(-preview)?(&(\\\$|%24)top=[0-9]{1,5})?(&(\\\$|%24)skiptoken=[A-Za-z0-9%._~+/=-]+)?)\$" local metrics_post='^https://[a-z0-9]{2,40}\.metrics\.monitor\.azure\.com/subscriptions/[0-9a-fA-F-]{36}/metrics:getBatch\?[A-Za-z0-9=&%:.,/_*()~+-]+$' if [ -n "$res" ]; then case "$res" in https://metrics.monitor.azure.com | https://metrics.monitor.azure.com/) ;; *) echo "scan.sh: refused az rest --resource $res" >&2; return 1 ;; esac if ! printf '%s' "$url" | grep -Eq "$metrics_post"; then echo "scan.sh: refused az rest --resource outside metrics:getBatch" >&2; return 1; fi fi method="$(printf '%s' "$method" | tr '[:upper:]' '[:lower:]')" case "$method" in get) case "$url" in https://management.azure.com/*) return 0 ;; esac ;; post) if printf '%s' "$url" | grep -Eq "$mgmt_post" || printf '%s' "$url" | grep -Eq "$metrics_post"; then return 0 fi ;; esac echo "scan.sh: refused az rest $method $url" >&2 return 1 ;; esac echo "scan.sh: refused az ${cmd:-} (not on the read-only allowlist)" >&2 return 1 } usage() { cat <<'U' Trimline read-only Azure waste scan (h19) bash scan.sh [--subscription ID] [--all-subscriptions] [--management-group ID] [--cost-scope SCOPE] [--focus PATH|URL] [--parallel N] [--out DIR] [--no-prices] [--bash-only] [--check] --subscription ID scan this subscription (default: the one `az account show` returns) --all-subscriptions scan every enabled subscription this login can read --management-group ID scan every enabled subscription under this management group (its id, not the display name). Needs Reader at that management group. --cost-scope SCOPE read 30 days of cost for the whole estate in one paged query instead of one query per subscription. SCOPE is ba:, bp:/, mg:, or a full scope path. Needs a billing reader role (EA enrollment reader, MCA billing account or billing profile reader) or Cost Management Reader at the management group. Management group cost scopes do not cover MCA billing accounts (Microsoft). --focus PATH|URL read cost from your Cost Management export files (FOCUS or actual cost, CSV or CSV.gz) instead of the cost query: a local folder or file, or https://.blob.core.windows.net// (read with your login; needs Storage Blob Data Reader on that container) --parallel N subscriptions analyzed at once (default 6, max 16) --out DIR output folder (default: ~/trimline-scan-) --no-prices skip the public Azure Retail Prices API and the areas 2 to 4 engine that needs it --bash-only skip the Python scanner; janitor rules only, needs jq --check print the allowlist self-test and exit, no Azure calls Environment: TRIMLINE_BASE overrides the download base URL (https only, or http://127.0.0.1 for testing). U } die() { echo "scan.sh: $*" >&2; exit 1; } say() { printf '%s\n' "$*" >&2; } self_check() { local ok=0 az_allowed account show >/dev/null 2>&1 || ok=1 az_allowed graph query -q "Resources | take 1" >/dev/null 2>&1 || ok=1 az_allowed rest --method post --url "https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/providers/Microsoft.CostManagement/query?api-version=2023-03-01" >/dev/null 2>&1 || ok=1 az_allowed rest --method post --url "https://management.azure.com/providers/Microsoft.Billing/billingAccounts/12345678/providers/Microsoft.CostManagement/query?api-version=2023-11-01&\$top=5000&\$skiptoken=AQ%3D" >/dev/null 2>&1 || ok=1 az_allowed rest --method post --url "https://eastus.metrics.monitor.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/metrics:getBatch?metricnames=Percentage%20CPU&api-version=2023-10-01" --resource https://metrics.monitor.azure.com >/dev/null 2>&1 || ok=1 az_allowed storage blob list --auth-mode login --account-name a --container-name c >/dev/null 2>&1 || ok=1 local -a bad=("vm delete --ids x" "vm deallocate -g a -n b" "disk update -g a -n b" "group delete -n a" "role assignment create" "extension add -n x" "config set core.x=y" "advisor recommendation list --refresh" "rest --method put --url https://management.azure.com/subscriptions/x" "rest --method delete --url https://management.azure.com/x" "rest --method post --url https://management.azure.com/subscriptions/x/providers/Microsoft.Compute/virtualMachines/y/deallocate?api-version=2024-07-01" "--subscription x vm delete" "rest --method post --url https://management.azure.com/providers/Microsoft.Billing/billingAccounts/1/createBillingRoleAssignment?api-version=2024-04-01" "rest --method post --url https://eastus.metrics.monitor.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/metrics:getBatch?a=1 --resource https://storage.azure.com" "storage blob list --account-name a" "storage blob download --auth-mode login --account-key k" "storage blob upload --auth-mode login" "storage blob delete --auth-mode login" "storage account keys list") local b for b in "${bad[@]}"; do # shellcheck disable=SC2086 if az_allowed $b >/dev/null 2>&1; then echo "allowlist FAILED to refuse: az $b" >&2; ok=1; fi done return $ok } main() { local sub="" all=0 out="" no_prices=0 bash_only=0 mg="" cost_scope="" focus="" parallel=6 while [ $# -gt 0 ]; do case "$1" in --subscription) sub="${2:?--subscription needs an id}"; shift 2 ;; --all-subscriptions) all=1; shift ;; --management-group) mg="${2:?--management-group needs an id}"; shift 2 ;; --cost-scope) cost_scope="${2:?--cost-scope needs a scope}"; shift 2 ;; --focus) focus="${2:?--focus needs a path or URL}"; shift 2 ;; --parallel) parallel="${2:?--parallel needs a number}"; shift 2 case "$parallel" in '' | *[!0-9]*) die "--parallel needs a number" ;; esac ;; --out) out="${2:?--out needs a folder}"; shift 2 ;; --no-prices) no_prices=1; shift ;; --bash-only) bash_only=1; shift ;; --check) self_check && { echo "allowlist self-test: ok"; exit 0; } || exit 1 ;; -h | --help) usage; exit 0 ;; *) usage >&2; die "unknown option $1" ;; esac done self_check || die "allowlist self-test failed; not running" local t0; t0=$(date +%s) local real_az; real_az="$(command -v az || true)" [ -n "$real_az" ] || die "az CLI not found. Open Azure Cloud Shell (Bash) or install az and run az login." command -v curl >/dev/null || die "curl not found" # Keep this run quiet and side-effect free: no extension auto-install, no telemetry, no prompts. export AZURE_EXTENSION_USE_DYNAMIC_INSTALL=no export AZURE_CORE_COLLECT_TELEMETRY=false export AZURE_CORE_ONLY_SHOW_ERRORS=true export AZURE_CORE_NO_COLOR=true local work; work="$(mktemp -d "${TMPDIR:-/tmp}/trimline.XXXXXX")" # shellcheck disable=SC2064 trap "rm -rf '$work'" EXIT # Guarded az wrapper, first on PATH for this run only. Same allowlist as above. mkdir -p "$work/bin" { echo '#!/usr/bin/env bash' echo 'set -euo pipefail' declare -f az_allowed printf 'az_allowed "$@" || exit 97\nexec %q "$@"\n' "$real_az" } > "$work/bin/az" chmod 700 "$work/bin/az" export PATH="$work/bin:$PATH" [ "$(command -v az)" = "$work/bin/az" ] || die "could not install the read-only az wrapper" az account show -o none /dev/null || die "not logged in. Run az login (Cloud Shell is already logged in)." local -a subs=() if [ -n "$mg" ]; then subs=("management-group:$mg") elif [ -n "$sub" ]; then subs=("$sub") elif [ "$all" = 1 ]; then mapfile -t subs < <(az account list --query "[?state=='Enabled'].id" -o tsv /dev/null && python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 9) else 1)'; then py="python3"; mode="python-engine" fi if [ -z "$py" ]; then command -v jq >/dev/null || die "needs python3 3.9+ or jq" fi local estate=0 if [ -n "$py" ] && { [ -n "$mg" ] || [ -n "$cost_scope" ] || [ -n "$focus" ] || [ "${#subs[@]}" -gt 1 ]; }; then estate=1; fi if [ -z "$py" ] && { [ -n "$mg" ] || [ -n "$cost_scope" ] || [ -n "$focus" ]; }; then die "--management-group, --cost-scope and --focus need python3 3.9+" fi if [ -n "$mg" ]; then say "Trimline read-only scan $SCAN_VERSION: management group $mg, mode $mode, output $out" else say "Trimline read-only scan $SCAN_VERSION: ${#subs[@]} subscription(s), mode $mode, output $out" fi local base="${TRIMLINE_BASE:-https://singularity.foundationalit.net/finops}" case "$base" in https://* | http://127.0.0.1:* | http://localhost:*) ;; *) die "TRIMLINE_BASE must be https" ;; esac if [ -n "$py" ]; then curl -fsSL --proto '=https,http' "$base/scanner/$SCANNER_TGZ" -o "$work/scanner.tgz" "$work/subs.txt" pyargs+=(--subscriptions "@$work/subs.txt") fi if [ -n "$cost_scope" ]; then pyargs+=(--cost-scope "$cost_scope"); fi if [ -n "$focus" ]; then pyargs+=(--focus "$focus"); fi if [ "$no_prices" = 1 ]; then pyargs+=(--no-engine); fi (cd "$work/scanner" && PYTHONDONTWRITEBYTECODE=1 python3 -m finops_scanner "${pyargs[@]}" &2) || say " the estate scan reported a problem; writing what it read" subs=() fi for s in "${subs[@]}"; do i=$((i + 1)) say "[$i/${#subs[@]}] subscription $s" if [ -n "$py" ]; then local -a pyargs=(--subscription "$s" --out "$work/out/$s" --no-scripts) if [ "$no_prices" = 1 ]; then pyargs+=(--no-engine); fi if ! (cd "$work/scanner" && PYTHONDONTWRITEBYTECODE=1 python3 -m finops_scanner "${pyargs[@]}" &2); then say " scanner failed on $s; continuing" continue fi else bash_janitor "$s" "$work/out/$s" fi az advisor recommendation list --category Cost --subscription "$s" -o json "$work/out/$s/advisor.json" 2>/dev/null || echo '[]' > "$work/out/$s/advisor.json" done local elapsed=$(( $(date +%s) - t0 )) local bundle="$out/trimline-bundle.json" if [ -n "$py" ]; then python3 - "$work/out" "$bundle" "$SCAN_VERSION" "$mode" "$elapsed" "$estate" <<'PY' import gzip, json, os, sys, datetime src, dst, ver, mode, elapsed, estate_mode = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5]), sys.argv[6] == "1" # Estate runs: the bundle keeps what the report page reads (findings, costs, inventory counts, notes, # Advisor); each subscription's full scan is saved gzipped in full/ next to it. LEAN_DROP = ("disks", "public_ips", "snapshots", "vms", "vmss", "aks_pools", "metrics", "engine") full_dir = os.path.join(os.path.dirname(dst), "full") subs = [] estate = None try: estate = json.load(open(os.path.join(src, "estate.json"))) except Exception: pass for sid in sorted(os.listdir(src)): p = os.path.join(src, sid, "scan.json") if not os.path.exists(p): continue scan = json.load(open(p)) try: scan["advisor_cost"] = json.load(open(os.path.join(src, sid, "advisor.json"))) except Exception: scan["advisor_cost"] = [] if estate_mode: os.makedirs(full_dir, exist_ok=True) with gzip.open(os.path.join(full_dir, f"{sid}.json.gz"), "wt") as fh: json.dump(scan, fh, default=str) scan = {k: v for k, v in scan.items() if k not in LEAN_DROP} subs.append(scan) json.dump({"format": "trimline-scan-bundle", "bundle_version": 1, "scan_sh": ver, "mode": mode, "generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"), "elapsed_seconds": elapsed, "estate": estate, "subscriptions": subs}, open(dst, "w"), default=str, **({"separators": (",", ":")} if estate_mode else {"indent": 1})) PY else jq -s --arg v "$SCAN_VERSION" --arg m "$mode" --argjson e "$elapsed" \ '{format: "trimline-scan-bundle", bundle_version: 1, scan_sh: $v, mode: $m, generated_at: (now | todate), elapsed_seconds: $e, subscriptions: .}' \ "$work"/out/*/scan.json > "$bundle" fi summary "$bundle" "$elapsed" say "" say "Bundle: $bundle" say "View it: open $base/report.html and drop the bundle file on the page. The page reads it in your browser only." say "In Cloud Shell, run: download $bundle to save it to your computer first." say "Nothing was changed in Azure. Results stay in this folder; nothing was uploaded." } summary() { local bundle="$1" elapsed="$2" if command -v python3 >/dev/null; then python3 - "$bundle" "$elapsed" <<'PY' >&2 import json, sys b = json.load(open(sys.argv[1])) print("") print(f"Scan finished in {sys.argv[2]} s ({b['mode']}). All savings below are estimates from your own data.") e = b.get("estate") or {} subs = b["subscriptions"] if e: print(f"Estate: {e.get('scanned')} of {e.get('subscriptions')} subscriptions, {e.get('resources') or 0:,} resources, " f"30-day cost read {e.get('cost_total_30d') or 0:,.2f}, {e.get('findings')} findings, " f"estimated monthly savings, ready findings only: {e.get('est_monthly_savings_ready') or 0:,.2f}") for n in (e.get("notes") or [])[:5]: print(f" note: {n[:220]}") if e.get("error_count"): print(f" read errors: {e['error_count']}. First: {str((e.get('errors') or [''])[0])[:200]}") if len(subs) > 5: def est(s): return sum((x.get("est_monthly_savings") or 0) for x in s.get("findings", []) if x.get("verdict", "PASS") == "PASS" and not x.get("blocked")) subs = sorted(subs, key=lambda s: -est(s))[:5] print(f"\nTop 5 subscriptions by estimated savings (all {len(b['subscriptions'])} are in the bundle):") for s in subs: f = s.get("findings", []) ok = [x for x in f if x.get("verdict", "PASS") == "PASS" and not x.get("blocked")] est = sum((x.get("est_monthly_savings") or 0) for x in ok) blocked = len(f) - len(ok) print(f"\n{s.get('subscription_name') or 'Subscription'} ({s.get('subscription_id')})") print(f" findings: {len(f)} ready to review: {len(ok)} held by a safety gate: {blocked}") print(f" estimated monthly savings, ready findings only: {est:,.2f} USD") nc = sum(1 for x in ok if x.get("savings_capped")) if nc: print(f" {nc} finding(s) capped so savings on one resource never exceed its 30-day cost") for x in sorted(ok, key=lambda x: -(x.get("est_monthly_savings") or 0))[:10]: print(f" - {x.get('kind')}: {x.get('name')} ({x.get('resource_group')}) est {x.get('est_monthly_savings') or 0:,.2f}/mo. {x.get('action') or ''}") adv = s.get("advisor_cost") or [] if adv: seen = {} for r in adv: ep = r.get("extendedProperties") or {} key = ((r.get("shortDescription") or {}).get("problem") or "", ep.get("displaySKU") or ep.get("sku") or r.get("impactedValue") or "", ep.get("term") or "") try: amt = float(ep.get("savingsAmount") or 0) except ValueError: amt = 0.0 seen[key] = max(seen.get(key, 0.0), amt) print(f" Azure Advisor cost recommendations: {len(adv)} ({len(seen)} distinct). Microsoft's estimates, not checked by this scan:") for (prob, what, term), amt in sorted(seen.items(), key=lambda kv: -kv[1])[:5]: print(f" - {prob} [{what}{' ' + term if term else ''}]" + (f" Advisor est {amt:,.0f}/mo" if amt else "")) for r in (s.get("refusals") or [])[:3]: print(f" not estimated: {r.get('kind')}: {r.get('reason')}") for n in (s.get("notes") or [])[:3]: print(f" note: {n[:200]}") if s.get("errors"): print(f" read errors: {len(s['errors'])}. First: {str(s['errors'][0])[:200]}") PY else jq -r '.subscriptions[] | "\(.subscription_id): \(.findings | length) janitor findings"' "$bundle" >&2 fi } bash_janitor() { # Fallback without Python: unattached disks, unassociated public IPs, snapshots over 30 days, deallocated VMs. local s="$1" dir="$2" mkdir -p "$dir" local q='Resources | where (type =~ "microsoft.compute/disks" and properties.diskState =~ "Unattached") or (type =~ "microsoft.network/publicipaddresses" and isnull(properties.ipConfiguration) and isnull(properties.natGateway)) or (type =~ "microsoft.compute/snapshots" and todatetime(properties.timeCreated) < ago(30d)) | project id, name, type, resourceGroup, location, tags' local q2='Resources | where type =~ "microsoft.compute/virtualmachines" | extend ps = tostring(properties.extended.instanceView.powerState.code) | where ps =~ "PowerState/deallocated" | project id, name, type, resourceGroup, location, tags' page_all() { # Every page, 1,000 rows at a time (Resource Graph skip tokens). local query="$1" tok="" res while :; do if [ -n "$tok" ]; then res="$(az graph query -q "$query" --subscriptions "$s" --first 1000 --skip-token "$tok" -o json "$dir/scan.json" } main "$@"