azure-cost-optimization
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAzure Cost Optimization Skill
Azure成本优化Skill
Analyze Azure subscriptions to identify cost savings through orphaned resource cleanup, rightsizing, and optimization recommendations based on actual usage data.
通过清理孤立资源、调整规格以及基于实际使用数据生成优化建议,分析Azure订阅以识别成本节约空间。
When to Use This Skill
何时使用此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
当用户提出以下需求时使用此Skill:
- 优化Azure成本或降低支出
- 分析Azure订阅以寻找成本节约点
- 生成成本优化报告
- 查找孤立或未使用的资源
- 调整Azure VM、容器或服务的规格
- 识别Azure中的超支环节
- 专门优化Redis成本 - 有关Redis专属分析,请参阅Azure Redis成本优化
Instructions
操作步骤
Follow these steps in conversation with the user:
在与用户的对话中遵循以下步骤:
Step 0: Validate Prerequisites
步骤0:验证前提条件
Before starting, verify these tools and permissions are available:
Required Tools:
- Azure CLI installed and authenticated ()
az login - Azure CLI extensions: ,
costmanagementresource-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:
powershell
az --version
az account show
az extension show --name costmanagement
azqr version开始之前,确认以下工具和权限已就绪:
必备工具:
- 已安装并完成身份验证的Azure CLI(执行)
az login - Azure CLI扩展:、
costmanagementresource-graph - 已安装Azure Quick Review (azqr) - 详情请参阅Azure Quick Review
必备权限:
- 成本管理读取者角色
- 监控读取者角色
- 订阅/资源组的读取者角色
验证命令:
powershell
az --version
az account show
az extension show --name costmanagement
azqr versionStep 1: Load Best Practices
步骤1:加载最佳实践
Get Azure cost optimization best practices to inform recommendations:
javascript
// 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" }
})获取Azure成本优化最佳实践以指导建议生成:
javascript
// 使用Azure MCP最佳实践工具
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)
步骤1.5:Redis专属分析(可选)
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 command
redis_list
Report templates available:
- Subscription-level Redis summary
- Detailed Redis cache analysis
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.
如果用户专门要求优化Redis成本,请使用专属的Redis技能:
📋 参考文档:Azure Redis成本优化
何时使用Redis专属分析:
- 用户提及“Redis”、“Azure Cache for Redis”或“Azure Managed Redis”
- 重点是Redis资源优化,而非常规订阅分析
- 用户需要Redis专属建议(如SKU降级、故障缓存处理等)
核心功能:
- 交互式订阅筛选(前缀、ID或“所有订阅”)
- Redis专属优化规则(故障缓存、规格过大的层级、缺失标签等)
- 预构建的Redis成本分析报告模板
- 使用命令
redis_list
可用报告模板:
- 订阅级Redis摘要
- 详细Redis缓存分析
注意:如需针对包含Redis在内的全订阅范围成本优化,请继续执行步骤2。如需仅聚焦Redis的分析,请遵循Redis专属参考文档中的说明。
Step 1.6: Choose Analysis Scope (for Redis-specific analysis)
步骤1.6:选择分析范围(针对Redis专属分析)
If performing Redis cost optimization, ask the user to select their analysis scope:
Prompt the user with these options:
- Specific Subscription ID - Analyze a single subscription
- Subscription Name - Use display name instead of ID
- Subscription Prefix - Analyze all subscriptions starting with a prefix (e.g., "CacheTeam")
- All My Subscriptions - Scan all accessible subscriptions
- Tenant-wide - Analyze entire organization
Wait for user response before proceeding to Step 2.
如果执行Redis成本优化,请让用户选择分析范围:
向用户提供以下选项:
- 特定订阅ID - 分析单个订阅
- 订阅名称 - 使用显示名称而非ID
- 订阅前缀 - 分析所有以指定前缀开头的订阅(例如“CacheTeam”)
- 我的所有订阅 - 扫描所有可访问的订阅
- 租户范围 - 分析整个组织
等待用户回复后再继续执行步骤2。
Step 2: Run Azure Quick Review
步骤2:运行Azure Quick Review
Run azqr to find orphaned resources (immediate cost savings):
📋 Reference: Azure Quick Review - Detailed instructions for running azqr scans
javascript
// 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 thefolder, and interpreting results for cost optimization.output/
执行azqr以查找孤立资源(可立即实现成本节约):
📋 参考文档:Azure Quick Review - 运行azqr扫描的详细说明
javascript
// 使用Azure MCP extension_azqr工具
extension_azqr({
subscription: "<SUBSCRIPTION_ID>",
"resource-group": "<RESOURCE_GROUP>" // 可选
})azqr结果重点关注:
- 孤立资源:未挂载的磁盘、未使用的NIC、闲置的NAT网关
- 过度配置的资源:过长的保留期、规格过大的SKU
- 缺失成本标签:未配置合理成本分配标签的资源
注意:Azure Quick Review参考文档包含创建筛选配置、将输出保存到文件夹以及解读成本优化结果的说明。output/
Step 3: Discover Resources
步骤3:发现资源
List all resources in the subscription using Azure MCP tools or CLI:
powershell
undefined使用Azure MCP工具或CLI列出订阅中的所有资源:
powershell
undefinedGet subscription info
获取订阅信息
az account show
az account show
List all resources
列出所有资源
az resource list --subscription "<SUBSCRIPTION_ID>" --resource-group "<RESOURCE_GROUP>"
az resource list --subscription "<SUBSCRIPTION_ID>" --resource-group "<RESOURCE_GROUP>"
Use MCP tools for specific services (preferred):
针对特定服务使用MCP工具(推荐):
- Storage accounts, Cosmos DB, Key Vaults: use Azure MCP tools
- 存储账户、Cosmos DB、Key Vault:使用Azure MCP工具
- Redis caches: use mcp_azure_mcp_redis tool (see ./references/azure-redis.md)
- Redis缓存:使用mcp_azure_mcp_redis工具(请参阅./references/azure-redis.md)
- Web apps, VMs, SQL: use az CLI commands
- Web应用、VM、SQL:使用az CLI命令
undefinedundefinedStep 4: Query Actual Costs
步骤4:查询实际成本
Get actual cost data from Azure Cost Management API (last 30 days):
Create cost query file:
Create with:
temp/cost-query.jsonjson
{
"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(30 days ago) and<START_DATE>(today) in ISO 8601 format (e.g.,<END_DATE>).2025-11-03T00:00:00Z
Execute cost query:
powershell
undefined从Azure成本管理API获取实际成本数据(过去30天):
创建成本查询文件:
创建,内容如下:
temp/cost-query.jsonjson
{
"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"
}
]
}
}需执行操作:计算(30天前)和<START_DATE>(今天)的ISO 8601格式时间(例如<END_DATE>)。2025-11-03T00:00:00Z
执行成本查询:
powershell
undefinedCreate temp folder
创建temp文件夹
New-Item -ItemType Directory -Path "temp" -Force
New-Item -ItemType Directory -Path "temp" -Force
Query using REST API (more reliable than az costmanagement query)
使用REST API查询(比az costmanagement query更可靠)
az rest --method post
--body '@temp/cost-query.json'
--url "https://management.azure.com/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RESOURCE_GROUP>/providers/Microsoft.CostManagement/query?api-version=2023-11-01"
**Important:** Save the query results to `output/cost-query-result<timestamp>.json` for audit trail.az rest --method post
--body '@temp/cost-query.json'
--url "https://management.azure.com/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RESOURCE_GROUP>/providers/Microsoft.CostManagement/query?api-version=2023-11-01"
**重要提示:** 将查询结果保存到`output/cost-query-result<timestamp>.json`以留存审计轨迹。Step 5: Validate Pricing
步骤5:验证定价
Fetch current pricing from official Azure pricing pages using :
fetch_webpagejavascript
// 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:
- Container Apps: https://azure.microsoft.com/pricing/details/container-apps/
- Virtual Machines: https://azure.microsoft.com/pricing/details/virtual-machines/
- App Service: https://azure.microsoft.com/pricing/details/app-service/
- Log Analytics: https://azure.microsoft.com/pricing/details/monitor/
Important: Check for free tier allowances - many Azure services have generous free limits that may explain $0 costs.
使用从官方Azure定价页面获取当前定价:
fetch_webpagejavascript
// 验证核心服务的定价
fetch_webpage({
urls: ["https://azure.microsoft.com/en-us/pricing/details/container-apps/"],
query: "pricing tiers and costs"
})需验证的核心服务:
- 容器应用:https://azure.microsoft.com/pricing/details/container-apps/
- 虚拟机:https://azure.microsoft.com/pricing/details/virtual-machines/
- 应用服务:https://azure.microsoft.com/pricing/details/app-service/
- 日志分析:https://azure.microsoft.com/pricing/details/monitor/
重要提示:检查免费层级额度 - 许多Azure服务提供丰厚的免费限额,这可能是产生0成本的原因。
Step 6: Collect Utilization Metrics
步骤6:收集使用指标
Query Azure Monitor for utilization data (last 14 days) to support rightsizing recommendations:
powershell
undefined查询Azure Monitor获取使用数据(过去14天),以支持规格调整建议:
powershell
undefinedCalculate dates for last 14 days
计算过去14天的时间范围
$startTime = (Get-Date).AddDays(-14).ToString("yyyy-MM-ddTHH:mm:ssZ")
$endTime = Get-Date -Format "yyyy-MM-ddTHH:mm:ssZ"
$startTime = (Get-Date).AddDays(-14).ToString("yyyy-MM-ddTHH:mm:ssZ")
$endTime = Get-Date -Format "yyyy-MM-ddTHH:mm:ssZ"
VM CPU utilization
VM CPU使用率
az monitor metrics list
--metric "Percentage CPU"
--aggregation Average
--end-time $endTime
--resource "<RESOURCE_ID>" --interval PT1H --start-time $startTimeaz monitor metrics list
--metric "Percentage CPU"
--aggregation Average
--end-time $endTime
--resource "<RESOURCE_ID>" --interval PT1H --start-time $startTimeApp Service Plan utilization
应用服务计划使用率
az monitor metrics list
--metric "CpuTime,Requests"
--aggregation Total
--end-time $endTime
--resource "<RESOURCE_ID>" --interval PT1H --start-time $startTimeaz monitor metrics list
--metric "CpuTime,Requests"
--aggregation Total
--end-time $endTime
--resource "<RESOURCE_ID>" --interval PT1H --start-time $startTimeStorage capacity
存储容量
az monitor metrics list
--metric "UsedCapacity,BlobCount"
--aggregation Average
--end-time $endTime
--resource "<RESOURCE_ID>" --interval PT1H --start-time $startTimeundefinedaz monitor metrics list
--metric "UsedCapacity,BlobCount"
--aggregation Average
--end-time $endTime
--resource "<RESOURCE_ID>" --interval PT1H --start-time $startTimeundefinedStep 7: Generate Optimization Report
步骤7:生成优化报告
Create a comprehensive cost optimization report in the folder:
output/Use the tool with path :
create_fileoutput/costoptimizereport<YYYYMMDD_HHMMSS>.mdReport Structure:
markdown
undefined在文件夹中创建全面的成本优化报告:
output/使用工具,路径为:
create_fileoutput/costoptimizereport<YYYYMMDD_HHMMSS>.md报告结构:
markdown
undefinedAzure Cost Optimization Report
Azure成本优化报告
Generated: <timestamp>
生成时间:<timestamp>
Executive Summary
执行摘要
- Total Monthly Cost: $X (💰 ACTUAL DATA)
- Top Cost Drivers: [List top 3 resources with Azure Portal links]
- 月度总成本:$X(💰 实际数据)
- 主要成本驱动因素:[列出前3个资源并附Azure门户链接]
Cost Breakdown
成本明细
[Table with top 10 resources by cost, including Azure Portal links]
[按成本排序的前10个资源表格,包含Azure门户链接]
Free Tier Analysis
免费层级分析
[Resources operating within free tiers showing $0 cost]
[在免费层级内运行、成本为$0的资源]
Orphaned Resources (Immediate Savings)
孤立资源(可立即节约成本)
[From azqr - resources that can be deleted immediately]
- Resource name with Portal link - $X/month savings
[来自azqr的结果 - 可立即删除的资源]
- 资源名称(附门户链接) - 每月可节约$X
Optimization Recommendations
优化建议
Priority 1: High Impact, Low Risk
优先级1:高影响、低风险
[Example: Delete orphaned resources]
- 💰 ACTUAL cost: $X/month
- 📊 ESTIMATED savings: $Y/month
- Commands to execute (with warnings)
[示例:删除孤立资源]
- 💰 实际成本:每月$X
- 📊 预计节约:每月$Y
- 执行命令(含警告)
Priority 2: Medium Impact, Medium Risk
优先级2:中影响、中风险
[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
[示例:将VM从D4s_v5调整为D2s_v5]
- 💰 实际基准:D4s_v5,每月$X
- 📈 实际指标:CPU使用率8%,内存使用率30%
- 💵 已验证定价:D4s_v5 每小时$Y,D2s_v5 每小时$Z
- 📊 预计节约:每月$S
- 执行命令
Priority 3: Long-term Optimization
优先级3:长期优化
[Example: Reserved Instances, Storage tiering]
[示例:预留实例、存储分层]
Total Estimated Savings
预计总节约额
- Monthly: $X
- Annual: $Y
- 月度:$X
- 年度:$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: Thefile (if present) is a temporary query template and can be safely deleted. All permanent audit data is in thetemp/cost-query.jsonfolder.output/
**Portal Link Format:**https://portal.azure.com/#@<TENANT_ID>/resource/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RESOURCE_GROUP>/providers/<RESOURCE_PROVIDER>/<RESOURCE_TYPE>/<RESOURCE_NAME>/overview
undefined- 成本查询结果:
output/cost-query-result<timestamp>.json- 来自Azure成本管理API的原始成本数据
- 报告生成时实际成本的审计轨迹
- 需保留至少12个月以用于历史对比
- 包含分析周期内每个资源的精确成本
- 定价来源:[Azure定价页面链接]
- 免费层级额度:[适用的免费额度]
注意:若存在文件,它只是临时查询模板,可安全删除。所有永久审计数据均存储在temp/cost-query.json文件夹中。output/
**门户链接格式:**https://portal.azure.com/#@<TENANT_ID>/resource/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RESOURCE_GROUP>/providers/<RESOURCE_PROVIDER>/<RESOURCE_TYPE>/<RESOURCE_NAME>/overview
undefinedStep 8: Save Audit Trail
步骤8:保存审计轨迹
Save all cost query results for validation:
Use the tool with path :
create_fileoutput/cost-query-result<YYYYMMDD_HHMMSS>.jsonjson
{
"timestamp": "<ISO_8601>",
"subscription": "<SUBSCRIPTION_ID>",
"resourceGroup": "<RESOURCE_GROUP>",
"queries": [
{
"queryType": "ActualCost",
"timeframe": "MonthToDate",
"query": { },
"response": { }
}
]
}保存所有成本查询结果以用于验证:
使用工具,路径为:
create_fileoutput/cost-query-result<YYYYMMDD_HHMMSS>.jsonjson
{
"timestamp": "<ISO_8601>",
"subscription": "<SUBSCRIPTION_ID>",
"resourceGroup": "<RESOURCE_GROUP>",
"queries": [
{
"queryType": "ActualCost",
"timeframe": "MonthToDate",
"query": { },
"response": { }
}
]
}Step 9: Clean Up Temporary Files
步骤9:清理临时文件
Remove temporary query files and folder after the report is generated:
powershell
undefined报告生成后,删除临时查询文件和文件夹:
powershell
undefinedDelete entire temp folder (no longer needed)
删除整个temp文件夹(已无用处)
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.Remove-Item -Path "temp" -Recurse -Force -ErrorAction SilentlyContinue
> **注意**:`temp/cost-query.json`文件仅在API执行期间需要。实际查询和结果已保留在`output/cost-query-result*.json`中用于审计。Output
输出结果
The skill generates:
-
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
-
Cost Query Results ()
output/cost-query-result<timestamp>.json- Audit trail of all cost queries and responses
- Validation evidence for recommendations
本Skill将生成:
-
成本优化报告()
output/costoptimizereport<timestamp>.md- 包含总成本和主要驱动因素的执行摘要
- 带Azure门户链接的详细成本明细
- 基于实际数据和预计节约额的优先级建议
- 含安全警告的实施命令
-
成本查询结果()
output/cost-query-result<timestamp>.json- 所有成本查询和响应的审计轨迹
- 建议的验证依据
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
- 💰 实际数据 = 从Azure成本管理API获取
- 📈 实际指标 = 从Azure Monitor获取
- 💵 已验证定价 = 从官方Azure定价页面获取
- 📊 预计节约额 = 基于实际数据和已验证定价计算得出
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
- 始终先查询实际成本 - 绝不估算或假设
- 从官方来源验证定价 - 考虑免费层级
- 使用REST API进行成本查询(比更可靠)
az costmanagement query - 保存审计轨迹 - 包含所有查询和响应
- 为所有资源添加Azure门户链接
- 创建报告文件时使用UTF-8编码
- 对于每月成本低于$10的资源,重点强调运营改进而非财务节约
- 未经明确批准,绝不执行破坏性操作
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 with JSON body, not
az restaz costmanagement query
- 假设成本:始终从成本管理API查询实际数据
- 忽略免费层级:许多服务提供丰厚的免费额度(例如容器应用:每月免费180,000 vCPU秒)
- 使用错误的时间范围:成本查询用30天,使用指标用14天
- 门户链接失效:验证租户ID和资源ID格式
- 成本查询失败:使用带JSON请求体的,而非
az restaz 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
- 删除资源前需获得批准
- 先在非生产环境测试变更
- 提供用于验证的试运行命令
- 包含回滚流程
- 实施后监控影响