azurecost
v1.2.1
Published
CLI tool and library to perform cost analysis on your Azure account with multiple output formats and visualizations
Maintainers
Readme
✨ Features
| Feature | Description | |---------|-------------| | 📊 Multiple Output Formats | Table, JSON, CSV, TSV, ASCII Chart, Excel, PNG Image | | 🔐 Flexible Authentication | SSO, Service Principal, Managed Identity, Device Code, Azure CLI | | 🎯 Smart Filtering | Filter by Resource Group or Service Type | | ⏰ Time Range Queries | Minutes, hours, days, custom date ranges with timezone support | | 🌍 Timezone Support | Configure default timezone (UTC, America/New_York, etc.) | | 💾 Auto-Save Reports | Automatically generate timestamped reports | | 📦 Dual Usage | Use as CLI tool or import as library in your code | | 🔍 Service Discovery | Search and list available Azure service types | | ⚙️ Configuration | Persistent settings for timezone, default ranges, and more |
🚀 Quick Start
# Install globally
npm install -g azurecost
# Login to Azure (if not already)
az login
# Run cost analysis
azurecostThat's it! You'll see an interactive cost report for your Azure subscription.
📦 Installation
Prerequisites
Before installing, ensure you have:
| Requirement | Version | Check Command |
|-------------|---------|---------------|
| Node.js | 20.0.0+ | node --version |
| npm | 9.0.0+ | npm --version |
| Azure CLI | (optional) | az --version |
Global CLI Installation
# Install globally (recommended for CLI usage)
npm install -g azurecost
# Verify installation
azurecost --versionProject Dependency (Library)
# For use in your Node.js/TypeScript projects
npm install azurecost
# Or with yarn
yarn add azurecost
# Or with pnpm
pnpm add azurecostRun Without Installing
# Run directly with npx (downloads temporarily)
npx azurecost
# Run specific version
npx [email protected]Upgrade
# Upgrade global installation to latest
npm update -g azurecost
# Or reinstall to specific version
npm install -g azurecost@latest
# Check current version
azurecost --version
# Upgrade project dependency
npm update azurecostUninstall
# Remove global installation
npm uninstall -g azurecost
# Remove from project
npm uninstall azurecost
# Clean up config files (optional)
# Windows:
rmdir /s /q "%USERPROFILE%\.azurecost"
# macOS/Linux:
rm -rf ~/.azurecostPlatform-Specific Notes
# Install with PowerShell (run as Administrator for global install)
npm install -g azurecost
# If you encounter permission issues
npm config set prefix "$env:APPDATA\npm"
# Add to PATH if needed
$env:PATH += ";$env:APPDATA\npm"# If permission denied, use sudo or fix npm permissions
npm install -g azurecost
# Or fix npm permissions (recommended)
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.zshrc
source ~/.zshrc
npm install -g azurecost# Install with npm
npm install -g azurecost
# If permission denied, use nvm or fix permissions
# Using nvm (recommended):
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install 20
nvm use 20
npm install -g azurecostFROM node:20-slim
# Install azurecost
RUN npm install -g azurecost
# Set working directory
WORKDIR /app
# Run with mounted Azure credentials
# docker run -v ~/.azure:/root/.azure azurecost-image azurecost -y# Build and run
docker build -t azurecost-image .
docker run -v ~/.azure:/root/.azure azurecost-image azurecost -yVerify Installation
# Check version
azurecost --version
# Show help
azurecost --help
# Test authentication (if Azure CLI is configured)
azurecost auth --cli
# Quick test (requires Azure login)
az login
azurecost -y --summary💻 CLI Usage
Basic Commands
# Show help
azurecost --help
# Analyze costs (interactive mode)
azurecost
# Skip confirmation prompt
azurecost -y
# Show version
azurecost versionCommand Structure
azurecost [command] [options]
Commands:
cost [options] Analyze Azure subscription costs (default)
services [options] List and search Azure service types
auth [options] Test Azure authentication
version Show version information
help [command] Display help for command🔐 Authentication
Authentication Methods
| Method | Flag | Description |
|--------|------|-------------|
| Default | --auth default | Auto-detect (tries all methods) |
| SSO/Interactive | --sso | Opens browser for login |
| Device Code | --device-code | Code-based auth for headless environments |
| Azure CLI | --cli | Uses existing az login session |
| Service Principal | --spn | Client ID + Secret authentication |
| Managed Identity | --identity | For Azure-hosted applications |
Examples
# Browser SSO login
azurecost --sso -s <subscription-id>
# Device code (for SSH/remote sessions)
azurecost --device-code -s <subscription-id>
# Service Principal
azurecost --spn \
--client-id <client-id> \
--client-secret <secret> \
--tenant-id <tenant-id> \
-s <subscription-id>
# Managed Identity (in Azure)
azurecost --identity -s <subscription-id>
# Test authentication
azurecost auth --sso
azurecost auth --cli📊 Output Formats
Format Options
| Format | Flag | Description |
|--------|------|-------------|
| Table | (default) | Colored, formatted table |
| JSON | --json | Machine-readable JSON |
| CSV | --csv | Comma-separated values |
| TSV | --tsv | Tab-separated values |
| Chart | --chart | ASCII bar chart visualization |
| Excel | --xlsx [file] | Excel spreadsheet (.xlsx) |
| Image | --image [file] | PNG chart visualization |
Examples
# JSON output
azurecost -y --json
# CSV output
azurecost -y --csv
# ASCII chart in terminal
azurecost -y --chart
# Export to Excel
azurecost -y --xlsx report.xlsx
# Export to PNG image
azurecost -y --image chart.png
# Multiple exports at once
azurecost -y --xlsx --image --json⏰ Time Ranges
Preset Ranges
# Last N periods
azurecost --range last-7d # Last 7 days
azurecost --range last-30d # Last 30 days
azurecost --range last-90d # Last 90 days
# Month ranges
azurecost --range this-month # Current month
azurecost --range last-month # Previous month
# Other presets
azurecost --range last-hour # Last hour
azurecost --range last-24h # Last 24 hours
azurecost --range this-year # Current yearRelative Ranges (Custom)
# Minutes
azurecost --range 30m # Last 30 minutes
azurecost --range 60m # Last 60 minutes
# Hours
azurecost --range 12h # Last 12 hours
azurecost --range 24h # Last 24 hours
azurecost --range 48h # Last 48 hours
# Days
azurecost --range 7d # Last 7 days
azurecost --range 14d # Last 14 days
azurecost --range 90d # Last 90 days
# Months
azurecost --range 3M # Last 3 months
azurecost --range 6M # Last 6 monthsCustom Date Ranges
# Using --from and --to
azurecost --from 2024-01-01 --to 2024-01-31
azurecost --from 2024-06-01 --to 2024-06-30
# Using range with date format
azurecost --range "2024-01-01..2024-01-31"
azurecost --range "2024-Q1-start..2024-Q1-end"
# With time (ISO 8601)
azurecost --from 2024-01-01T00:00:00 --to 2024-01-31T23:59:59Timezone Support
# Specify timezone per query
azurecost --range last-7d --timezone America/New_York
azurecost --range this-month --timezone Europe/London
azurecost --range last-24h --timezone Asia/Tokyo
# Set default timezone (persists)
azurecost config --set timezone=America/New_York⚙️ Configuration
Config Command
# View all settings
azurecost config --list
# Get specific setting
azurecost config --get timezone
# Set settings
azurecost config --set timezone=America/New_York
azurecost config --set defaultTimeRange=last-7d
azurecost config --set subscriptionId=your-subscription-id
# Reset to defaults
azurecost config --reset
# Show config file location
azurecost config --pathAvailable Settings
| Setting | Description | Default |
|---------|-------------|---------|
| timezone | Default timezone for queries | UTC |
| defaultTimeRange | Default time range for cost queries | last-30d |
| subscriptionId | Default Azure subscription ID | (none) |
Supported Timezones
UTC America/New_York America/Chicago
America/Denver America/Los_Angeles America/Toronto
America/Vancouver Europe/London Europe/Paris
Europe/Berlin Europe/Amsterdam Asia/Tokyo
Asia/Shanghai Asia/Singapore Asia/Dubai
Asia/Kolkata Australia/Sydney Australia/Melbourne
Pacific/Auckland🎯 Filtering
Filter by Resource Group
azurecost -g my-resource-group
azurecost --resource-group production-rgFilter by Service Type
azurecost --service "Virtual Machines"
azurecost --service "Storage"
azurecost --service "Azure Kubernetes Service"Combined Filters
azurecost -g my-rg --service "Virtual Machines" -y🔍 Service Discovery
Don't know the exact service name? Use the services command:
# List all common services
azurecost services
# Search for services
azurecost services -q storage
azurecost services -q database
azurecost services -q kubernetes
# Fetch live services from your subscription
azurecost services --live -s <subscription-id>
# Output as JSON
azurecost services --jsonExample Output
Available Azure Service Types
────────────────────────────────────────────────────────────
Use with: azurecost --service "<service-name>"
Azure Cosmos DB
NoSQL database
Azure Database for MySQL
Managed MySQL
Azure Database for PostgreSQL
Managed PostgreSQL
SQL Database
Managed SQL Server
────────────────────────────────────────────────────────────
Total: 4 services💾 Auto-Save Reports
Save to Default Location
# Saves to ./azurecost-reports/ with timestamp
azurecost --save
# Specify custom directory
azurecost --save --path ./my-reportsAuto-Generated Filenames
Files are automatically named with context:
azurecost_<subscription>_<resource-group>_<service>_<timestamp>.<ext>
Example: azurecost_my-sub_prod-rg_2024-01-15T10-30-00.xlsxExamples
# Auto-save JSON
azurecost --json --save
# Auto-save to custom path
azurecost --csv --save --path ./reports
# Auto-path Excel and Image
azurecost --xlsx --image📚 Library API
Installation
npm install azurecostBasic Usage
import { AzureCostClient } from 'azurecost';
// Create client (uses DefaultAzureCredential)
const client = new AzureCostClient();
// Get cost data
const costs = await client.getCosts();
console.log('This Month:', `$${costs.totals.thisMonth.toFixed(2)}`);
console.log('Last Month:', `$${costs.totals.lastMonth.toFixed(2)}`);With Options
import { AzureCostClient } from 'azurecost';
const client = new AzureCostClient({
subscriptionId: 'your-subscription-id',
resourceGroup: 'my-resource-group',
serviceName: 'Virtual Machines',
authMethod: 'interactive', // or 'spn', 'cli', etc.
});
const costs = await client.getCosts();Get Formatted Output
const client = new AzureCostClient();
// Get as JSON string
const json = await client.getCostsFormatted('json');
// Get as CSV string
const csv = await client.getCostsFormatted('csv');
// Get as table string
const table = await client.getCostsFormatted('table');Export to Files
const client = new AzureCostClient();
// Export to Excel
await client.exportToExcel('./costs.xlsx');
// Export to PNG image
await client.exportToImage('./chart.png');
// Export to any format (auto-detects from extension)
await client.exportToFile('./costs.csv');
await client.exportToFile('./costs.json');Service Principal Authentication
import { AzureCostClient } from 'azurecost';
const client = new AzureCostClient({
subscriptionId: process.env.AZURE_SUBSCRIPTION_ID,
tenantId: process.env.AZURE_TENANT_ID,
authMethod: 'spn',
clientId: process.env.AZURE_CLIENT_ID,
clientSecret: process.env.AZURE_CLIENT_SECRET,
});
const costs = await client.getCosts();Get Current Azure Account
import { AzureCostClient } from 'azurecost';
const account = await AzureCostClient.getCurrentAccount();
if (account) {
console.log('Subscription:', account.name);
console.log('ID:', account.subscriptionId);
console.log('Tenant:', account.tenantId);
}TypeScript Types
import {
AzureCostClient,
CostData,
CostTotals,
ServiceCosts,
OutputFormat,
AuthMethod,
} from 'azurecost';
// CostData structure
interface CostData {
account: string;
subscriptionId: string;
resourceGroup?: string;
serviceFilter?: string;
totals: CostTotals;
totalsByService: ServiceCosts;
generatedAt: string;
}
// CostTotals structure
interface CostTotals {
lastMonth: number;
thisMonth: number;
last7Days: number;
yesterday: number;
}🛠️ Configuration Examples
Environment Variables
# Set default subscription
export AZURE_SUBSCRIPTION_ID=your-subscription-id
# Service Principal credentials
export AZURE_TENANT_ID=your-tenant-id
export AZURE_CLIENT_ID=your-client-id
export AZURE_CLIENT_SECRET=your-client-secretCI/CD Pipeline (GitHub Actions)
name: Azure Cost Report
on:
schedule:
- cron: '0 9 * * 1' # Every Monday at 9 AM
jobs:
report:
runs-on: ubuntu-latest
steps:
- name: Generate Cost Report
run: |
npx azurecost \
--spn \
--client-id ${{ secrets.AZURE_CLIENT_ID }} \
--client-secret ${{ secrets.AZURE_CLIENT_SECRET }} \
--tenant-id ${{ secrets.AZURE_TENANT_ID }} \
-s ${{ secrets.AZURE_SUBSCRIPTION_ID }} \
-y --json > cost-report.json
- name: Upload Report
uses: actions/upload-artifact@v4
with:
name: cost-report
path: cost-report.jsonDocker Usage
FROM node:20-slim
RUN npm install -g azurecost
# Use with Azure CLI credentials mounted
# docker run -v ~/.azure:/root/.azure azurecost -yIntegration with Express.js
import express from 'express';
import { AzureCostClient } from 'azurecost';
const app = express();
const client = new AzureCostClient();
app.get('/api/costs', async (req, res) => {
try {
const costs = await client.getCosts();
res.json(costs);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/costs/summary', async (req, res) => {
try {
const costs = await client.getCosts();
res.json({
thisMonth: costs.totals.thisMonth,
lastMonth: costs.totals.lastMonth,
change: ((costs.totals.thisMonth - costs.totals.lastMonth) / costs.totals.lastMonth * 100).toFixed(1) + '%'
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000);📋 Complete CLI Reference
Cost Command (Default)
azurecost cost [options]
azurecost [options] # 'cost' is default
Options:
-s, --subscription-id <id> Azure subscription ID
-t, --tenant-id <id> Azure tenant ID
-g, --resource-group <name> Filter by resource group
--service <name> Filter by service type
-y, --yes Skip confirmation prompts
-u, --summary Show only summary
Authentication:
--sso Browser SSO login
--interactive Alias for --sso
--spn Service Principal
--identity Managed Identity
--managed-identity Alias for --identity
--device-code Device code flow
--cli Azure CLI credentials
--client-id <id> Client ID for SPN
--client-secret <secret> Client Secret for SPN
Output:
-j, --json JSON output
--csv CSV output
--tsv TSV output
--text Plain text output
--chart ASCII chart
--xlsx [file] Export to Excel
--image [file] Export to PNG
File:
--save Auto-save to ./azurecost-reports/
--path <dir> Custom save directoryServices Command
azurecost services [options]
Options:
-s, --subscription-id <id> Fetch live services from Azure
-q, --query <text> Search/filter services
--live Fetch live list (requires auth)
-j, --json Output as JSON
# Auth options same as cost commandAuth Command
azurecost auth [options]
Options:
--sso Test browser SSO
--interactive Alias for --sso
--spn Test Service Principal
--identity Test Managed Identity
--device-code Test device code
--cli Test Azure CLI
--default Test default chain
--client-id <id> Client ID
--client-secret <secret> Client Secret
-t, --tenant-id <id> Tenant ID🔧 Troubleshooting
Authentication Issues
# Test your authentication
azurecost auth --cli
# If using Azure CLI, make sure you're logged in
az login
az account show
# For SSO issues, try device code instead
azurecost --device-code -s <subscription-id>Permission Issues
Ensure your account has these permissions:
Microsoft.CostManagement/query/actionMicrosoft.Resources/subscriptions/read
Image Export on Windows
The --image option requires native dependencies. If installation fails:
# Alternative: Use ASCII chart
azurecost --chart
# Or Excel export
azurecost --xlsx report.xlsx📄 License
MIT © Rajkumar R
