id: github-actions-billing-spending-limit-sentinel
namespace: company.finops
description: |
Audits GitHub Actions minute consumption, tracks spending limit burn rates, and alerts Slack before budget caps freeze CI/CD pipelines.
inputs:
- id: github_org
type: STRING
displayName: GitHub Organization
defaults: "kestra-io"
description: "GitHub organization account name to audit for Actions minutes and
shared storage consumption."
- id: primary_repository
type: STRING
displayName: Primary Monitored Repository
defaults: "kestra-io/kestra"
description: "Key repository to sample recent workflow execution runtimes and
identify top minute-consuming workflows."
- id: monthly_spending_limit_usd
type: FLOAT
displayName: Monthly Spending Limit (USD)
defaults: 200.0
description: "Configured monthly spending limit in USD from GitHub Organization
Billing and Plans settings."
- id: warning_threshold_pct
type: FLOAT
displayName: Quota Warning Threshold (%)
defaults: 80.0
description: "Quota consumption percentage threshold to trigger warning notifications."
- id: critical_threshold_pct
type: FLOAT
displayName: Quota Critical Threshold (%)
defaults: 95.0
description: "Quota consumption percentage threshold to trigger critical freeze
risk alerts."
- id: rate_per_paid_minute_usd
type: FLOAT
displayName: Blended Paid Minute Rate (USD)
defaults: 0.008
description: "Standard billable runner rate per minute (Linux standard x86
2-core runner is $0.008/min)."
- id: rate_per_gb_storage_usd
type: FLOAT
displayName: Storage Rate per GB (USD)
defaults: 0.25
description: "Standard billable storage rate per GB-month for Actions artifacts
and GitHub Packages."
- id: slack_channel
type: STRING
displayName: Slack Channel
defaults: "#finops-alerts"
description: "Target Slack channel for billing quota notifications and burn-rate
warnings."
- id: always_notify_slack
type: BOOL
displayName: Always Notify Slack
defaults: false
description: "When true, dispatches summary report to Slack even if quota
consumption remains healthy."
triggers:
- id: daily_billing_audit
type: io.kestra.plugin.core.trigger.Schedule
description: "Runs daily audit at 08:00 UTC to evaluate consumption burn rates
before engineering standups."
cron: "0 8 * * *"
disabled: true
tasks:
- id: get_actions_billing
type: io.kestra.plugin.core.http.Request
description: "Retrieves organization Actions billable minutes, plan inclusions,
and runner breakdown from GitHub REST API."
uri: "https://api.github.com/orgs/{{ inputs.github_org
}}/settings/billing/actions"
method: GET
headers:
Accept: "application/vnd.github+json"
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
X-GitHub-Api-Version: "2022-11-28"
options:
allowFailed: true
timeout:
readIdleTimeout: PT15S
- id: get_shared_storage_billing
type: io.kestra.plugin.core.http.Request
description: "Retrieves organization shared storage usage and remaining days in
billing cycle from GitHub REST API."
uri: "https://api.github.com/orgs/{{ inputs.github_org
}}/settings/billing/shared-storage"
method: GET
headers:
Accept: "application/vnd.github+json"
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
X-GitHub-Api-Version: "2022-11-28"
options:
allowFailed: true
timeout:
readIdleTimeout: PT15S
- id: get_workflow_runs
type: io.kestra.plugin.core.http.Request
description: "Queries recent completed workflow runs from the primary repository
to identify top minute-consuming jobs."
uri: "https://api.github.com/repos/{{ inputs.primary_repository
}}/actions/runs?per_page=50&status=completed"
method: GET
headers:
Accept: "application/vnd.github+json"
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
X-GitHub-Api-Version: "2022-11-28"
options:
allowFailed: true
timeout:
readIdleTimeout: PT15S
- id: get_previous_billing_telemetry
type: io.kestra.plugin.core.kv.Get
description: "Loads the previous audit snapshot from Kestra KV store to measure
spend deltas across executions."
key: "github_billing_actions_{{ inputs.github_org }}"
errorOnMissing: false
- id: compute_billing_sentinel_metrics
type: io.kestra.plugin.scripts.python.Script
description: "Calculates quota consumption, daily burn rate, projected month-end
spend, and top workflow durations."
containerImage: python:3.12-slim
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
beforeCommands:
- pip install kestra
env:
ACTIONS_BILLING_JSON: "{{ (outputs.get_actions_billing.body ?? {}) | toJson }}"
SHARED_STORAGE_JSON: "{{ (outputs.get_shared_storage_billing.body ?? {}) | toJson }}"
WORKFLOW_RUNS_JSON: "{{ (outputs.get_workflow_runs.body ?? {}) | toJson }}"
PREVIOUS_TELEMETRY_JSON: "{{ (outputs.get_previous_billing_telemetry.value ?? {}) | toJson }}"
ORG_NAME: "{{ inputs.github_org }}"
SPENDING_LIMIT_USD: "{{ inputs.monthly_spending_limit_usd }}"
WARN_THRESHOLD_PCT: "{{ inputs.warning_threshold_pct }}"
CRIT_THRESHOLD_PCT: "{{ inputs.critical_threshold_pct }}"
MINUTE_RATE: "{{ inputs.rate_per_paid_minute_usd }}"
STORAGE_RATE: "{{ inputs.rate_per_gb_storage_usd }}"
ALWAYS_NOTIFY: "{{ inputs.always_notify_slack }}"
script: |
import json
import os
from datetime import datetime, timezone
from kestra import Kestra
org = os.environ.get("ORG_NAME", "kestra-io")
spending_limit = float(os.environ.get("SPENDING_LIMIT_USD", "200.0"))
warn_pct = float(os.environ.get("WARN_THRESHOLD_PCT", "80.0"))
crit_pct = float(os.environ.get("CRIT_THRESHOLD_PCT", "95.0"))
minute_rate = float(os.environ.get("MINUTE_RATE", "0.008"))
storage_rate = float(os.environ.get("STORAGE_RATE", "0.25"))
always_notify = os.environ.get("ALWAYS_NOTIFY", "false").lower() == "true"
try:
actions_raw = os.environ.get("ACTIONS_BILLING_JSON", "{}")
actions_data = json.loads(actions_raw) if isinstance(actions_raw, str) else actions_raw
if not isinstance(actions_data, dict):
actions_data = {}
except Exception:
actions_data = {}
try:
storage_raw = os.environ.get("SHARED_STORAGE_JSON", "{}")
storage_data = json.loads(storage_raw) if isinstance(storage_raw, str) else storage_raw
if not isinstance(storage_data, dict):
storage_data = {}
except Exception:
storage_data = {}
try:
runs_raw = os.environ.get("WORKFLOW_RUNS_JSON", "{}")
runs_data = json.loads(runs_raw) if isinstance(runs_raw, str) else runs_raw
if not isinstance(runs_data, dict):
runs_data = {}
except Exception:
runs_data = {}
try:
prev_raw = os.environ.get("PREVIOUS_TELEMETRY_JSON", "{}")
prev_data = json.loads(prev_raw) if isinstance(prev_raw, str) else prev_raw
if not isinstance(prev_data, dict):
prev_data = {}
except Exception:
prev_data = {}
total_minutes_used = float(actions_data.get("total_minutes_used", 0) or 0)
total_paid_minutes = float(actions_data.get("total_paid_minutes_used", 0) or 0)
included_minutes = float(actions_data.get("included_minutes", 0) or 0)
breakdown = actions_data.get("minutes_used_breakdown", {})
if not isinstance(breakdown, dict):
breakdown = {}
days_left_in_cycle = int(storage_data.get("days_left_in_billing_cycle", 0) or 0)
estimated_paid_storage_gb = float(storage_data.get("estimated_paid_storage_for_month", 0) or 0)
estimated_storage_gb = float(storage_data.get("estimated_storage_for_month", 0) or 0)
spend_minutes_usd = total_paid_minutes * minute_rate
spend_storage_usd = estimated_paid_storage_gb * storage_rate
total_spend_usd = round(spend_minutes_usd + spend_storage_usd, 2)
if spending_limit > 0:
quota_consumption_pct = round((total_spend_usd / spending_limit) * 100.0, 2)
else:
quota_consumption_pct = 0.0
if included_minutes > 0:
included_consumption_pct = round((total_minutes_used / included_minutes) * 100.0, 2)
else:
included_consumption_pct = 0.0
now_utc = datetime.now(timezone.utc)
if 0 < days_left_in_cycle < 31:
days_elapsed = max(1, 30 - days_left_in_cycle)
else:
days_elapsed = max(1, now_utc.day)
days_left_in_cycle = max(0, 30 - days_elapsed)
daily_burn_rate = round(total_spend_usd / days_elapsed, 2)
projected_month_end_spend = round(total_spend_usd + (daily_burn_rate * days_left_in_cycle), 2)
if spending_limit > 0:
projected_consumption_pct = round((projected_month_end_spend / spending_limit) * 100.0, 2)
else:
projected_consumption_pct = 0.0
is_critical = quota_consumption_pct >= crit_pct or (projected_consumption_pct >= 100.0 and total_spend_usd > 0)
is_warning = (quota_consumption_pct >= warn_pct or projected_consumption_pct >= warn_pct) and not is_critical
if is_critical:
status = "CRITICAL"
status_headline = "CRITICAL FREEZE RISK: Spending Limit Breach Imminent"
status_detail = (
f"Actions billing spend (${total_spend_usd:.2f}) has reached {quota_consumption_pct:.1f}% of "
f"limit (${spending_limit:.2f}), or burn rate projects ${projected_month_end_spend:.2f} ({projected_consumption_pct:.1f}%). "
f"GitHub disables private repository workflow runs upon reaching 100%."
)
elif is_warning:
status = "WARNING"
status_headline = "WARNING: Actions Quota Approaching Spending Limit"
status_detail = (
f"Actions billing spend (${total_spend_usd:.2f}) is at {quota_consumption_pct:.1f}% of "
f"limit (${spending_limit:.2f}). Projected month-end spend is ${projected_month_end_spend:.2f} ({projected_consumption_pct:.1f}%)."
)
else:
status = "HEALTHY"
status_headline = "HEALTHY: Actions Usage Within Budget Thresholds"
status_detail = (
f"Actions consumption is nominal at ${total_spend_usd:.2f} of ${spending_limit:.2f} limit ({quota_consumption_pct:.1f}%). "
f"{days_left_in_cycle} days remaining in cycle."
)
should_alert = is_critical or is_warning or always_notify
workflow_durations = {}
runs_list = runs_data.get("workflow_runs", [])
if isinstance(runs_list, list):
for run in runs_list:
if not isinstance(run, dict):
continue
wf_name = run.get("name") or f"Workflow #{run.get('workflow_id', 'unknown')}"
started_str = run.get("run_started_at")
updated_str = run.get("updated_at")
if started_str and updated_str:
try:
t0 = datetime.fromisoformat(started_str.replace("Z", "+00:00"))
t1 = datetime.fromisoformat(updated_str.replace("Z", "+00:00"))
duration_mins = max(0.0, (t1 - t0).total_seconds() / 60.0)
workflow_durations[wf_name] = workflow_durations.get(wf_name, 0.0) + duration_mins
except Exception:
pass
top_workflows = []
if workflow_durations:
sorted_wf = sorted(workflow_durations.items(), key=lambda x: x[1], reverse=True)[:5]
for name, dur in sorted_wf:
top_workflows.append({
"workflow_name": name,
"total_sampled_minutes": round(dur, 1),
"estimated_spend_usd": round(dur * minute_rate, 2)
})
if top_workflows:
top_wf_lines = [f"• `{wf['workflow_name']}`: {wf['total_sampled_minutes']:.1f} mins (~${wf['estimated_spend_usd']:.2f})" for wf in top_workflows]
top_workflows_text = "\n".join(top_wf_lines)
else:
top_workflows_text = "No sampled repository workflow runs available. Review organization repository list."
breakdown_items = []
for k, v in breakdown.items():
if k.upper() in ["UBUNTU", "MACOS", "WINDOWS"] and v > 0:
breakdown_items.append(f"{k}: {v}m")
breakdown_text = ", ".join(breakdown_items) if breakdown_items else "No OS minutes recorded"
prev_spend = float(prev_data.get("estimated_spend_usd", 0.0) or 0.0)
spend_delta_usd = round(total_spend_usd - prev_spend, 2)
telemetry_payload = {
"organization": org,
"status": status,
"timestamp": now_utc.isoformat(),
"total_minutes_used": total_minutes_used,
"included_minutes": included_minutes,
"total_paid_minutes_used": total_paid_minutes,
"included_consumption_pct": included_consumption_pct,
"estimated_spend_usd": total_spend_usd,
"spending_limit_usd": spending_limit,
"quota_consumption_pct": quota_consumption_pct,
"daily_burn_rate_usd": daily_burn_rate,
"projected_month_end_spend_usd": projected_month_end_spend,
"projected_consumption_pct": projected_consumption_pct,
"spend_delta_since_previous_audit_usd": spend_delta_usd,
"days_left_in_cycle": days_left_in_cycle,
"estimated_storage_gb": estimated_storage_gb,
"estimated_paid_storage_gb": estimated_paid_storage_gb,
"runner_breakdown": breakdown,
"top_workflows": top_workflows
}
print(f"Sentinel evaluation completed: status={status}, spend=${total_spend_usd:.2f}, quota={quota_consumption_pct:.1f}%, projected=${projected_month_end_spend:.2f}")
Kestra.outputs({
"status": status,
"status_headline": status_headline,
"status_detail": status_detail,
"total_minutes_used": total_minutes_used,
"included_minutes": included_minutes,
"total_paid_minutes_used": total_paid_minutes,
"included_consumption_pct": included_consumption_pct,
"estimated_spend_usd": total_spend_usd,
"spending_limit_usd": spending_limit,
"quota_consumption_pct": quota_consumption_pct,
"daily_burn_rate_usd": daily_burn_rate,
"projected_month_end_spend_usd": projected_month_end_spend,
"projected_consumption_pct": projected_consumption_pct,
"spend_delta_usd": spend_delta_usd,
"days_left_in_cycle": days_left_in_cycle,
"estimated_storage_gb": estimated_storage_gb,
"estimated_paid_storage_gb": estimated_paid_storage_gb,
"is_critical": is_critical,
"is_warning": is_warning,
"should_alert": should_alert,
"top_workflows_text": top_workflows_text,
"runner_breakdown_text": breakdown_text,
"telemetry_payload": telemetry_payload
})
- id: save_billing_telemetry_kv
type: io.kestra.plugin.core.kv.Set
description: "Persists organization billing telemetry, burn rates, and quota
status into Kestra KV store."
key: "github_billing_actions_{{ inputs.github_org }}"
value: "{{ outputs.compute_billing_sentinel_metrics.vars.telemetry_payload |
toJson }}"
kvType: JSON
- id: evaluate_spending_gate
type: io.kestra.plugin.core.flow.If
description: "Dispatches Slack incident notification if spending limit breach
warning or critical freeze risk is detected."
condition: "{{ outputs.compute_billing_sentinel_metrics.vars.should_alert }}"
then:
- id: alert_slack_quota_breach
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: "Dispatches actionable FinOps warning or freeze alert to the
designated Slack channel."
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": "{{ inputs.slack_channel }}",
"text": "[FINOPS ALERT] {{ outputs.compute_billing_sentinel_metrics.vars.status_headline }} (Org: {{ inputs.github_org }})",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "FinOps Sentinel: GitHub Actions Spending Limit Alert"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Status:* `{{ outputs.compute_billing_sentinel_metrics.vars.status }}`\n*Organization:* `{{ inputs.github_org }}`\n*Alert Detail:* {{ outputs.compute_billing_sentinel_metrics.vars.status_detail }}"
}
},
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*Current Spend:*\n${{ outputs.compute_billing_sentinel_metrics.vars.estimated_spend_usd }} / ${{ inputs.monthly_spending_limit_usd }} ({{ outputs.compute_billing_sentinel_metrics.vars.quota_consumption_pct }}%)"
},
{
"type": "mrkdwn",
"text": "*Projected Month-End:*\n${{ outputs.compute_billing_sentinel_metrics.vars.projected_month_end_spend_usd }} ({{ outputs.compute_billing_sentinel_metrics.vars.projected_consumption_pct }}%)"
},
{
"type": "mrkdwn",
"text": "*Daily Burn Rate:*\n${{ outputs.compute_billing_sentinel_metrics.vars.daily_burn_rate_usd }} / day"
},
{
"type": "mrkdwn",
"text": "*Days Left in Cycle:*\n{{ outputs.compute_billing_sentinel_metrics.vars.days_left_in_cycle }} days"
},
{
"type": "mrkdwn",
"text": "*Minutes (Used / Included):*\n{{ outputs.compute_billing_sentinel_metrics.vars.total_minutes_used }} / {{ outputs.compute_billing_sentinel_metrics.vars.included_minutes }} (Paid: {{ outputs.compute_billing_sentinel_metrics.vars.total_paid_minutes_used }})"
},
{
"type": "mrkdwn",
"text": "*Storage (Total / Paid):*\n{{ outputs.compute_billing_sentinel_metrics.vars.estimated_storage_gb }} GB / {{ outputs.compute_billing_sentinel_metrics.vars.estimated_paid_storage_gb }} GB"
}
]
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Top Minute-Consuming Workflows:*\n{{ outputs.compute_billing_sentinel_metrics.vars.top_workflows_text }}\n\n*Runner OS Breakdown:* {{ outputs.compute_billing_sentinel_metrics.vars.runner_breakdown_text }}"
}
},
{
"type": "context",
"elements": [
{
"type": "mrkdwn",
"text": "Action Required: Verify workflow timeouts, prune artifact retention, or increase spending limits at https://github.com/organizations/{{ inputs.github_org }}/settings/billing."
}
]
}
]
}
else:
- id: log_healthy_quota
type: io.kestra.plugin.core.log.Log
description: "Logs nominal spending status when consumption is safely within
quota limits."
message: "GitHub Actions billing nominal for {{ inputs.github_org }}: Spend=${{
outputs.compute_billing_sentinel_metrics.vars.estimated_spend_usd
}}/${{ inputs.monthly_spending_limit_usd }} ({{
outputs.compute_billing_sentinel_metrics.vars.quota_consumption_pct
}}%), Projected=${{
outputs.compute_billing_sentinel_metrics.vars.projected_month_end_spe\
nd_usd }}, Days Remaining={{
outputs.compute_billing_sentinel_metrics.vars.days_left_in_cycle }}."
- id: export_billing_manifest
type: io.kestra.plugin.core.debug.Return
description: "Returns structured telemetry dictionary for downstream FinOps
dashboards or data warehouse ingestion."
format:
organization: "{{ inputs.github_org }}"
status: "{{ outputs.compute_billing_sentinel_metrics.vars.status }}"
quota_consumption_pct: "{{
outputs.compute_billing_sentinel_metrics.vars.quota_consumption_pct }}"
estimated_spend_usd: "{{ outputs.compute_billing_sentinel_metrics.vars.estimated_spend_usd }}"
projected_month_end_spend_usd: "{{
outputs.compute_billing_sentinel_metrics.vars.projected_month_end_spend\
_usd }}"
daily_burn_rate_usd: "{{ outputs.compute_billing_sentinel_metrics.vars.daily_burn_rate_usd }}"
days_left_in_cycle: "{{ outputs.compute_billing_sentinel_metrics.vars.days_left_in_cycle }}"
errors:
- id: alert_sentinel_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: "Alerts FinOps channel when API calls fail or credentials expire."
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": "{{ inputs.slack_channel }}",
"text": "[CRITICAL] GitHub Actions Billing Sentinel flow execution {{ execution.id }} failed for org {{ inputs.github_org }}. Verify GITHUB_TOKEN permissions or network connectivity."
}