azure-cost-optimization by microsoft/github-copilot-for-azure
npx skills add https://github.com/microsoft/github-copilot-for-azure --skill azure-cost-optimization通过分析 Azure 订阅,基于实际使用数据,识别通过清理孤立资源、调整资源规模以及优化建议来节省成本的机会。
当用户提出以下要求时使用此技能:
与用户对话时,请遵循以下步骤:
开始之前,请验证以下工具和权限是否可用:
必需工具:
az login)costmanagement, resource-graph所需权限:
Analyze Azure subscriptions to identify cost savings through orphaned resource cleanup, rightsizing, and optimization recommendations based on actual usage data.
Use this skill when the user asks to:
Follow these steps in conversation with the user:
Before starting, verify these tools and permissions are available:
Required Tools:
az login)costmanagement, resource-graph广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
暂无相关 Skills
验证命令:
az --version
az account show
az extension show --name costmanagement
azqr version
获取 Azure 成本优化最佳实践,为建议提供依据:
// 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" }
})
如果用户特别请求 Redis 成本优化,请使用专门的 Redis 技能:
📋 参考:Azure Redis 成本优化
何时使用 Redis 特定分析:
关键能力:
redis_list 命令可用的报告模板:
注意:对于通用的订阅范围成本优化(包括 Redis),请继续执行步骤 2。对于仅关注 Redis 的分析,请遵循 Redis 特定参考文档中的说明。
如果执行 Redis 成本优化,请让用户选择分析范围:
向用户提示以下选项:
在继续执行步骤 2 之前,等待用户响应。
运行 azqr 以查找孤立资源(即时节省成本):
📋 参考:Azure Quick Review - 运行 azqr 扫描的详细说明
// Use Azure MCP extension_azqr tool
extension_azqr({
subscription: "<SUBSCRIPTION_ID>",
"resource-group": "<RESOURCE_GROUP>" // optional
})
在 azqr 结果中需要关注的内容:
注意:Azure Quick Review 参考文档包含创建筛选配置、将输出保存到
output/文件夹以及解释成本优化结果的说明。
为了高效地进行跨订阅资源发现,请使用 Azure Resource Graph。有关孤立资源检测和成本优化模式,请参阅 Azure Resource Graph 查询。
使用 Azure MCP 工具或 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
从 Azure Cost Management API 获取实际成本数据(最近 30 天):
创建成本查询文件:
创建 temp/cost-query.json,内容如下:
{
"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"
}
]
}
}
必需操作:计算
<START_DATE>(30 天前)和<END_DATE>(今天)的 ISO 8601 格式(例如2025-11-03T00:00:00Z)。
执行成本查询:
# 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'
重要提示: 将查询结果保存到 output/cost-query-result<timestamp>.json 以用于审计跟踪。
使用 fetch_webpage 从官方 Azure 定价页面获取当前定价:
// Validate pricing for key services
fetch_webpage({
urls: ["https://azure.microsoft.com/en-us/pricing/details/container-apps/"],
query: "pricing tiers and costs"
})
需要验证定价的关键服务:
重要提示: 检查免费层额度 - 许多 Azure 服务都有慷慨的免费额度,这可能解释了 $0 成本。
查询 Azure Monitor 获取使用率数据(最近 14 天),以支持调整规模的建议:
# 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
在 output/ 文件夹中创建全面的成本优化报告:
使用 create_file 工具,路径为 output/costoptimizereport<YYYYMMDD_HHMMSS>.md:
报告结构:
# Azure 成本优化报告
**生成时间**:<timestamp>
## 执行摘要
- 月度总成本:$X (💰 实际数据)
- 主要成本驱动因素:[列出前 3 个资源,附带 Azure 门户链接]
## 成本细分
[按成本排序的前 10 个资源表格,包含 Azure 门户链接]
## 免费层分析
[在免费层额度内运行、显示 $0 成本的资源]
## 孤立资源(即时节省)
[来自 azqr - 可以立即删除的资源]
- 资源名称及门户链接 - 每月节省 $X
## 优化建议
### 优先级 1:高影响,低风险
[示例:删除孤立资源]
- 💰 实际成本:每月 $X
- 📊 预计节省:每月 $Y
- 要执行的命令(附警告)
### 优先级 2:中等影响,中等风险
[示例:将 VM 从 D4s_v5 调整为 D2s_v5]
- 💰 实际基准:D4s_v5,每月 $X
- 📈 实际指标:CPU 8%,内存 30%
- 💵 已验证定价:D4s_v5 $Y/小时,D2s_v5 $Z/小时
- 📊 预计节省:每月 $S
- 要执行的命令
### 优先级 3:长期优化
[示例:预留实例、存储分层]
## 预计总节省
- 月度:$X
- 年度:$Y
## 实施命令
[附有批准警告的安全命令]
## 验证附录
### 数据源和文件
- **成本查询结果**:`output/cost-query-result<timestamp>.json`
- 来自 Azure Cost Management 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
保存所有成本查询结果以供验证:
使用 create_file 工具,路径为 output/cost-query-result<YYYYMMDD_HHMMSS>.json:
{
"timestamp": "<ISO_8601>",
"subscription": "<SUBSCRIPTION_ID>",
"resourceGroup": "<RESOURCE_GROUP>",
"queries": [
{
"queryType": "ActualCost",
"timeframe": "MonthToDate",
"query": { },
"response": { }
}
]
}
报告生成后,删除临时查询文件和文件夹:
# Delete entire temp folder (no longer needed)
Remove-Item -Path "temp" -Recurse -Force -ErrorAction SilentlyContinue
注意:
temp/cost-query.json文件仅在 API 执行期间需要。实际的查询和结果保存在output/cost-query-result*.json中以用于审计目的。
该技能生成:
output/costoptimizereport<timestamp>.md)
output/cost-query-result<timestamp>.json)
az costmanagement query 更可靠)az rest,而不是 az costmanagement query每周安装量
102.6K
代码仓库
GitHub 星标数
143
首次出现
2026年2月4日
安全审计
安装于
github-copilot102.5K
codex390
gemini-cli380
opencode363
kimi-cli351
amp351
Required Permissions:
Verification commands:
az --version
az account show
az extension show --name costmanagement
azqr version
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" }
})
If the user specifically requests Redis cost optimization , use the specialized Redis skill:
📋 Reference : Azure Redis Cost Optimization
When to use Redis-specific analysis:
Key capabilities:
redis_list commandReport 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.
If performing Redis cost optimization , ask the user to select their analysis scope:
Prompt the user with these options:
Wait for user response before proceeding to Step 2.
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:
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.
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
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.
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.
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
Create a comprehensive cost optimization report in the output/ folder:
Use thecreate_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
Save all cost query results for validation:
Use thecreate_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": { }
}
]
}
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.jsonfile is only needed during API execution. The actual query and results are preserved inoutput/cost-query-result*.jsonfor audit purposes.
The skill generates:
Cost Optimization Report (output/costoptimizereport<timestamp>.md)
Cost Query Results (output/cost-query-result<timestamp>.json)
az costmanagement query)az rest with JSON body, not az costmanagement queryWeekly Installs
102.6K
Repository
GitHub Stars
143
First Seen
Feb 4, 2026
Security Audits
Installed on
github-copilot102.5K
codex390
gemini-cli380
opencode363
kimi-cli351
amp351