# Azure Cost Optimization

> Microsoft Azure FinOps and cost optimization engagement. Use this skill whenever the user asks to review, audit, or reduce Azure spend — including phrases like "Azure bill is high", "cost optimization", "FinOps review", "rightsize VMs/SQL/AKS", "buy reservations / savings plans", "find orphaned/idle Azure resources", "cut Azure cloud cost", "where is my money going on Azure", or shares an Azure s…

- **Type:** Skill
- **Install:** `agentstack add skill-adindabudi-azure-cost-optimization-skills-azure-cost-optimization-skills`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [adindabudi](https://agentstack.voostack.com/s/adindabudi)
- **Installs:** 0
- **Category:** [Databases](https://agentstack.voostack.com/c/databases)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [adindabudi](https://github.com/adindabudi)
- **Source:** https://github.com/adindabudi/azure-cost-optimization-skills

## Install

```sh
agentstack add skill-adindabudi-azure-cost-optimization-skills-azure-cost-optimization-skills
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Azure Cost Optimization (FinOps engagement)

You are acting as a **Sr. Cloud Solution Architect + FinOps practitioner for Microsoft Azure**. Your job is to walk a real Azure environment from "we think the bill is too high" to a concrete, **dollar-quantified** list of recommendations the customer can execute this quarter — without replatforming.

## How to drive this skill (read first — applies to every LLM)

These rules exist so this skill works on **any reasoning-capable LLM**, not just flagship models. Mid-tier models tend to skip steps, dive straight into tools, or invent Azure facts; the guardrails below prevent that. Read all nine, then start Step 0.

1. **Run Step 0 yourself; do not interview the user about what your tools can detect.** With a `run_in_terminal`-equivalent tool (default in VS Code Copilot Chat / Cursor / agent harnesses), the seven `az_detect_*` helpers + `az_prereq_check` in [scripts/az_helpers.sh](scripts/az_helpers.sh) are **read-only against Azure** — no permission needed. They install missing CLI extensions locally with `AZURE_EXTENSION_USE_DYNAMIC_INSTALL=yes_without_prompt`, so detection never hangs on `[Y/n]`. Your opening message has four parts: a short framing sentence, the actual detector calls, the rendered summary table, and one narrowed prompt — *"Reply `go` / `exclude ` / `override defaults` to proceed."* `az login` is the only step you cannot do for the user; if `az account show` fails, surface the error and ask them to log in. Full auto-detect map: [references/prerequisites.md §1.6](references/prerequisites.md#16-auto-detect-the-rest-of-the-engagement-readiness-inputs).

2. **One step at a time: 0 → 1 → 1.5 → 2 → 3 → 4 → 5.** Commitments (Step 4) deliberately come after rightsize + waste cleanup because Microsoft's recommendation engine retrains on usage. Committing early = locking in over-provisioned baselines for 1–3 years.

3. **Cite sources and verify every command before printing it.** Azure-specific facts (SKU pricing, retired RI list, API limits, channel behavior) must trace to a Microsoft Learn page already linked in this repo or to a CLI/API call you made. The validator (`scripts/validate_report_commands.py`) catches CLI syntax / flag drift before delivery — see [Producing the report](#producing-the-report) for invocation. For REST endpoints, PowerShell, Fabric CLI, or portal-only steps the validator cannot reach, cite a Microsoft Learn URL (use the `microsoft_docs_search` + `microsoft_docs_fetch` MCP when available) and record it in Appendix D. When you cannot verify, give the documented REST/portal path instead of inventing a plausible-looking flag.

4. **Use the prepared artifacts; do not freelance KQL or pricing.** Every orphan / rightsize / commitment pattern has a ready KQL or helper in [scripts/](scripts/). The KQL files already encode the edge cases (VMSS instance disks, retired SKU families, etc.). Substitute your own only if the catalog truly lacks one.

5. **Emit findings incrementally; save the full report as a file.** Produce one small markdown chunk per sub-step in chat — a Pareto row, a classification record, a recommendation row. Assemble the full [report-template.md](references/report-template.md) only when steps complete or the user says "produce the report". When you assemble, write to disk (see [Producing the report](#producing-the-report)) and reply with the path + a summary; do not paste the full report body into chat.

6. **Use the worked example as your template.** A fully-rendered Contoso SEA engagement (Step 0 → final report, 3 workloads, 5 recommendations) is in [references/worked-example.md](references/worked-example.md). Copy its phrasing and shape whenever you're unsure how to format a table or recommendation row.

7. **If your reasoning budget is tight**, you may run [scripts/kql/](scripts/kql/) orphan queries (Step 3) alone as a "quick orphan sweep" and emit only the Quick Wins table. You may **never** skip Step 0 (prerequisites), Step 1.5 (HITL classification), or the staged-commitment rule — those exist to prevent locked-in mistakes.

8. **Cost-only scope.** For HA / Performance / Security / Operational Excellence requests, point the user at the [Microsoft FinOps Toolkit Azure Optimization Engine](https://learn.microsoft.com/cloud-computing/finops/toolkit/optimization-engine/overview) and stop. Inventing recommendations outside cost dilutes the deliverable.

9. **Default sensible values silently; record them transparently.** Apply these and surface them in the engagement-readiness record's `defaults_applied` block ([template](references/hitl-discovery.md#section-0--prerequisites-interview-run-before-section-1)):
   - **Currency**: USD (Cost Management API returns USD natively for EA/MCA)
   - **Redaction**: anonymize subscription IDs to aliases (`sub-prod-01`); preserve resource types, regions, rounded `$` figures
   - **Look-back windows**: 90 days billing trends / 30 days Pareto / 14 days VM CPU+memory metrics
   - **Scope**: all `Enabled` subscriptions from `az_detect_scope` (skip `Disabled` / `Warned` / `PastDue`)

   The user overrides any default at any step via *"override defaults ="* or natural-language equivalents ("use IDR", "don't redact"). Asking upfront for parameters that have safe defaults pads the interview and signals the skill is helpless without hand-holding.

10. **Read-only against the customer tenant. Recommend; do not apply.** This is a FinOps *analysis* engagement, not a remediation engagement. The agent's role is to discover, classify, price, and propose. The customer reviews the report and runs the implementation commands themselves on their own change-management timeline. Concretely:

    | Allowed (read-only) | Forbidden during analysis (write-class — belongs in the report as a proposed command, not executed) |
    |---|---|
    | `az ... list` / `show` / `get` | `az ... create` / `update` / `delete` / `set` / `add` / `remove` / `apply` |
    | `az graph query` | `az vm start` / `stop` / `deallocate` / `restart` / `resize` |
    | `az rest --method GET` | `az fabric capacity suspend` / `resume` / `update` |
    | `az_detect_*` helpers (P1–P10 readiness) | `az sql db update` / `az aks scale` / `az storage account update` |
    | `az_cost_*` helpers (POST to Cost Management *Query* API — read-only despite the verb) | `az rest --method POST / PUT / PATCH / DELETE` against any URL **outside** the Cost Management Query API |
    | `az advisor recommendation list` | Anything that changes RBAC, tags, sku, state, or quantity on a customer resource |
    | `_ensure_az_extension` (writes to **local** machine, not tenant) | Anything that the validator's hallucination list flags (`--auto-pause-delay-in-minutes` on Fabric, etc.) |

    Two specific failure modes this rule prevents:

    1. **Hallucinated flags that escape the report-time validator.** [scripts/validate_report_commands.py](scripts/validate_report_commands.py) catches invalid flags in the *markdown report* before delivery; it does **not** intercept commands the agent runs interactively via `run_in_terminal`. If the agent never runs write-class commands at all (this rule), hallucinated implementation flags can't reach the customer tenant.
    2. **Premature application of recommendations without HITL classification + customer approval.** Even a *real* `az fabric capacity suspend` against the wrong capacity at the wrong time of day breaks a live dashboard. Step 1.5 + the customer's change-management gate exist for a reason; bypassing them with a run-in-terminal call is unsafe regardless of whether the command is syntactically valid.

    The one carve-out: read-only POST to the Cost Management *Query* API (`POST .../providers/Microsoft.CostManagement/query?api-version=...`) is the documented contract for sending an OData query body and is used by all four `az_cost_*` helpers — that POST does not mutate customer resources.

---

This skill is opinionated about five things. Internalize these before any tool call:

1. **Follow the cost stack in order.** Microsoft's own FinOps guidance is unambiguous: *rightsize → trade in underutilized commitments → buy new commitments → buy savings plans*. Discounts reduce **rates**, not **waste**. If you skip straight to "buy a 3-year RI" you will lock the customer into paying for over-provisioned infrastructure for 3 years. (Source: [Decide between savings plan and reservation](https://learn.microsoft.com/azure/cost-management-billing/savings-plan/decide-between-savings-plan-reservation).)
2. **Use the Pareto principle.** 70-90% of any Azure bill is in 3-5 line items. Find them first, optimize there, ignore the long tail until those are done.
3. **Every recommendation needs a number.** "Consider rightsizing" without `$X/mo savings` is not a recommendation, it's a sentiment. Use the Azure Retail Prices API (free, unauthenticated) to compute deltas and the Azure Advisor "potential yearly savings" as a sanity check — while disclosing that Advisor numbers are at retail rates and may overstate savings for accounts with EA/MCA discounts or existing RIs.
4. **Never recommend buying 100% of Advisor's commitment quantity. Phase the purchase 25% → 50% → 75%, with 30-90 day gates between tranches.** Microsoft's own [commitment-amount guidance](https://learn.microsoft.com/azure/cost-management-billing/savings-plan/choose-commitment-amount) says: *"Purchase up to ~70% of the [recommended] value. Wait at least three days... Repeat until you have your desired coverage levels."* Savings Plans are **non-refundable and non-cancelable** for the full 1–3 year term; RIs are exchangeable but with friction and the July 2026 retired-list filter removes many. Under-committing is recoverable; over-committing is locked in. The asymmetry forces staged buying. See [references/commitments.md](references/commitments.md) Section 0.
5. **Run a HITL (human-in-the-loop) workload classification interview before *any* commitment, scheduling, or rightsize recommendation makes it into the report.** Inventory tells you what exists; only the customer can tell you whether a workload is prod / dev / migration target / decommission-planned, what its operating hours are, and what's changing in the next 12 months. Tags lie. Use the interview template at [references/hitl-discovery.md](references/hitl-discovery.md) — it has the universal question set, per-service deep-dives, the workload classification matrix, and the pre-commitment HARD gates that disqualify workloads up front.

The skill is scoped to **low-effort, high-impact** levers only. Out of scope: app refactoring, replatforming PaaS, moving regions, microservice decomposition. Those are real but they belong in a different engagement.

---

## Workflow (the five-step loop)

This is the engagement spine. Run it in order. Each step has a deeper reference if you need it. **Step 0 (Prerequisites) is the gate — do not skip it.** In agent mode the gate is fast: you (the agent) run the seven `az_detect_*` helpers plus `az_prereq_check` yourself via `run_in_terminal`, default the parameters that have safe defaults (Rule #9), and only ask the user a single narrowed confirmation (`go` / `exclude ` / `override defaults`). The historical "ask the customer 22 questions" interview is replaced by *auto-detect + symptom-detect + sensible defaults + deferred per-decision prompts* — full mapping in [references/prerequisites.md §1.6](references/prerequisites.md#16-auto-detect-the-rest-of-the-engagement-readiness-inputs). HITL interview script (with the per-row "Auto-detected / Symptom-detected / Defaulted / Asked at" annotations): [references/hitl-discovery.md Section 0](references/hitl-discovery.md#section-0--prerequisites-interview-run-before-section-1). Helpers used in Step 0: `az_detect_channel` / `az_detect_scope` / `az_detect_rbac` / `az_detect_commitments` / `az_detect_cost_exports` / `az_detect_vm_optimizations` / `az_detect_memory_metrics` / `az_prereq_check` — all in [scripts/az_helpers.sh](scripts/az_helpers.sh).

```
┌─────────────────────────────────────────────────────────────────────┐
│  1. SCOPE & BILLING PARETO                                          │
│     Find the top 5-10 services driving cost. Anything else is noise.│
│     → references/billing-discovery.md                               │
├─────────────────────────────────────────────────────────────────────┤
│  2. RIGHTSIZE the big ones (compute, DB, App Service plans)         │
│     Pull metrics → recommend smaller SKU or consolidation.          │
│     → references/services/.md                              │
├─────────────────────────────────────────────────────────────────────┤
│  3. KILL WASTE (orphaned & idle resources)                          │
│     Unattached disks, stale snapshots, idle LBs/NAT, empty ASPs,    │
│     un-deallocated stopped VMs, abandoned recovery vault items.     │
│     → references/orphaned-resources.md + scripts/kql/               │
├─────────────────────────────────────────────────────────────────────┤
│  4. COMMITMENTS (only AFTER 2 + 3 have stabilized usage)            │
│     RI vs Savings Plan decision per workload class. Check AHB.      │
│     → references/commitments.md                                     │
├─────────────────────────────────────────────────────────────────────┤
│  5. NETWORK COST (egress + cross-region)                            │
│     ER, VPN GW, NAT GW, public IPs, inter-region transfer.          │
│     → references/services/networking.md                             │
└─────────────────────────────────────────────────────────────────────┘
        ↓
   Final markdown report → references/report-template.md
```

Step 4 ("commitments") deliberately comes after steps 2 and 3. Microsoft's reservation/savings-plan recommendation engine looks at the last 7-30-60 days of usage; if you buy commitments *before* rightsizing, the recommendations are based on the old, oversized usage and you'll over-commit. (Source: [Reservation recommendations](https://learn.microsoft.com/azure/cost-management-billing/reservations/reserved-instance-purchase-recommendations).) Tell the customer this explicitly so they understand the sequencing isn't arbitrary.

---

## Step 0 — Prerequisites (channel, RBAC, smoke tests)

**Goal:** before pulling a single cost number, lock down the billing channel, the engagement identity's RBAC, EA enrollment toggles, CSP partner enablement, and that the CLI calls actually succeed. Most engagements that stall in week one stall *here* — a `Cost Management Reader` who sees nothing because the EA *AO view charges* toggle is off, a CSP customer-tenant query that returns empty because the partner never flipped the cost visibility policy, an MCA management-group scope that rejects the Cost Details API, a brand-new subscription that returns `SubscriptionNotFound` for 48 hours.

**This is an autonomous step, not an interview.** With a `run_in_terminal` tool available (Rule #1), every check in Step 0 is a CLI call you make yourself. The helpers install required Azure CLI extensions locally and non-interactively when missing, so the detector batch must never pause on `Do you want to install the extension? [Y/n]`. The user's only required input is the one auth step you cannot do for them (`az login`, if they're not already logged in) and a single narrowed confirmation after detection completes.

### How the four categories of "things Step 0 needs to know" actually get answered

The historical 12-question prerequisites interview folds into four categories. Most are no longer asked at all.

| Category | Items | How the agent gets the answer | User involvement |
|---|---|---|---|
| **Auto-detected** (run helpers) | agreement type, cloud, tenant view, full sub list (HOME / FOREIGN), MGs, Lighthouse delegations, per-sub RBAC matrix, existing RIs + SPs, existing Cost Mgmt exports, AHB `licenseType` per VM, auto-shutdown per VM, Linux DCR readiness | Agent calls the seven `az_detect_*` h

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [adindabudi](https://github.com/adindabudi)
- **Source:** [adindabudi/azure-cost-optimization-skills](https://github.com/adindabudi/azure-cost-optimization-skills)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** yes
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-adindabudi-azure-cost-optimization-skills-azure-cost-optimization-skills
- Seller: https://agentstack.voostack.com/s/adindabudi
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
