# FinOps Cost Governance Example

Implement cost governance framework with budgets, showback, and optimization.

## Cost Budget Framework

```nickel
{
  finops = {
    budgets = [
      {
        name = "production_monthly",
        workspace = "production",
        monthly_limit = 50000,
        alert_thresholds = [
          { percentage = 75, action = "notify" },
          { percentage = 90, action = "escalate" },
          { percentage = 100, action = "freeze" }
        ]
      },
      {
        name = "staging_monthly",
        workspace = "staging",
        monthly_limit = 10000,
        alert_thresholds = [
          { percentage = 80, action = "notify" },
          { percentage = 100, action = "freeze" }
        ]
      },
      {
        name = "development_monthly",
        workspace = "development",
        monthly_limit = 5000,
        alert_thresholds = [
          { percentage = 100, action = "freeze" }
        ]
      }
    ],

    chargeback = {
      enabled = true,
      model = "team-based",
      allocation_method = "usage",
      monthly_reports = true
    }
  }
}
```

## Cost Monitoring

```nushell
def monitor-cloud-costs [] {
    print "Cloud Cost Monitoring Dashboard"
    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

    let today = (date now)
    let month_start = ($today | date format "%Y-%m-01")
    let month_end = ($today | date format "%Y-%m-%d")

    let costs = (
        provisioning cost analyze \
            --from $month_start \
            --to $month_end \
            --group-by "service,tag:team"
    )

    # By Service
    print ""
    print "Top 10 Services by Cost:"
    $costs.by_service
    | sort-by cost --reverse
    | first 10
    | each { | service |
        print $"  ($service.name): $($service.cost.monthly) (($service.percentage)% of total)"
    }

    # By Team (Chargeback)
    print ""
    print "Cost by Team (Chargeback):"
    $costs.by_team
    | each { | team |
        let budget = (provisioning budget get --team $team.name)
        let percentage = ($team.cost / $budget.monthly_limit) * 100
        let status = if $percentage > 100 {
            "⚠️  OVER BUDGET"
        } else if $percentage > 80 {
            "⚠️  WARNING"
        } else {
            "✓ OK"
        }

        print $"  ($team.name): $($team.cost) / $($budget.monthly_limit) ($percentage.0)% - ($status)"
    }

    # Top Offenders (High Cost)
    print ""
    print "Top Cost Anomalies:"
    let anomalies = (
        $costs.by_resource
        | where cost > 1000
        | sort-by cost --reverse
        | first 5
    )

    if ($anomalies | length) > 0 {
        $anomalies | each { | resource |
            print $"  ($resource.name): $($resource.cost) - Review for optimization"
        }
    } else {
        print "  No significant anomalies detected"
    }
}
```

## Showback Reports

```nushell
def generate-cost-showback-report [--team: string] {
    print $"Generating cost showback report for ($team)..."

    let period = "2025-01"
    let costs = (
        provisioning cost analyze \
            --from $"($period)-01" \
            --to $"($period)-31" \
            --filter $"tag:team=($team)"
    )

    let report = {
        team: $team,
        period: $period,
        summary: {
            total_cost: $costs.total,
            compute_cost: $costs.compute,
            storage_cost: $costs.storage,
            network_cost: $costs.network,
            database_cost: $costs.database
        },
        breakdown: {
            by_service: $costs.by_service,
            by_resource: $costs.by_resource,
            by_region: $costs.by_region
        },
        trends: {
            daily_average: ($costs.total / 31),
            week_over_week: $costs.wow_change,
            month_over_month: $costs.mom_change
        },
        optimization_opportunities: (
            find-optimization-opportunities --team $team --costs $costs
        )
    }

    # Export as CSV for accounting
    export-cost-report-csv --report $report --filename $"showback-($team)-($period).csv"

    print $"✓ Showback report generated: showback-($team)-($period).csv"
}

def find-optimization-opportunities [--team: string, --costs: record] {
    let opportunities = []

    # Check for overprovisioned instances
    let oversized = (
        provisioning analyze resources \
            --filter $"tag:team=($team)" \
            --metric cpu_utilization \
            --threshold 20
    )

    if ($oversized | length) > 0 {
        $opportunities | append {
            title: "Downsize overprovisioned instances",
            count: ($oversized | length),
            estimated_savings: ($oversized | map .monthly_savings | math sum)
        }
    }

    # Check for unused resources
    let unused = (
        provisioning analyze resources \
            --filter $"tag:team=($team)" \
            --metric usage_days \
            --threshold 0
    )

    if ($unused | length) > 0 {
        $opportunities | append {
            title: "Remove unused resources",
            count: ($unused | length),
            estimated_savings: ($unused | map .monthly_cost | math sum)
        }
    }

    # Check for non-reserved instances in production
    let non_reserved = (
        provisioning analyze instances \
            --filter $"tag:team=($team),tag:environment=production" \
            --reserved false
    )

    if ($non_reserved | length) > 10 {
        $opportunities | append {
            title: "Purchase reserved instances",
            count: ($non_reserved | length),
            estimated_savings: ($non_reserved | map .yearly_savings | math sum)
        }
    }

    $opportunities
}
```

## Budget Enforcement

```nushell
def enforce-budget-limits [] {
    print "Enforcing budget limits..."

    let teams = ["platform", "backend", "frontend", "data"]

    $teams | each { | team |
        let budget = (provisioning budget get --team $team)
        let current_spend = (provisioning cost current-month --team $team)
        let remaining = $budget.monthly_limit - $current_spend.total
        let percentage = ($current_spend.total / $budget.monthly_limit) * 100

        print ""
        print $"Team: ($team)"
        print $"  Budget: $($budget.monthly_limit)"
        print $"  Current Spend: $($current_spend.total)"
        print $"  Remaining: $($remaining)"
        print $"  Usage: ($percentage.0)%"

        # Actions based on thresholds
        if $percentage >= 100 {
            print "  ⛔ ACTION: Budget exceeded, enforcing freeze"
            provisioning budget enforce --team $team --action freeze
        } else if $percentage >= 90 {
            print "  🔴 ACTION: Critical alert, notifying team leads"
            provisioning notification send \
                --team $team \
                --severity critical \
                --message "Budget nearly exhausted"
        } else if $percentage >= 75 {
            print "  🟡 ACTION: Warning alert"
            provisioning notification send \
                --team $team \
                --severity warning \
                --message "Budget at 75%, plan optimizations"
        }
    }
}
```

## Optimization Recommendations

```nushell
def recommend-cost-optimizations [] {
    print "Analyzing infrastructure for optimization opportunities..."

    let recommendations = []

    # 1. Idle resource detection
    let idle_resources = (
        provisioning analyze resources --idle-days 30
    )

    if ($idle_resources | length) > 0 {
        $recommendations | append {
            category: "Remove Idle Resources",
            savings: ($idle_resources | map .monthly_cost | math sum),
            effort: "Low",
            risk: "Low",
            items: ($idle_resources | map .name)
        }
    }

    # 2. Right-sizing
    let oversized = (
        provisioning analyze resources --overprovisioned true
    )

    if ($oversized | length) > 0 {
        $recommendations | append {
            category: "Right-Size Instances",
            savings: ($oversized | map .monthly_savings | math sum),
            effort: "Medium",
            risk: "Medium",
            items: ($oversized | map .name)
        }
    }

    # 3. Reserved instances
    let on_demand = (
        provisioning analyze instances \
            --environment production \
            --reserved false
    )

    if ($on_demand | length) > 10 {
        $recommendations | append {
            category: "Purchase Reserved Instances",
            savings: ($on_demand | map .yearly_savings | math sum),
            effort: "Low",
            risk: "Low",
            items: $on_demand
        }
    }

    # 4. Storage optimization
    let unoptimized_storage = (
        provisioning analyze storage --optimization-level low
    )

    if ($unoptimized_storage | length) > 0 {
        $recommendations | append {
            category: "Optimize Storage Tiers",
            savings: ($unoptimized_storage | map .monthly_savings | math sum),
            effort: "Medium",
            risk: "Low",
            items: $unoptimized_storage
        }
    }

    # Sort by savings
    $recommendations
    | sort-by savings --reverse
    | each { | rec |
        print ""
        print $"($rec.category) - Potential Savings: $($rec.savings)"
        print $"  Effort: ($rec.effort) | Risk: ($rec.risk)"
        print $"  Items: ($rec.items | length)"
    }
}
```

## Cost Allocation Tags

Enforce consistent tagging for cost allocation:

```nushell
def validate-cost-allocation-tags [] {
    print "Validating cost allocation tags..."

    let required_tags = [
        "team",
        "environment",
        "cost-center",
        "application",
        "owner"
    ]

    let resources = (provisioning resource list)

    let untagged = (
        $resources | filter { | resource |
            $required_tags | any { | tag |
                $resource.tags | where name == $tag | length == 0
            }
        }
    )

    if ($untagged | length) > 0 {
        print "⚠️  Resources missing cost allocation tags:"
        $untagged | each { | resource |
            print $"  - ($resource.name)"
        }
        return 1
    }

    print "✓ All resources properly tagged for cost allocation"
}
```

## See Also

- [Cost Optimization Examples](./cost-optimization-examples.md)
- [Capacity Planning](../operations/capacity-planning.md)
- [Monitoring Guide](../operations/monitoring.md)
