返回 Skills
microsoft/azure-skills· MIT 内容可用

azure-cost-optimization

Identify Azure cost savings from usage and spending data. USE FOR: optimize Azure costs, reduce Azure spending/expenses, analyze Azure costs, find cost savings, generate cost optimization report, identify orphaned resources to delete, rightsize VMs, reduce waste, optimize Redis costs, optimize storage costs, AKS cost analysis add-on, namespace cost, cost spike, anomaly, budget alert, AKS cost visibility. DO NOT USE FOR: deploying resources (use azure-deploy), general Azure diagnostics (use azure-diagnostics), security issues (use azure-security)

安装

与 skills.sh 相同的 Command / Prompt 安装方式


name: azure-cost-optimization description: "Identify Azure cost savings from usage and spending data. USE FOR: optimize Azure costs, reduce Azure spending/expenses, analyze Azure costs, find cost savings, generate cost optimization report, identify orphaned resources to delete, rightsize VMs, reduce waste, optimize Redis costs, optimize storage costs, AKS cost analysis add-on, namespace cost, cost spike, anomaly, budget alert, AKS cost visibility. DO NOT USE FOR: deploying resources (use azure-deploy), general Azure diagnostics (use azure-diagnostics), security issues (use azure-security)" license: MIT metadata: author: Microsoft version: "1.0.2"

Azure Cost Optimization Skill

Analyze Azure subscriptions to identify cost savings through orphaned resource cleanup, rightsizing, and optimization recommendations based on actual usage data.

When to Use This Skill

Use this skill when the user asks to:

  • Optimize Azure costs or reduce spending
  • Analyze Azure subscription for cost savings
  • Generate cost optimization report
  • Find orphaned or unused resources
  • Rightsize Azure VMs, containers, or services
  • Identify where they're overspending in Azure
  • Optimize Redis costs specifically - See Azure Redis Cost Optimization for Redis-specific analysis

Instructions

Follow these steps in conversation with the user:

Step 0: Validate Prerequisites

Before starting, verify these tools and permissions are available:

Required Tools:

  • Azure CLI installed and authenticated (az login)
  • Azure CLI extensions: costmanagement, resource-graph
  • Azure Quick Review (azqr) installed - See Azure Quick Review for details

Required Permissions:

  • Cost Management Reader role
  • Monitoring Reader role
  • Reader role on subscription/resource group

Verification commands:

az --version
az account show
az extension show --name costmanagement
azqr version

Step 1: Load Best Practices

Get Azure cost optimization best practices to inform recommendations:

// Use Azure MCP best practices tool
mcp_azure_mcp_get_azure_bestpractices({
  intent: "Get cost optimization best practices",
  command: "get_bestpractices",
  parameters: { resource: "cost-optimization", action: "all" }
})

Step 1.5: Redis-Specific Analysis (Conditional)

If the user specifically requests Redis cost optimization, use the specialized Redis skill:

📋 Reference: Azure Redis Cost Optimization

When to use Redis-specific analysis:

  • User mentions "Redis", "Azure Cache for Redis", or "Azure Managed Redis"
  • Focus is on Redis resource optimization, not general subscription analysis
  • User wants Redis-specific recommendations (SKU downgrade, failed caches, etc.)

Key capabilities:

  • Interactive subscription filtering (prefix, ID, or "all subscriptions")
  • Redis-specific optimization rules (failed caches, oversized tiers, missing tags)
  • Pre-built report templates for Redis cost analysis
  • Uses redis_list command

Report templates available:

Note: For general subscription-wide cost optimization (including Redis), continue with Step 2. For Redis-only focused analysis, follow the instructions in the Redis-specific reference document.

Step 1.6: Choose Analysis Scope (for Redis-specific analysis)

If performing Redis cost optimization, ask the user to select their analysis scope:

Prompt the user with these options:

  1. Specific Subscription ID - Analyze a single subscription
  2. Subscription Name - Use display name instead of ID
  3. Subscription Prefix - Analyze all subscriptions starting with a prefix (e.g., "CacheTeam")
  4. All My Subscriptions - Scan all accessible subscriptions
  5. Tenant-wide - Analyze entire organization

Wait for user response, then proceed to Step 2.

Step 1.7: AKS-Specific Analysis (Conditional)

If the user specifically requests AKS cost optimization, use the specialized AKS reference files:

When to use AKS-specific analysis:

  • User mentions "AKS", "Kubernetes", "cluster", "node pool", "pod", or "kubectl"
  • User wants to enable the AKS cost analysis add-on or namespace cost visibility
  • User reports a cost spike, unusual cluster utilization, or wants budget alerts

Tool Selection:

  • Prefer MCP first: Use mcp_azure_mcp_aks for AKS operations (list clusters, get node pools, inspect configuration) — it provides richer metadata and is consistent with AKS skill conventions in this repo
  • Fall back to CLI: Use az aks and kubectl only when the specific operation cannot be performed via the MCP surface

Reference files (load only what is needed for the request):

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.

Step 1.8: Choose Analysis Scope (for AKS-specific analysis)

If performing AKS cost optimization, ask the user to select their analysis scope:

Prompt the user with these options:

  1. Specific Cluster Name - Analyze a single AKS cluster
  2. Resource Group - Analyze all clusters in a resource group
  3. Subscription ID - Analyze all clusters in a subscription
  4. All My Clusters - Scan all accessible clusters across subscriptions

Wait for user response before proceeding to Step 2.

Step 2: Run Azure Quick Review

Run azqr to find orphaned resources (immediate cost savings):

📋 Reference: Azure Quick Review - Detailed instructions for running azqr scans

// Use Azure MCP extension_azqr tool
extension_azqr({
  subscription: "<SUBSCRIPTION_ID>",
  "resource-group": "<RESOURCE_GROUP>"  // optional
})

What to look for in azqr results:

  • Orphaned resources: unattached disks, unused NICs, idle NAT gateways
  • Over-provisioned resources: excessive retention periods, oversized SKUs
  • Missing cost tags: resources without proper cost allocation

Note: The Azure Quick Review reference document includes instructions for creating filter configurations, saving output to the output/ folder, and interpreting results for cost optimization.

Step 3: Discover Resources

For efficient cross-subscription resource discovery, use Azure Resource Graph. See Azure Resource Graph Queries for orphaned resource detection and cost optimization patterns.

List all resources in the subscription using Azure MCP tools or CLI:

# Get subscription info
az account show

# List all resources
az resource list --subscription "<SUBSCRIPTION_ID>" --resource-group "<RESOURCE_GROUP>"

# Use MCP tools for specific services (preferred):
# - Storage accounts, Cosmos DB, Key Vaults: use Azure MCP tools
# - Redis caches: use mcp_azure_mcp_redis tool (see ./references/azure-redis.md)
# - Web apps, VMs, SQL: use az CLI commands

Step 4: Query Actual Costs

Get actual cost data from Azure Cost Management API (last 30 days):

Create cost query file:

Create temp/cost-query.json with:

{
  "type": "ActualCost",
  "timeframe": "Custom",
  "timePeriod": {
    "from": "<START_DATE>",  
    "to": "<END_DATE>"
  },
  "dataset": {
    "granularity": "None",
    "aggregation": {
      "totalCost": {
        "name": "Cost",
        "function": "Sum"
      }
    },
    "grouping": [
      {
        "type": "Dimension",
        "name": "ResourceId"
      }
    ]
  }
}

Action Required: Calculate <START_DATE> (30 days ago) and <END_DATE> (today) in ISO 8601 format (e.g., 2025-11-03T00:00:00Z).

Execute cost query:

# Create temp folder
New-Item -ItemType Directory -Path "temp" -Force

# Query using REST API (more reliable than az costmanagement query)
az rest --method post `
  --url "https://management.azure.com/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RESOURCE_GROUP>/providers/Microsoft.CostManagement/query?api-version=2023-11-01" `
  --body '@temp/cost-query.json'

Important: Save the query results to output/cost-query-result<timestamp>.json for audit trail.

Step 5: Validate Pricing

Fetch current pricing from official Azure pricing pages using fetch_webpage:

// Validate pricing for key services
fetch_webpage({
  urls: ["https://azure.microsoft.com/en-us/pricing/details/container-apps/"],
  query: "pricing tiers and costs"
})

Key services to validate:

Important: Check for free tier allowances - many Azure services have generous free limits that may explain $0 costs.

Step 6: Collect Utilization Metrics

Query Azure Monitor for utilization data (last 14 days) to support rightsizing recommendations:

# Calculate dates for last 14 days
$startTime = (Get-Date).AddDays(-14).ToString("yyyy-MM-ddTHH:mm:ssZ")
$endTime = Get-Date -Format "yyyy-MM-ddTHH:mm:ssZ"

# VM CPU utilization
az monitor metrics list `
  --resource "<RESOURCE_ID>" `
  --metric "Percentage CPU" `
  --interval PT1H `
  --aggregation Average `
  --start-time $startTime `
  --end-time $endTime

# App Service Plan utilization
az monitor metrics list `
  --resource "<RESOURCE_ID>" `
  --metric "CpuTime,Requests" `
  --interval PT1H `
  --aggregation Total `
  --start-time $startTime `
  --end-time $endTime

# Storage capacity
az monitor metrics list `
  --resource "<RESOURCE_ID>" `
  --metric "UsedCapacity,BlobCount" `
  --interval PT1H `
  --aggregation Average `
  --start-time $startTime `
  --end-time $endTime

Step 7: Generate Optimization Report

Create a comprehensive cost optimization report in the output/ folder:

Use the create_file tool with path output/costoptimizereport<YYYYMMDD_HHMMSS>.md:

Report Structure:

# Azure Cost Optimization Report
**Generated**: <timestamp>

## Executive Summary
- Total Monthly Cost: $X (💰 ACTUAL DATA)
- Top Cost Drivers: [List top 3 resources with Azure Portal links]

## Cost Breakdown
[Table with top 10 resources by cost, including Azure Portal links]

## Free Tier Analysis
[Resources operating within free tiers showing $0 cost]

## Orphaned Resources (Immediate Savings)
[From azqr - resources that can be deleted immediately]
- Resource name with Portal link - $X/month savings

## Optimization Recommendations

### Priority 1: High Impact, Low Risk
[Example: Delete orphaned resources]
- 💰 ACTUAL cost: $X/month
- 📊 ESTIMATED savings: $Y/month
- Commands to execute (with warnings)

### Priority 2: Medium Impact, Medium Risk
[Example: Rightsize VM from D4s_v5 to D2s_v5]
- 💰 ACTUAL baseline: D4s_v5, $X/month
- 📈 ACTUAL metrics: CPU 8%, Memory 30%
- 💵 VALIDATED pricing: D4s_v5 $Y/hr, D2s_v5 $Z/hr
- 📊 ESTIMATED savings: $S/month
- Commands to execute

### Priority 3: Long-term Optimization
[Example: Reserved Instances, Storage tiering]

## Total Estimated Savings
- Monthly: $X
- Annual: $Y

## Implementation Commands
[Safe commands with approval warnings]

## Validation Appendix

### Data Sources and Files
- **Cost Query Results**: `output/cost-query-result<timestamp>.json`
  - Raw cost data from Azure Cost Management API
  - Audit trail proving actual costs at report generation time
  - Keep for at least 12 months for historical comparison
  - Contains every resource's exact cost over the analysis period
- **Pricing Sources**: [Links to Azure pricing pages]
- **Free Tier Allowances**: [Applicable allowances]

> **Note**: The `temp/cost-query.json` file (if present) is a temporary query template and can be safely deleted. All permanent audit data is in the `output/` folder.

Portal Link Format:

https://portal.azure.com/#@<TENANT_ID>/resource/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RESOURCE_GROUP>/providers/<RESOURCE_PROVIDER>/<RESOURCE_TYPE>/<RESOURCE_NAME>/overview

Step 8: Save Audit Trail

Save all cost query results for validation:

Use the create_file tool with path output/cost-query-result<YYYYMMDD_HHMMSS>.json:

{
  "timestamp": "<ISO_8601>",
  "subscription": "<SUBSCRIPTION_ID>",
  "resourceGroup": "<RESOURCE_GROUP>",
  "queries": [
    {
      "queryType": "ActualCost",
      "timeframe": "MonthToDate",
      "query": { },
      "response": { }
    }
  ]
}

Step 9: Clean Up Temporary Files

Remove temporary query files and folder after the report is generated:

# Delete entire temp folder (no longer needed)
Remove-Item -Path "temp" -Recurse -Force -ErrorAction SilentlyContinue

Note: The temp/cost-query.json file is only needed during API execution. The actual query and results are preserved in output/cost-query-result*.json for audit purposes.

Output

The skill generates:

  1. Cost Optimization Report (output/costoptimizereport<timestamp>.md)

    • Executive summary with total costs and top drivers
    • Detailed cost breakdown with Azure Portal links
    • Prioritized recommendations with actual data and estimated savings
    • Implementation commands with safety warnings
  2. Cost Query Results (output/cost-query-result<timestamp>.json)

    • Audit trail of all cost queries and responses
    • Validation evidence for recommendations

Important Notes

Data Classification

  • 💰 ACTUAL DATA = Retrieved from Azure Cost Management API
  • 📈 ACTUAL METRICS = Retrieved from Azure Monitor
  • 💵 VALIDATED PRICING = Retrieved from official Azure pricing pages
  • 📊 ESTIMATED SAVINGS = Calculated based on actual data and validated pricing

Best Practices

  • Always query actual costs first - never estimate or assume
  • Validate pricing from official sources - account for free tiers
  • Use REST API for cost queries (more reliable than az costmanagement query)
  • Save audit trail - include all queries and responses
  • Include Azure Portal links for all resources
  • Use UTF-8 encoding when creating report files
  • For costs < $10/month, emphasize operational improvements over financial savings
  • Never execute destructive operations without explicit approval

Common Pitfalls

  • Assuming costs: Always query actual data from Cost Management API
  • Ignoring free tiers: Many services have generous allowances (e.g., Container Apps: 180K vCPU-sec free/month)
  • Using wrong date ranges: 30 days for costs, 14 days for utilization
  • Broken Portal links: Verify tenant ID and resource ID format
  • Cost query failures: Use az rest with JSON body, not az costmanagement query

Safety Requirements

  • Get approval before deleting resources
  • Test changes in non-production first
  • Provide dry-run commands for validation
  • Include rollback procedures
  • Monitor impact after implementation

SDK Quick References

  • Redis Management: .NET

附带文件

references/auth-best-practices.md
# Azure Authentication Best Practices

> Source: [Microsoft — Passwordless connections for Azure services](https://learn.microsoft.com/azure/developer/intro/passwordless-overview) and [Azure Identity client libraries](https://learn.microsoft.com/dotnet/azure/sdk/authentication/).

## Golden Rule

Use **managed identities** and **Azure RBAC** in production. Reserve `DefaultAzureCredential` for **local development only**.

## Authentication by Environment

| Environment | Recommended Credential | Why |
|---|---|---|
| **Production (Azure-hosted)** | `ManagedIdentityCredential` (system- or user-assigned) | No secrets to manage; auto-rotated by Azure |
| **Production (on-premises)** | `ClientCertificateCredential` or `WorkloadIdentityCredential` | Deterministic; no fallback chain overhead |
| **CI/CD pipelines** | `AzurePipelinesCredential` / `WorkloadIdentityCredential` | Scoped to pipeline identity |
| **Local development** | `DefaultAzureCredential` | Chains CLI, PowerShell, and VS Code credentials for convenience |

## Why Not `DefaultAzureCredential` in Production?

1. **Unpredictable fallback chain** — walks through multiple credential types, adding latency and making failures harder to diagnose.
2. **Broad surface area** — checks environment variables, CLI tokens, and other sources that should not exist in production.
3. **Non-deterministic** — which credential actually authenticates depends on the environment, making behavior inconsistent across deployments.
4. **Performance** — each failed credential attempt adds network round-trips before falling back to the next.

## Production Patterns

### .NET

```csharp
using Azure.Identity;

var credential = Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT") == "Development"
    ? new DefaultAzureCredential()                          // local dev — uses CLI/VS credentials
    : new ManagedIdentityCredential();                      // production — deterministic, no fallback chain
// For user-assigned identity: new ManagedIdentityCredential("<client-id>")
```

### TypeScript / JavaScript

```typescript
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";

const credential = process.env.NODE_ENV === "development"
  ? new DefaultAzureCredential()                          // local dev — uses CLI/VS credentials
  : new ManagedIdentityCredential();                      // production — deterministic, no fallback chain
// For user-assigned identity: new ManagedIdentityCredential("<client-id>")
```

### Python

```python
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential

credential = (
    DefaultAzureCredential()                              # local dev — uses CLI/VS credentials
    if os.getenv("AZURE_FUNCTIONS_ENVIRONMENT") == "Development"
    else ManagedIdentityCredential()                      # production — deterministic, no fallback chain
)
# For user-assigned identity: ManagedIdentityCredential(client_id="<client-id>")
```

### Java

```java
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

var credential = "Development".equals(System.getenv("AZURE_FUNCTIONS_ENVIRONMENT"))
    ? new DefaultAzureCredentialBuilder().build()          // local dev — uses CLI/VS credentials
    : new ManagedIdentityCredentialBuilder().build();      // production — deterministic, no fallback chain
// For user-assigned identity: new ManagedIdentityCredentialBuilder().clientId("<client-id>").build()
```

## Local Development Setup

`DefaultAzureCredential` is ideal for local dev because it automatically picks up credentials from developer tools:

1. **Azure CLI** — `az login`
2. **Azure Developer CLI** — `azd auth login`
3. **Azure PowerShell** — `Connect-AzAccount`
4. **Visual Studio / VS Code** — sign in via Azure extension

```typescript
import { DefaultAzureCredential } from "@azure/identity";

// Local development only — uses CLI/PowerShell/VS Code credentials
const credential = new DefaultAzureCredential();
```

## Environment-Aware Pattern

Detect the runtime environment and select the appropriate credential. The key principle: use `DefaultAzureCredential` only when running locally, and a specific credential in production.

> **Tip:** Azure Functions sets `AZURE_FUNCTIONS_ENVIRONMENT` to `"Development"` when running locally. For App Service or containers, use any environment variable you control (e.g. `NODE_ENV`, `ASPNETCORE_ENVIRONMENT`).

```typescript
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";

function getCredential() {
  if (process.env.NODE_ENV === "development") {
    return new DefaultAzureCredential();          // picks up az login / VS Code creds
  }
  return process.env.AZURE_CLIENT_ID
    ? new ManagedIdentityCredential(process.env.AZURE_CLIENT_ID)  // user-assigned
    : new ManagedIdentityCredential();                            // system-assigned
}
```

## Security Checklist

- [ ] Use managed identity for all Azure-hosted apps
- [ ] Never hardcode credentials, connection strings, or keys
- [ ] Apply least-privilege RBAC roles at the narrowest scope
- [ ] Use `ManagedIdentityCredential` (not `DefaultAzureCredential`) in production
- [ ] Store any required secrets in Azure Key Vault
- [ ] Rotate secrets and certificates on a schedule
- [ ] Enable Microsoft Defender for Cloud on production resources

## Further Reading

- [Passwordless connections overview](https://learn.microsoft.com/azure/developer/intro/passwordless-overview)
- [Managed identities overview](https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/overview)
- [Azure RBAC overview](https://learn.microsoft.com/azure/role-based-access-control/overview)
- [.NET authentication guide](https://learn.microsoft.com/dotnet/azure/sdk/authentication/)
- [Python identity library](https://learn.microsoft.com/python/api/overview/azure/identity-readme)
- [JavaScript identity library](https://learn.microsoft.com/javascript/api/overview/azure/identity-readme)
- [Java identity library](https://learn.microsoft.com/java/api/overview/azure/identity-readme)
references/azure-aks-anomalies.md
# AKS Cost Anomaly Investigation

Investigate user-reported cost or utilization spikes by correlating Azure Monitor metrics, scaling events, and Cost Management data.

## Step 1 - Confirm Timeframe

Ask the user: "When did you notice the spike? (e.g., 'last Tuesday', 'between 2 AM and 4 AM yesterday')"

## Step 2 - Pull Cost Data

```bash
az rest --method post \
  --url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.CostManagement/query?api-version=2023-11-01" \
  --body '{
    "type": "ActualCost",
    "timeframe": "Custom",
    "timePeriod": { "from": "<start-date>", "to": "<end-date>" },
    "dataset": {
      "granularity": "Daily",
      "aggregation": { "totalCost": { "name": "Cost", "function": "Sum" } },
      "grouping": [{ "type": "Dimension", "name": "ResourceId" }]
    }
  }'
```

## Step 3 - Pull Node Count and Scaling Events

```bash
# First, verify available metrics on your AKS resource
az monitor metrics list-definitions \
  --resource "<aks-resource-id>" \
  --output table

# Node count over the anomaly window (use metric name from list-definitions output)
az monitor metrics list \
  --resource "<aks-resource-id>" \
  --metrics "<verified-node-count-metric>" \
  --interval PT5M --aggregation Count \
  --start-time "<start-date>" --end-time "<end-date>"

# HPA scaling events
kubectl get events --all-namespaces \
  --field-selector reason=SuccessfulRescale \
  --sort-by='.lastTimestamp'
```

## Step 4 - Top Consumers

```bash
kubectl top nodes
kubectl top pods --all-namespaces --sort-by=cpu
```

## Common Causes

| Symptom | Likely Cause | Action |
|---------|-------------|--------|
| Node count surged off-peak | HPA/VPA misconfiguration | Review HPA min replicas |
| Single pod consuming all CPU | Memory leak or runaway process | Check logs, add resource limits |
| Cost spike on specific day | Batch job ran unexpectedly | Review CronJob schedule |
| Persistent high node count | CAS scale-down blocked | Check PodDisruptionBudgets, system pods |
| Sudden namespace cost jump | New deployment with no resource limits | Add requests/limits |

## Set Up Budget Alert

```bash
az consumption budget create \
  --budget-name "aks-monthly-budget" \
  --amount <budget-amount> \
  --time-grain Monthly \
  --start-date "<YYYY-MM-01>" \
  --end-date "<YYYY-MM-01>" \
  --resource-group "<resource-group>" \
  --threshold 80 \
  --contact-emails "<contact-email>"
```

references/azure-aks-cost-addon.md
# AKS Cost Analysis Add-on

Enable namespace-level cost visibility using the built-in AKS cost monitoring add-on.

## Check Status

```bash
# Check if add-on is enabled
az aks show \
  --name "<cluster-name>" --resource-group "<resource-group>" \
  --query "addonProfiles.costAnalysis" -o json

# Check cluster tier (add-on requires Standard or Premium)
az aks show \
  --name "<cluster-name>" --resource-group "<resource-group>" \
  --query "{tier:sku.tier, name:name}" -o table
```

## Enable Add-on

```bash
# Requires Standard or Premium tier
az aks update \
  --name "<cluster-name>" --resource-group "<resource-group>" \
  --enable-cost-analysis
```

## If Cluster is Free Tier

Warn user that upgrading from Free to Standard introduces an ongoing cluster management fee. Use the official AKS pricing page or this skill’s pricing validation step to confirm the current cost with the user and obtain explicit approval before proceeding. After user approval:

```bash
az aks update \
  --name "<cluster-name>" --resource-group "<resource-group>" \
  --tier standard

az aks update \
  --name "<cluster-name>" --resource-group "<resource-group>" \
  --enable-cost-analysis
```

## After Enabling

Namespace-level cost data is available in:
- Azure Portal: AKS cluster -> Cost Analysis blade
- Azure Cost Management: filter by cluster resource ID + `kubernetes namespace` dimension

> Risk: Low for enabling the add-on. Upgrading tier (Free -> Standard) has a cost — always confirm with user first.
references/azure-quick-review.md
## Azure Quick Review (azqr) for Cost Optimization

Azure Quick Review (azqr) generates compliance and governance reports that identify cost-impacting issues and orphaned resources.

## Create Filters Configuration

Create a `filters.yaml` file to focus the scan on cost optimization:

```yaml
includeSections:
  - Costs
  - Advisor
  - Inventory
  - Orphaned
excludeSections:
  - Recommendations
  - AzurePolicy
  - DefenderRecommendations
```

## Run the azqr Scan

Execute the scan using Azure MCP or CLI:

```powershell
# Via Azure MCP (preferred if available)
# Use the extension_azqr tool with subscription and optional resource-group parameters

# Or via direct CLI:
azqr scan --subscription "<SUBSCRIPTION_ID>" --resource-group "<RESOURCE_GROUP>" --filters ./filters.yaml --output json
```

## Save Output

Save all generated files to the `output/` folder:
1. Create the folder: `mkdir output` (if it doesn't exist)
2. Save the azqr report as: `output/azqr_report_<YYYYMMDD_HHMMSS>.json`
3. After the scan completes, delete the temporary `filters.yaml` file

## Report Output

The scan generates a JSON report with recommendations categorized by impact level (High/Medium/Low), including:
- Orphaned resources (NICs, disks, IPs)
- Azure Advisor cost recommendations  
- Resource inventory
- Cost breakdown by resource

## Notes

- azqr provides qualitative governance recommendations
- Always validate findings with actual cost data before making changes
- The tool requires Reader role on the subscription or resource group
- Save reports to `output/` folder with timestamps for audit trail
references/azure-redis.md
## Azure Redis Cost Optimization

Reference guide for identifying cost savings opportunities in Azure Redis deployments through analysis and targeted scans.

## Subscription Input Options

Accept any of these identifiers to identify subscriptions for analysis:

| Input Type | Example | Use Case |
|------------|---------|----------|
| **Subscription ID** | `a1b2c3d4-...` | Analyze specific subscription |
| **Subscription Name** | `Production-Environment` | User-friendly identifier |
| **Subscription Prefix** | `CacheTeam -` | Analyze all team subscriptions |
| **Tenant ID** | `tenant-guid` | Analyze entire organization |
| **"All my subscriptions"** | (keyword) | Scan all accessible subscriptions |

## Cost Optimization Rules

When analyzing each cache, apply these prioritized rules:

| Priority | Rule | Detection Logic | Recommendation | Avg Savings |
|----------|------|----------------|----------------|-------------|
| 🔴 Critical | Failed Cache | `provisioningState == 'Failed'` | Delete immediately | $50-300/mo |
| 🔴 Critical | Stuck Creating | `provisioningState == 'Creating'` AND age >4 hours | Delete/support ticket | $50-300/mo |
| 🟠 High | Premium in Dev | `sku.name == 'Premium'` AND `tags.environment in ['dev','test','staging']` | Downgrade to Standard | $175/mo |
| 🟠 High | Enterprise Unused | `sku.name startsWith 'Enterprise'` AND no modules/clustering | Downgrade to Premium/Standard | $300-1000/mo |
| 🟠 High | Old Test Cache | `tags.purpose == 'test'` AND age >60 days | Delete or downgrade | $50-150/mo |
| 🟡 Medium | Large Dev Cache | `sku.capacity >3` AND `tags.environment == 'dev'` | Reduce size | $100-300/mo |
| 🟡 Medium | No Expiration Tag | Missing `expirationDate` or `ttl` tag | Add cleanup policy | N/A |
| 🟢 Low | Untagged Resource | Missing required tags (`environment`, `owner`) | Apply tags | N/A |
| 🟢 Low | Old Cache | Age >365 days | Review if still needed | Variable |

## Report Templates

### Subscription-Level Summary
Quick overview of costs and issues per subscription (use for multi-subscription scans).
See [redis-subscription-level-report.md](../templates/redis-subscription-level-report.md) for template format.

### Detailed Cache Analysis
Individual cache breakdown with specific recommendations.
See [redis-detailed-cache-analysis.md](../templates/redis-detailed-cache-analysis.md) for template format.

## Tools & Commands

**MCP Tool:** `mcp_azure_mcp_redis` with command `redis_list` (parameter: `subscription`)

**Azure CLI Equivalents:**
- `az account list` - List subscriptions
- `az redis list --subscription <id>` - List Redis caches
- `az redis show` - Get cache details
- `az redis delete` - Remove cache
references/azure-resource-graph.md
# Azure Resource Graph Queries for Cost Optimization

Azure Resource Graph (ARG) enables fast, cross-subscription resource querying using KQL via `az graph query`. Use it to find orphaned resources, unused infrastructure, and optimization targets.

## How to Query

Use the `extension_cli_generate` MCP tool to generate `az graph query` commands:

```yaml
mcp_azure_mcp_extension_cli_generate
  intent: "query Azure Resource Graph to <describe what you want to find>"
  cli-type: "az"
```

Or construct directly:

```bash
az graph query -q "<KQL>" --query "data[].{name:name, type:type}" -o table
```

> ⚠️ **Prerequisite:** `az extension add --name resource-graph`

## Key Tables

| Table | Contains |
|-------|----------|
| `Resources` | All ARM resources (name, type, location, properties, tags) |
| `ResourceContainers` | Subscriptions, resource groups, management groups |
| `AdvisorResources` | Cost and performance recommendations |

## Cost Optimization Query Patterns

**Find orphaned (unattached) managed disks:**

```kql
Resources
| where type =~ 'microsoft.compute/disks'
| where isempty(managedBy)
| project name, resourceGroup, location, diskSizeGb=properties.diskSizeGB, sku=sku.name
```

**Find unattached public IP addresses:**

```kql
Resources
| where type =~ 'microsoft.network/publicipaddresses'
| where isempty(properties.ipConfiguration)
| project name, resourceGroup, location, sku=sku.name
```

**Find orphaned network interfaces:**

```kql
Resources
| where type =~ 'microsoft.network/networkinterfaces'
| where isempty(properties.virtualMachine)
| project name, resourceGroup, location
```

**Resource count by SKU/tier (spot oversized resources):**

```kql
Resources
| where isnotempty(sku.name)
| summarize count() by type, tostring(sku.name)
| order by count_ desc
```

**Tag coverage for cost allocation:**

```kql
Resources
| extend hasCostCenter = isnotnull(tags['CostCenter'])
| summarize total=count(), tagged=countif(hasCostCenter) by type
| extend coverage=round(100.0 * tagged / total, 1)
| order by total desc
```

**Find idle load balancers (no backend pools):**

```kql
Resources
| where type =~ 'microsoft.network/loadbalancers'
| where array_length(properties.backendAddressPools) == 0
| project name, resourceGroup, location, sku=sku.name
```

**Get Advisor cost recommendations:**

```kql
AdvisorResources
| where properties.category == 'Cost'
| project name, impact=properties.impact, description=properties.shortDescription.solution
```

## Tips

- Use `=~` for case-insensitive type matching (resource types are lowercase)
- Navigate properties with `properties.fieldName`
- Use `--first N` to limit result count
- Use `--subscriptions` to scope to specific subscriptions
- Cross-reference orphaned resources with cost data from Cost Management API
references/sdk/azure-resource-manager-redis-dotnet.md
# Redis Management — .NET SDK Quick Reference

> Condensed from **azure-resource-manager-redis-dotnet**. Full patterns
> (cache creation, firewall rules, access keys, geo-replication, patching)
> in the **azure-resource-manager-redis-dotnet** plugin skill if installed.

## Install
dotnet add package Azure.ResourceManager.Redis
dotnet add package Azure.Identity

## Quick Start

> **Auth:** `DefaultAzureCredential` is for local development. See [auth-best-practices.md](../auth-best-practices.md) for production patterns.

```csharp
using Azure.ResourceManager;
using Azure.Identity;
var armClient = new ArmClient(new DefaultAzureCredential());
```

## Best Practices
- Use `WaitUntil.Completed` for operations that must finish before proceeding
- Use `WaitUntil.Started` when you want to poll manually or run operations in parallel
- Use DefaultAzureCredential for **local development only**. In production, use ManagedIdentityCredential — see [auth-best-practices.md](../auth-best-practices.md)
- Handle `RequestFailedException` for ARM API errors
- Use `CreateOrUpdateAsync` for idempotent operations
- Navigate hierarchy via `Get*` methods (e.g., `cache.GetRedisFirewallRules()`)
- Use Premium SKU for production workloads requiring geo-replication, clustering, or persistence
- Enable TLS 1.2 minimum — set `MinimumTlsVersion = RedisTlsVersion.Tls1_2`
- Disable non-SSL port — set `EnableNonSslPort = false` for security
- Rotate keys regularly — use `RegenerateKeyAsync` and update connection strings
templates/redis-detailed-cache-analysis.md
Redis Cost Optimization Report - Detailed Analysis
Subscription: Example-Subscription (12345678-1234-1234-1234-123456789abc)
Generated: January 26, 2026

═══════════════════════════════════════════════════════════════════

SUBSCRIPTION OVERVIEW
- Total Caches: 5
- Current Monthly Cost: $850
- Potential Savings: $425/month (50%)
- Critical Issues: 3

CRITICAL ISSUES (🔴 Immediate Action)

[1] example-cache-001
    SKU: Premium P1 (6GB)
    State: Failed
    Location: eastus2
    Age: 12 days
    Cost: $300/month
    Tags: environment=dev, owner=user1@example.com
    
    ❌ Problem: Cache in Failed state for 12 days
    💡 Recommendation: Delete immediately
    💰 Savings: $300/month
    
    Action: az redis delete --name example-cache-001 --resource-group dev-rg

[2] example-cache-002
    SKU: Premium P1 (6GB)
    State: Running
    Location: eastus2
    Age: 120 days
    Cost: $300/month
    Tags: environment=dev, owner=user2@example.com
    
    ⚠️ Problem: Premium tier in dev environment
    💡 Recommendation: Downgrade to Standard C3 (6GB)
    💰 Savings: $175/month
    
    Next Steps:
    1. Verify with owner: user2@example.com
    2. Schedule maintenance window
    3. az redis update --name example-cache-002 --resource-group dev-rg --sku Standard --vm-size C3

HIGH PRIORITY (🟠 Review This Week)

[3] example-cache-003
    SKU: Standard C2 (2.5GB)
    State: Running
    Location: westus
    Age: 180 days
    Cost: $100/month
    Tags: purpose=test, temporary=true, created=2025-07-15
    
    ⚠️ Problem: Temporary test cache running for 6 months
    💡 Recommendation: Delete if no longer needed
    💰 Savings: $100/month
    
    Action: Confirm with team, then delete

HEALTHY CACHES (🟢 No Action Needed)

[4] example-cache-004
    SKU: Standard C3 (6GB)
    State: Running
    Cost: $125/month
    Tags: environment=prod, owner=team@example.com
    ✓ Appropriate tier for production workload

[5] example-cache-005
    SKU: Standard C1 (1GB)
    State: Running
    Cost: $75/month
    Tags: environment=staging
    ✓ Cost-optimized for staging environment

═══════════════════════════════════════════════════════════════════

SAVINGS SUMMARY
- Critical issues resolved: $425/month
- Total potential savings: $425/month (50% reduction)
- New monthly cost: $425/month

RECOMMENDED ACTIONS
1. [Immediate] Confirm with the team, then delete example-cache-001 (Failed state)
2. [This Week] Downgrade example-cache-002 to Standard
3. [This Week] Confirm example-cache-003 still needed, delete if not

Would you like me to:
  A. Generate Azure CLI commands for these actions
  B. Analyze another subscription
  C. Export full report to CSV
  D. Set up automated monitoring

Please select (A/B/C/D):
templates/redis-subscription-level-report.md
Redis Cost Optimization Report
Tenant: Contoso Corp
Generated: January 26, 2026
Subscriptions Analyzed: 3 (filtered by prefix "CacheTeam -")

═══════════════════════════════════════════════════════════════════

EXECUTIVE SUMMARY
- Total Redis Caches: 20
- Current Monthly Cost: $3,625
- Potential Savings: $875/month (24.1%)
- Critical Issues: 4 caches requiring immediate action

BY SUBSCRIPTION
┌─────────────────────┬──────┬──────────┬─────────────┬──────────┐
│ Subscription        │Caches│  Cost/Mo │  Savings/Mo │ Priority │
├─────────────────────┼──────┼──────────┼─────────────┼──────────┤
│ CacheTeam - Alpha   │   5  │   $850   │   $425      │    🔴    │
│ CacheTeam - Beta    │   3  │   $375   │     $0      │    🟢    │
│ CacheTeam - Prod    │  12  │ $2,400   │   $450      │    🟠    │
└─────────────────────┴──────┴──────────┴─────────────┴──────────┘

CRITICAL ISSUES (🔴 Immediate Action Required)
- CacheTeam - Alpha: 1 failed cache, 2 Premium in dev
- CacheTeam - Prod: 1 old test cache (180 days)

Next Steps:
1. Review detailed analysis for CacheTeam - Alpha (type 'analyze alpha')
2. Review detailed analysis for CacheTeam - Prod (type 'analyze prod')
3. Generate full report with all recommendations (type 'full report')