Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Analyze and reduce Azure cloud costs by right-sizing resources, reservations, and spending policies
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
cost-optimization/workflow.md
1# Cost Optimization Workflow23Use this workflow when the user wants to **reduce their costs** โ find waste, orphaned resources, rightsizing opportunities.45> **Important:** Always present the total bill and cost breakdown (from the [Cost Query Workflow](../cost-query/workflow.md)) alongside optimization recommendations.67## Step 0: Validate Prerequisites89**Required Tools:**10- Azure CLI installed and authenticated (`az login`)11- Azure CLI extensions: `costmanagement`, `resource-graph`12- Azure Quick Review (azqr) installed โ See [Azure Quick Review](./azure-quick-review.md)1314**Required Permissions:**15- Cost Management Reader role16- Monitoring Reader role17- Reader role on subscription/resource group1819**Verification commands:**20```powershell21az --version22az account show23az extension show --name costmanagement24azqr version25```2627## Step 1: Load Best Practices2829```javascript30azure__get_azure_bestpractices({31intent: "Get cost optimization best practices",32command: "get_bestpractices",33parameters: { resource: "cost-optimization", action: "all" }34})35```3637## Step 1.5: Redis-Specific Analysis (Conditional)3839**If the user specifically requests Redis cost optimization**, use the specialized Redis reference:4041**Reference**: [Azure Redis Cost Optimization](./services/redis/azure-cache-for-redis.md)4243**When to use:**44- User mentions "Redis", "Azure Cache for Redis", or "Azure Managed Redis"45- Focus is on Redis resource optimization, not general subscription analysis4647> ๐ก **Note:** For general subscription-wide optimization, continue with Step 2. For Redis-only analysis, follow the Redis reference document.4849## Step 1.6: Choose Analysis Scope (for Redis-specific analysis)5051**If performing Redis cost optimization**, ask the user to select:521. **Specific Subscription ID**532. **Subscription Name**543. **Subscription Prefix** (e.g., "CacheTeam")554. **All My Subscriptions**565. **Tenant-wide**5758Wait for user response before proceeding.5960## Step 1.7: AKS-Specific Analysis (Conditional)6162**If the user specifically requests AKS cost optimization**, use the specialized AKS reference files:6364**When to use AKS-specific analysis:**65- User mentions "AKS", "Kubernetes", "cluster", "node pool", "pod", or "kubectl"66- User wants to enable the AKS cost analysis add-on or namespace cost visibility67- User reports a cost spike, unusual cluster utilization, or wants budget alerts6869**Tool Selection:**70- **Prefer MCP first**: Use `azure__aks` for AKS operations (list clusters, get node pools, inspect configuration) โ it provides richer metadata and is consistent with AKS skill conventions in this repo71- **Fall back to CLI**: Use `az aks` and `kubectl` only when the specific operation cannot be performed via the MCP surface7273**Reference files (load only what is needed for the request):**74- [Cost Analysis Add-on](./azure-aks-cost-addon.md) โ enable namespace-level cost visibility75- [Anomaly Investigation](./azure-aks-anomalies.md) โ cost spikes, scaling events, budget alerts7677> **Note**: For general subscription-wide cost optimization (including AKS resource groups), continue with Step 2. For AKS-focused analysis, follow the instructions in the relevant reference file above.7879## Step 1.8: Choose Analysis Scope (for AKS-specific analysis)8081**If performing AKS cost optimization**, ask the user to select their analysis scope:8283**Prompt the user with these options:**841. **Specific Cluster Name** - Analyze a single AKS cluster852. **Resource Group** - Analyze all clusters in a resource group863. **Subscription ID** - Analyze all clusters in a subscription874. **All My Clusters** - Scan all accessible clusters across subscriptions8889Wait for user response before proceeding to Step 2.9091## Step 2: Run Azure Quick Review9293Run azqr to find orphaned resources (immediate cost savings):9495**Reference**: [Azure Quick Review](./azure-quick-review.md)9697```yaml98azure__extension_azqr99subscription: "<SUBSCRIPTION_ID>"100resource-group: "<RESOURCE_GROUP>" # optional101```102103**What to look for:**104- Orphaned resources: unattached disks, unused NICs, idle NAT gateways105- Over-provisioned resources: excessive retention periods, oversized SKUs106- Missing cost tags107108## Step 3: Discover Resources109110Use Azure Resource Graph for efficient cross-subscription resource discovery. See [Azure Resource Graph Queries](./azure-resource-graph.md) for orphaned resource detection patterns.111112```powershell113az account show114az resource list --subscription "<SUBSCRIPTION_ID>" --resource-group "<RESOURCE_GROUP>"115```116117## Step 4: Query Actual Costs118119Get actual cost data from Azure Cost Management API (last 30 days). Use the [Cost Query Workflow](../cost-query/workflow.md) with this configuration:120121**Create `temp/cost-query.json`:**122```json123{124"type": "ActualCost",125"timeframe": "Custom",126"timePeriod": {127"from": "<START_DATE>",128"to": "<END_DATE>"129},130"dataset": {131"granularity": "None",132"aggregation": {133"totalCost": {134"name": "Cost",135"function": "Sum"136}137},138"grouping": [139{140"type": "Dimension",141"name": "ResourceId"142}143]144}145}146```147148> **Action Required**: Calculate `<START_DATE>` (30 days ago) and `<END_DATE>` (today) in ISO 8601 format.149150**Execute and save results to `output/cost-query-result<timestamp>.json`.** Always include the `--headers "ClientType=GitHubCopilotForAzure"` header in all Cost Management API requests.151152> ๐ก **Tip:** Also run a cost-by-service query (grouping by `ServiceName`) to present the total bill breakdown alongside optimization recommendations. See [examples.md](../cost-query/examples.md).153154> โ ๏ธ **Warning:** Sequential queries to the same scope share the per-scope rate limit (4 requests/minute). If a 429 response is received, check all `x-ms-ratelimit-microsoft.costmanagement-*-retry-after` headers and do not send further requests until the longest retry-after duration has elapsed.155156## Step 5: Validate Pricing157158Fetch current pricing from official Azure pricing pages using `fetch_webpage`:159160**Key services to validate:**161- Container Apps: https://azure.microsoft.com/pricing/details/container-apps/162- Virtual Machines: https://azure.microsoft.com/pricing/details/virtual-machines/163- App Service: https://azure.microsoft.com/pricing/details/app-service/164- Log Analytics: https://azure.microsoft.com/pricing/details/monitor/165166> **Important**: Check for free tier allowances โ many Azure services have generous free limits.167168## Step 6: Collect Utilization Metrics169170Query Azure Monitor for utilization data (last 14 days) to support rightsizing recommendations:171172```powershell173$startTime = (Get-Date).AddDays(-14).ToString("yyyy-MM-ddTHH:mm:ssZ")174$endTime = Get-Date -Format "yyyy-MM-ddTHH:mm:ssZ"175176# VM CPU utilization177az monitor metrics list `178--resource "<RESOURCE_ID>" `179--metric "Percentage CPU" `180--interval PT1H `181--aggregation Average `182--start-time $startTime `183--end-time $endTime184```185186## Step 7: Generate Optimization Report187188Generate a report to `output/costoptimizereport<YYYYMMDD_HHMMSS>.md` that includes an executive summary, cost breakdown by service, free tier analysis, orphaned resources, prioritized optimization recommendations, and implementation commands. Save cost query results to `output/cost-query-result<YYYYMMDD_HHMMSS>.json` for audit trail, then clean up temporary files.189190For the complete report template, see [report-template.md](./report-template.md).191