# Cost Estimation

Source: https://docs.ops0.com/docs/iac/deployments/cost

Before applying changes, ops0 automatically calculates estimated monthly costs using real-time cloud pricing data. Cost estimates help teams budget infrastructure changes and prevent unexpected billing surprises.

## Supported Cloud Providers

| Provider | Pricing Source | Coverage |
|----------|---------------|----------|
| **AWS** | Real-time pricing APIs | Full |
| **GCP** | Real-time pricing APIs | Full |
| **Azure** | Real-time pricing APIs | Full |
| **Oracle Cloud (OCI)** | Oracle public pricing API with static fallback | Full |

## How Cost Estimation Works

### Automatic Trigger
Cost estimation runs automatically during the plan stage of every deployment.

### Resource Analysis
ops0 parses the Terraform plan output to identify all resources being created, modified, or destroyed.

### Pricing Lookup
For each resource, ops0 queries real-time cloud pricing APIs based on:
- Cloud provider (AWS, GCP, Azure, or OCI)
- Resource type (compute instances, databases, storage, etc.)
- Region
- Configuration (instance type, storage size, IOPS, etc.)

Oracle Cloud uses a hybrid pricing engine that queries Oracle's public pricing API first, with a curated static price list as fallback. OCI pricing is uniform across regions.

### Cost Calculation
Monthly costs are calculated using:
- Instance hours: `instance_price * 730 hours/month`
- Storage: `storage_size_gb * price_per_gb`
- Data transfer: Baseline estimates for common usage patterns

### Display Results
Cost summary appears in the deployment panel alongside the Terraform plan.

## Cost Display

```
Monthly Cost Estimate
─────────────────────────────────────
aws_instance.web           $60.00/mo
aws_rds_cluster.main      $200.00/mo
aws_s3_bucket.data          $2.50/mo
─────────────────────────────────────
Total:                    $262.50/mo

Previous:                 $200.00/mo
Change:                   +$62.50/mo (+31.2%)
```

### Cost Breakdown by Resource

Click any resource in the cost estimate to see detailed pricing breakdown:

**Example: EC2 Instance Breakdown**

```
aws_instance.web - $60.00/mo
─────────────────────────────────────
Instance (t3.medium)         $30.41/mo
  730 hours × $0.0416/hour

EBS Volume (gp3, 30GB)        $2.40/mo
  30 GB × $0.08/GB

EBS IOPS (3000)               $0.00/mo
  Included in gp3 base

Data Transfer OUT             $27.19/mo
  300 GB × $0.09/GB (estimated)
─────────────────────────────────────
Total:                       $60.00/mo
```

---

## Supported Resource Types

| Resource Type | Cost Components | Coverage |
|---------------|-----------------|----------|
| **EC2 Instances** | Instance hours, EBS volumes, EBS IOPS, data transfer | ✅ Full |
| **RDS** | Instance hours, storage, backup storage, IOPS, multi-AZ | ✅ Full |
| **S3** | Storage (Standard, IA, Glacier), requests, data transfer | ✅ Full |
| **Lambda** | Request count, duration (GB-seconds), data transfer | ✅ Full |
| **ELB/ALB/NLB** | Load balancer hours, LCU hours, data processed | ✅ Full |
| **DynamoDB** | Read/write capacity units, storage, backups | ✅ Full |
| **CloudFront** | Data transfer, requests | ✅ Full |
| **NAT Gateway** | Gateway hours, data processed | ✅ Full |
| **ECS/Fargate** | vCPU hours, memory hours, data transfer | ✅ Full |
| **ElastiCache** | Node hours, backup storage | ✅ Full |
| **EKS** | Cluster hours, node hours (EC2 pricing) | ✅ Full |
| **VPC Endpoints** | Endpoint hours, data processed | ⚠️ Partial |
| **Route53** | Hosted zones, queries | ⚠️ Partial |

---

## Budget Tracking

Set budget limits for projects to receive alerts when estimated costs approach or exceed thresholds.

### Setting a Budget

### Navigate to Project Settings
Open your IaC project and click the settings icon.

### Set Budget Amount
Enter monthly budget limit (e.g., $500/month).

### Configure Alerts
Choose alert thresholds:
- **Warning**: 80% of budget ($400)
- **Critical**: 100% of budget ($500)
- **Overage**: 120% of budget ($600)

### Save Configuration
Budget is applied to all future deployments.

### Budget Status Indicators

During deployment, budget status is displayed prominently:

```
Budget Status
─────────────────────────────────────
Current Estimate:  $262.50/mo
Budget Limit:      $500.00/mo
Remaining:         $237.50/mo (47.5%)

Status: ✅ Within Budget
```

**Warning State** (80-100% of budget):

```
Budget Status
─────────────────────────────────────
Current Estimate:  $425.00/mo
Budget Limit:      $500.00/mo
Remaining:         $75.00/mo (15%)

Status: ⚠️ Approaching Budget Limit
```

**Critical State** (100%+ of budget):

```
Budget Status
─────────────────────────────────────
Current Estimate:  $650.00/mo
Budget Limit:      $500.00/mo
Over Budget:       $150.00/mo (+30%)

Status: 🚫 Budget Exceeded
```

### Budget Policy Enforcement

Optionally block deployments that exceed budget:

### Enable Budget Policy
In project settings, toggle "Block deployments over budget".

### Attempted Deployment
When cost estimate exceeds budget, deployment is blocked at plan stage.

### Override Permission
Users with `budget.override` permission can approve over-budget deployments.

### Audit Trail
All budget overrides are logged in audit logs with justification.

---

## Cost Alerts and Notifications

Configure automatic notifications when costs change significantly.

### Alert Types

| Alert Type | Trigger | Notification |
|------------|---------|--------------|
| **Budget Warning** | Estimate reaches 80% of budget | Email, Slack |
| **Budget Exceeded** | Estimate exceeds budget | Email, Slack, PagerDuty |
| **Cost Spike** | Estimate increases >50% from previous | Email, Slack |
| **Expensive Resource** | Single resource >$500/mo | Email |
| **Cost Reduction** | Estimate decreases >20% | Email (optional) |

### Configuring Alerts

### Navigate to Settings → Integrations
Configure Slack webhook or email settings.

### Enable Cost Alerts
In project settings, toggle desired alert types.

### Set Thresholds
Customize percentage thresholds for spike detection.

### Test Alerts
Use "Send Test Alert" to verify configuration.

### Example Alert: Cost Spike

**Slack Notification:**

```
🚨 Cost Alert: IaC Project "production-api"

Estimated monthly cost increased significantly:
Previous: $200.00/mo
Current:  $350.00/mo
Change:   +$150.00/mo (+75%)

New Resources:
+ aws_elasticache_cluster.redis - $120.00/mo
+ aws_instance.worker (2×) - $60.00/mo

Deployment #47 | View Details →
```

**Email Notification:**

```
Subject: [ops0 Cost Alert] production-api deployment exceeded budget

Hello,

Your IaC project "production-api" has a deployment with estimated
costs exceeding your $500/mo budget.

Estimated Cost: $650.00/mo
Budget Limit:   $500.00/mo
Overage:        $150.00/mo

Top Cost Contributors:
1. aws_rds_cluster.analytics - $280.00/mo
2. aws_instance.api (3×) - $180.00/mo
3. aws_elasticache_cluster.redis - $120.00/mo

View deployment: https://ops0.dev/projects/prod-api/deployments/47

To approve this deployment, click: [Approve Deployment]
To reject and cancel, click: [Cancel Deployment]
```

---

## Cost History and Trends

Track how infrastructure costs evolve over time across deployments.

### Viewing Cost History

Navigate to **Project → Cost History** to see:

- Line chart of estimated costs across all deployments
- Cost breakdown by resource type over time
- Comparison between estimated and actual costs (if AWS Cost Explorer is integrated)

**Example Cost History:**

```
Cost Trend (Last 30 Days)
─────────────────────────────────────
$400 │                             ╭─
     │                           ╭─╯
$300 │                     ╭─────╯
     │               ╭─────╯
$200 │         ╭─────╯
     │   ╭─────╯
$100 │───╯
     └────────────────────────────────
     Jan 1    Jan 15         Jan 30

Deployments: 12
Avg Cost: $275/mo
Peak Cost: $380/mo (Jan 28)
Current: $350/mo
```

### Cost Attribution

Understand which resources drive costs:

| Resource Type | Jan | Feb | Change |
|---------------|-----|-----|--------|
| **RDS** | $200 | $280 | +$80 (+40%) |
| **EC2** | $120 | $180 | +$60 (+50%) |
| **ElastiCache** | $0 | $120 | +$120 (new) |
| **S3** | $15 | $18 | +$3 (+20%) |
| **NAT Gateway** | $32 | $32 | $0 (0%) |
| **Total** | $367 | $630 | +$263 (+71.7%) |

---

## Estimate Accuracy and Limitations

**Estimate Limitations**

Cost estimates are calculated using real-time cloud pricing APIs and Terraform resource configurations. Actual costs may vary based on:

- **Usage Patterns**: Data transfer, API requests, and compute utilization
- **Regional Pricing**: Prices vary by cloud provider and region
- **Free Tier**: Free tier credits not accounted for
- **Reserved/Committed Use**: Reserved Instances (AWS), Committed Use Discounts (GCP), and Reserved VM Instances (Azure) are not applied to estimates
- **Spot/Preemptible Instances**: Spot and preemptible pricing not estimated (uses on-demand rates)
- **Pricing Changes**: Cloud providers update pricing periodically
- **Unsupported Resources**: Some newer resource types may lack pricing data

**Best Practice**: Use estimates for budgeting and relative comparisons. Verify actual costs in your cloud provider's billing console.

### Improving Estimate Accuracy

### Tag Resources
Add tags or labels to resources in Terraform for better cost allocation tracking in your cloud provider.

### Use Modules
Modular infrastructure makes cost attribution clearer.

### Regular Reconciliation
Compare estimated costs to your cloud provider's billing console monthly.

### Update Usage Assumptions
Adjust data transfer and request volume assumptions based on actual usage patterns.

---

## Example: Estimating Infrastructure Cost Before Deployment

**Scenario**: Adding ElastiCache Redis cluster to production API infrastructure.

**Step 1: Plan Deployment**

Run Terraform plan to create a change preview.

**Step 2: Review Cost Impact**

```
Cost Comparison
─────────────────────────────────────
Previous Monthly Cost: $200.00

Resource Changes:
+ aws_elasticache_cluster.redis
    Node Type: cache.r6g.large
    Nodes: 2 (primary + replica)
    Cost: $120.00/mo

New Monthly Cost: $320.00
Change: +$120.00/mo (+60%)
```

**Step 3: Detailed Breakdown**

```
aws_elasticache_cluster.redis - $120.00/mo
─────────────────────────────────────
Primary Node (cache.r6g.large)  $60.00/mo
  730 hours × $0.082/hour

Replica Node (cache.r6g.large)  $60.00/mo
  730 hours × $0.082/hour

Data Transfer (estimated)        $0.00/mo
  Within VPC (no charge)
─────────────────────────────────────
Total:                         $120.00/mo
```

**Step 4: Budget Check**

```
Budget Status
─────────────────────────────────────
Current Estimate:  $320.00/mo
Budget Limit:      $500.00/mo
Remaining:         $180.00/mo (36%)

Status: ✅ Within Budget
```

**Step 5: Approve or Adjust**

- **Option A**: Proceed with deployment (within budget)
- **Option B**: Reduce to smaller instance type (`cache.t4g.medium` - $30/mo total)
- **Option C**: Use single node without replica ($60/mo instead of $120/mo)

**Decision**: Proceed with 2-node cluster for high availability. Total cost $320/mo is acceptable within $500 budget.

---

## Next Steps

- [Deployments](https://docs.ops0.com/docs/iac/deployments): Deploy infrastructure after reviewing costs

- [Budget Settings](https://docs.ops0.com/docs/settings/budget): Configure organization-wide budget limits

- [Projects](https://docs.ops0.com/docs/iac/projects): Manage IaC projects and settings
