microsoft/azure-skills / azure-cost-optimization
azure-cost-optimization
- Установки
- 209,329
- Автор
- microsoft/azure-skills
Анализирует расходы Azure и находит способы сократить затраты: выявляет неиспользуемые ресурсы, завышенные размеры виртуальных машин и другие переплаты. Формирует подробный отчет с рекомендациями по оптимизации и оценкой экономии.
Установить скилл
npx skills add https://github.com/microsoft/azure-skills --skill azure-cost-optimization
Аудит безопасности
Gen Agent Trust Hub
passThis skill is designed to analyze Azure environments for cost-saving opportunities. It uses standard Azure CLI commands and Microsoft-provided tools to identify orphaned resources and generate optimization reports. The skill adheres to established security practices for the Azure ecosystem.
Audited: 3/30/2026, 9:50:16 PM
Socket
passNo alerts
Audited: 3/30/2026, 9:50:35 PM
Snyk
passRisk: LOW · No issues
Audited: 3/30/2026, 9:50:07 PM
Промпт скилла
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_listcommand
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:
- 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, 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_aksfor 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 aksandkubectlonly when the specific operation cannot be performed via the MCP surface
Reference files (load only what is needed for the request):
- Cost Analysis Add-on — enable namespace-level cost visibility
- Anomaly Investigation — cost spikes, scaling events, budget alerts
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:
- Specific Cluster Name - Analyze a single AKS cluster
- Resource Group - Analyze all clusters in a resource group
- Subscription ID - Analyze all clusters in a subscription
- 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:
- 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.
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.jsonfile is only needed during API execution. The actual query and results are preserved inoutput/cost-query-result*.jsonfor audit purposes.
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
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 restwith JSON body, notaz 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
Все файлы скилла
- SKILL.md
- references/auth-best-practices.md
- references/azure-aks-anomalies.md
- references/azure-aks-cost-addon.md
- references/azure-quick-review.md
- references/azure-redis.md
- references/azure-resource-graph.md
- references/sdk/azure-resource-manager-redis-dotnet.md
- templates/redis-detailed-cache-analysis.md
- templates/redis-subscription-level-report.md
Другие скиллы автора
azure-diagnostics
554,288 установокmicrosoft/azure-skills
Скилл для системной диагностики и устранения проблем Azure в продакшене: от App Service, Functions и AKS до виртуальных машин и очередей сообщений. Использует AppLens, Azure Monitor и проверку ресурсов, чтобы быстро находить первопричины сбоев, анализировать логи и предлагать шаги по восстановлению.
azure-prepare
553,704 установокmicrosoft/azure-skills
Скилл готовит проекты к развёртыванию в Azure: анализирует кодовую базу, выбирает подходящий сценарий (Bicep, Terraform или AZD) и создаёт всю необходимую инфраструктуру — план развёртывания, конфигурационные файлы и Dockerfile. Автоматизирует подготовительный этап, чтобы последующая валидация и деплой прошли без ошибок.
azure-ai
553,621 установокmicrosoft/azure-skills
Скилл для работы с сервисами Azure AI: поиск (включая векторный и гибридный), распознавание и синтез речи, транскрибация, OCR и документы. Помогает быстро выполнять задачи через MCP-инструменты или подсказывает нужные SDK-примеры для Python, TypeScript и .NET. Ускоряет интеграцию с Azure AI Search, Speech, OpenAI и Document Intelligence.
azure-deploy
553,594 установокmicrosoft/azure-skills
Навык автоматизирует развертывание уже подготовленных приложений в Azure с помощью azd, terraform и az deployment. Он проверяет готовность плана, выполняет деплой, обрабатывает ошибки и подтверждает успешный запуск, возвращая ссылки на ресурсы. Полезен для надежного и повторяемого деплоя без ручных шагов.
azure-validate
553,079 установокmicrosoft/azure-skills
Проверяет готовность Azure-окружения к развертыванию: конфигурацию, Bicep/Terraform-шаблоны, роли RBAC и разрешения managed identity. Позволяет выявить проблемы до деплоя, сэкономить время и избежать сбоев.
azure-storage
552,529 установокmicrosoft/azure-skills
Скилл для работы с Azure Storage: управление блоб-хранилищем, файловыми ресурсами, очередями и таблицами. Помогает выбирать уровни доступа (hot/cool/cold/archive) и варианты избыточности, а также выполнять операции через CLI или MCP. Полезен для загрузки, скачивания и перечисления объектов в облаке Azure.
entra-app-registration
552,269 установокmicrosoft/azure-skills
Скилл помогает регистрировать приложения в Microsoft Entra ID, настраивать OAuth 2.0 и подключать MSAL для аутентификации пользователей и сервисов. Охватывает создание app registration, настройку API-разрешений, клиентских секретов и сертификатов, а также лучшие практики безопасности. Удобен для быстрой настройки аутентификации в веб-, мобильных и фоновых приложениях.
appinsights-instrumentation
552,016 установокmicrosoft/azure-skills
Скилл предоставляет руководство по инструментированию веб-приложений с помощью Azure Application Insights: описывает паттерны телеметрии, настройку SDK и конфигурацию. Помогает разработчикам добавлять мониторинг в приложения, а также разграничивает случаи, когда следует использовать azure-prepare для внесения изменений в проект.
azure-resource-lookup
551,937 установокmicrosoft/azure-skills
Находит и перечисляет ресурсы Azure любого типа по подпискам и группам ресурсов через Azure Resource Graph. Помогает отвечать на вопросы «что у меня есть», искать ресурсы по тегам, обнаруживать осиротевшие диски и неиспользуемые IP-адреса. Используется, когда нет выделенного MCP-инструмента для нужного типа ресурсов.
azure-resource-visualizer
551,932 установокmicrosoft/azure-skills
Анализирует группы ресурсов Azure и создает подробные диаграммы архитектуры в формате Mermaid. Помогает визуализировать взаимосвязи между ресурсами, группировать их по слоям и документировать инфраструктуру. Полезен для понимания структуры облачных решений и создания наглядной документации.
azure-compliance
551,896 установокmicrosoft/azure-skills
Проводит аудит безопасности и соответствия Azure: оценивает ресурсы по лучшим практикам, находит неверно настроенные и потерянные ресурсы, а также проверяет ключи, секреты и сертификаты Key Vault на истечение срока действия. Помогает выявлять критические риски и планировать их устранение.
azure-aigateway
551,722 установокmicrosoft/azure-skills
Настраивает Azure API Management как AI-шлюз для управления моделями, MCP-инструментами и агентами. Включает семантическое кэширование, лимиты токенов, контроль безопасности, балансировку нагрузки и мониторинг. Помогает централизованно управлять доступом к AI-сервисам и снижать расходы.
azure-kusto
551,647 установокmicrosoft/azure-skills
Помогает работать с Azure Data Explorer (Kusto): выполнять KQL-запросы, исследовать схему таблиц, анализировать логи, телеметрию и временные ряды. Полезен для поиска аномалий, агре
azure-messaging
541,378 установокmicrosoft/azure-skills
Навык для диагностики и устранения неполадок в Azure Messaging SDK (Event Hubs, Service Bus). Помогает решать проблемы с подключением, аутентификацией, обработкой сообщений и конфигурацией. Использует инструменты MCP для проверки состояния ресурсов, поиска документации и анализа ошибок.
azure-compute
495,407 установокmicrosoft/azure-skills
Помогает подбирать, сравнивать и создавать виртуальные машины и масштабируемые наборы в Azure, а также оценивать их стоимость. Разбирается в сценариях резервирования мощности, автомасштабирования и управления машинами, направляя запрос к нужному рабочему процессу.
azure-rbac
486,709 установокmicrosoft/azure-skills
Помогает подобрать роль Azure RBAC с минимальными правами для идентичности, сгенерировать команды CLI и код Bicep для её назначения. Также подскажет, какие разрешения нужны, чтобы выдать доступ другому пользователю или сервису.
azure-cloud-migrate
485,404 установокmicrosoft/azure-skills
Помогает оценить и перенести существующие облачные нагрузки в Azure: конвертирует код и конфигурацию, формирует отчёт о миграции. Поддерживает переезд AWS Lambda, Elastic Beanstalk, Heroku, Google App Engine, Kubernetes, Cloud Run и Spring Boot в Azure Functions, App Service и Container Apps.
azure-hosted-copilot-sdk
438,545 установокmicrosoft/azure-skills
Скилл автоматизирует сборку, развертывание и доработку приложений на GitHub Copilot SDK в Azure: определяет наличие SDK в коде, создаёт инфраструктуру, настраивает модели (включая BYOM) и запускает деплой. Полезен, когда нужно быстро подготовить или модифицировать Copilot-приложение без ручной настройки Azure.
azure-quotas
421,637 установокmicrosoft/azure-skills
Помогает проверять и управлять квотами Azure: лимитами ресурсов, текущим использованием и доступной ёмкостью в регионах. Позволяет планировать развёртывание, сравнивать регионы по доступности квот, запрашивать увеличение лимитов и избегать ошибок превышения. Использует Azure CLI для точных данных.
azure-upgrade
413,773 установокmicrosoft/azure-skills
Навык для оценки и автоматизации обновления Azure-ресурсов: планов, SKU, тарифов, а также модернизации Azure SDK в коде. Поддерживает сценарии: обновление Azure Functions (Consumption→Flex), миграцию App Service на Container Apps, обновление Java SDK (com.microsoft.azure→com.azure) и миграцию Azure Cache
azure-enterprise-infra-planner
388,208 установокmicrosoft/azure-skills
Навык проектирует корпоративную инфраструктуру Azure: сети, безопасность, identity, мультирегиональные сценарии. Генерирует код Bicep или Terraform, проверяет его на соответствие лучшим практикам и безопасность, затем разворачивает с подтверждением. Помогает архитекторам и инженерам быстро создавать надёжные облачные решения.
azure-kubernetes
381,128 установокmicrosoft/azure-skills
Навык помогает планировать и создавать кластеры Azure Kubernetes Service (AKS): выбирать SKU, проектировать сеть, настраивать безопасность, наблюдаемость, обновления и оптимизацию затрат. Различает решения Day-0 (сеть, API-сервер) и Day-1 (автомасштабирование, VPA, Spot-пулы), предоставляет чек-листы и сценарии для глубокой настройки.
azure-cost
356,363 установокmicrosoft/azure-skills
Навык для управления затратами в Azure: позволяет запрашивать исторические данные о расходах, прогнозировать будущие затраты и получать рекомендации по оптимизации. Помогает анализировать затраты по подпискам, группам ресурсов и другим областям, а также выявлять возможности для сокращения расходов.
airunway-aks-setup
300,339 установокmicrosoft/azure-skills
Скилл помогает развернуть AI Runway на кластере AKS: проверяет готовность кластера, устанавливает контроллер, выбирает провайдера инференса и запускает модель. Пошагово проводит от начальной настройки до первого развертывания, с проверкой статуса на каждом этапе.