An intelligent Python tool that analyzes your Azure subscription, identifies cost-saving opportunities, and provides actionable recommendations. Save up to 40% on your Azure bill with automated insights.
| Feature | Description |
|---|---|
| π Comprehensive Cost Analysis | Analyze spending by resource group, service, and location |
| π‘ Smart Recommendations | AI-driven suggestions for cost optimization |
| π Trend Analysis | Track spending trends and predict future costs |
| π¨ Visual Reports | Generate PDF, Excel, and JSON reports |
| π§ Automated Alerts | Email notifications for budget overruns |
| π Scheduled Scans | Continuous monitoring with configurable schedules |
| π³ Docker Support | Run anywhere with containerized deployment |
- π₯οΈ Idle Resources: Find unused VMs, disks, and public IPs
- π Right-sizing: Identify oversized VMs based on actual metrics
- π΅ Reserved Instances: Calculate savings with RI purchases
- πΎ Storage Optimization: Detect expensive storage tiers
- ποΈ Snapshot Cleanup: Identify outdated snapshots and backups
- ποΈ Database Optimization: Find idle or oversized SQL databases
- Python 3.11+ (Download)
- Azure subscription with Cost Management access
- Azure CLI or Service Principal credentials
# Clone repository
git clone https://github.com/rchamoli/azure-cost-optimizer.git
cd azure-cost-optimizer
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install package
pip install -e .
# Or install with development dependencies
pip install -e ".[dev]"# Copy environment template
cp .env.example .env
# Edit with your Azure credentials
nano .env # or use your preferred editorRequired environment variables:
AZURE_SUBSCRIPTION_ID=your-subscription-id
AZURE_TENANT_ID=your-tenant-id
AZURE_CLIENT_ID=your-client-id
AZURE_CLIENT_SECRET=your-client-secretπ‘ Tip: You can also use Azure CLI authentication. If logged in via
az login, credentials are picked up automatically.
# Basic analysis with console output
python cost_optimizer.py analyze
# Or use the installed CLI
azure-cost-optimizer analyze
# Analyze specific resource group
azure-cost-optimizer analyze --resource-group myResourceGroup
# Generate PDF report
azure-cost-optimizer analyze --format pdf --output report.pdf
# Analyze last 90 days
azure-cost-optimizer analyze --days 90
# Send report via email
azure-cost-optimizer analyze --email
# Validate Azure connection
azure-cost-optimizer validate
# Show current configuration
azure-cost-optimizer configββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Azure Cost Optimization Report β
β January 2024 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π Cost Summary:
Current Month: $15,234.56
Previous Month: $14,890.23
Change: +2.3% ($344.33)
Projected (EOY): $182,814.72
π‘ Potential Savings: $4,521.00 per month (29.7%)
π― Top Recommendations:
1. Stop Idle Virtual Machines (8 found)
π° Estimated Savings: $1,840/month
π Resources: vm-dev-01, vm-test-03, vm-staging-02...
2. Delete Unattached Disks (15 found)
π° Estimated Savings: $325/month
3. Right-size Oversized VMs (5 found)
π° Estimated Savings: $1,156/month
4. Purchase Reserved Instances
π° Estimated Savings: $1,200/month
azure-cost-optimizer/
βββ src/azure_cost_optimizer/ # Main package
β βββ analyzers/ # Cost analysis modules
β β βββ compute.py # VM and disk analysis
β β βββ storage.py # Storage analysis
β β βββ network.py # Network analysis
β β βββ database.py # Database analysis
β βββ recommenders/ # Recommendation engines
β β βββ reserved_instances.py
β βββ reporters/ # Report generators
β β βββ console.py # Terminal output
β β βββ pdf.py # PDF generation
β β βββ excel.py # Excel export
β β βββ email.py # Email reports
β βββ utils/ # Utilities
β β βββ azure_client.py # Azure SDK wrapper
β β βββ cost_calculator.py # Cost calculations
β β βββ metrics.py # Metrics collection
β βββ cli.py # CLI commands
β βββ config.py # Configuration
β βββ models.py # Data models
β βββ optimizer.py # Main orchestrator
βββ tests/ # Test suite
βββ .github/workflows/ # CI/CD pipelines
βββ pyproject.toml # Project configuration
βββ Dockerfile # Container image
βββ docker-compose.yml # Docker Compose setup
All configuration is done via environment variables. See .env.example for the full list.
| Variable | Description | Default |
|---|---|---|
AZURE_SUBSCRIPTION_ID |
Azure subscription to analyze | Required |
AZURE_TENANT_ID |
Azure AD tenant ID | Optional* |
AZURE_CLIENT_ID |
Service principal client ID | Optional* |
AZURE_CLIENT_SECRET |
Service principal secret | Optional* |
ANALYSIS_DAYS |
Days to analyze | 30 |
DEFAULT_OUTPUT_FORMAT |
Output format | console |
*Optional if using Azure CLI authentication
| Variable | Description | Default |
|---|---|---|
IDLE_VM_CPU_PERCENT |
CPU % to consider VM idle | 5 |
IDLE_VM_DAYS |
Days of idle before flagging | 7 |
SNAPSHOT_AGE_DAYS |
Age to flag old snapshots | 90 |
MIN_SAVINGS_THRESHOLD |
Minimum savings to report | 10 |
| Variable | Description | Default |
|---|---|---|
EMAIL_ENABLED |
Enable email reports | false |
SMTP_SERVER |
SMTP server hostname | smtp.gmail.com |
SMTP_PORT |
SMTP port | 587 |
EMAIL_FROM |
Sender email address | - |
EMAIL_TO |
Recipients (comma-separated) | - |
# Build image
docker build -t azure-cost-optimizer .
# Run analysis
docker run --env-file .env azure-cost-optimizer analyze
# Generate PDF report (mount volume for output)
docker run --env-file .env -v $(pwd)/reports:/app/reports \
azure-cost-optimizer analyze --format pdf --output /app/reports/report.pdf# Run one-time analysis
docker compose run --rm optimizer analyze
# Start scheduled analyzer (weekly)
docker compose --profile scheduled up -d scheduler# Install with dev dependencies
pip install -e ".[dev]"
# Install pre-commit hooks
pre-commit install# Run all tests
pytest
# Run with coverage
pytest --cov=src/azure_cost_optimizer --cov-report=html
# Run specific test file
pytest tests/test_models.py -v# Run linter
ruff check src/ tests/
# Auto-fix issues
ruff check --fix src/ tests/
# Format code
ruff format src/ tests/
# Type checking
mypy src/azure_cost_optimizerThe service principal needs these roles:
| Role | Purpose |
|---|---|
Cost Management Reader |
Read cost data |
Reader |
Read resource metadata |
Monitoring Reader |
Read performance metrics |
# Create service principal with required roles
az ad sp create-for-rbac --name "cost-optimizer-sp" \
--role "Cost Management Reader" \
--scopes /subscriptions/{subscription-id}
# Assign additional roles
az role assignment create \
--assignee {service-principal-id} \
--role "Reader" \
--scope /subscriptions/{subscription-id}
az role assignment create \
--assignee {service-principal-id} \
--role "Monitoring Reader" \
--scope /subscriptions/{subscription-id}- β
Never commit
.envor credentials to git - β Use Azure Managed Identity in production
- β Rotate service principal secrets regularly
- β Use least-privilege access (read-only roles)
- β Enable audit logging for the service principal
- β Store secrets in Azure Key Vault for production
- Use Azure Managed Identity instead of service principal secrets
- Deploy to Azure Container Instances or Azure Functions
- Enable Azure Monitor for container logs
- Set up budget alerts in Azure Cost Management
- Configure email notifications for stakeholders
- Schedule weekly/monthly analysis runs
- Store reports in Azure Blob Storage
- Enable RBAC for report access
# Deploy to ACI
az container create \
--resource-group myResourceGroup \
--name cost-optimizer \
--image ghcr.io/rchamoli/azure-cost-optimizer:latest \
--assign-identity \
--restart-policy OnFailure \
--environment-variables \
AZURE_SUBSCRIPTION_ID=your-sub-id \
LOG_LEVEL=INFO# Deploy as Azure Function (timer-triggered)
func azure functionapp publish YourFunctionAppAuthentication Failed
Error: DefaultAzureCredential failed to retrieve a token
Solutions:
- Verify Azure CLI is logged in:
az account show - Check service principal credentials in
.env - Ensure tenant ID is correct
- Run
azure-cost-optimizer validateto test connection
Cost Data Unavailable
Warning: Cost Management API access limited
Solutions:
- Ensure
Cost Management Readerrole is assigned - Cost data may take 24-48 hours to appear for new subscriptions
- Check if Cost Management is enabled for the subscription
No Recommendations Found
Possible causes:
- All resources are already optimized
- Metrics data not available (wait 7+ days)
- Thresholds too strict - adjust in
.env - Resource group filter too narrow
from azure_cost_optimizer import CostOptimizer
# Create optimizer instance
optimizer = CostOptimizer(subscription_id="your-sub-id")
# Run analysis
result = optimizer.analyze(days=30)
# Get recommendations
recommendations = optimizer.get_recommendations(limit=10)
# Calculate total savings
total_savings = optimizer.calculate_potential_savings()
print(f"Potential savings: ${total_savings}/month")
# Generate reports
optimizer.generate_report(format="pdf", output="report.pdf")
optimizer.generate_report(format="json", output="data.json")
# Export to JSON
optimizer.export_to_json("analysis.json")
# Send email report
optimizer.send_email(attachment_format="pdf")
# Clean up
optimizer.close()- Multi-subscription support
- AWS and GCP cost analysis
- Machine learning for anomaly detection
- Slack/Teams integration
- Custom policies and rules engine
- Historical trend analysis (12+ months)
- What-if scenario modeling
- Integration with Azure DevOps
- Terraform cost estimation
- Real-time cost alerts
Contributions are welcome! Please see our Contributing Guide for details.
- Additional analyzers for Azure services (AKS, App Service, etc.)
- Enhanced visualization options
- Performance optimizations
- Documentation improvements
- Integration tests
This project is licensed under the MIT License - see the LICENSE file for details.
Rahul Chamoli - Cloud Engineer & Cost Optimization Specialist
- Azure Cost Management Team
- Python Azure SDK contributors
- Open-source reporting libraries (ReportLab, Pandas, Rich)
- Azure Cost Management Documentation
- Azure SDK for Python
- Azure Well-Architected Framework - Cost Optimization
- FinOps Foundation
π° Save money, optimize resources, sleep better!
β Star this repo if it helps you reduce your Azure costs!
