Cut GitHub Actions CI cost ~10x with ephemeral self-hosted EC2 runners
Every CI job gets its own fresh EC2 machine in your AWS account, created when the job is queued and destroyed when it finishes. GitHub still schedules the jobs and shows the logs; only the machine underneath changes.
8 vCPU Linux
Per minute
AWS CodeBuild LARGE
$0.020
GitHub-hosted 8-core
$0.022
EC2 on-demand
~$0.006
EC2 spot
~$0.002
Moving off CodeBuild, on the same jobs: about the same speed, about 10x cheaper (spot first with on-demand fallback, light jobs on 2 vCPU machines, and no checks a change cannot affect).
How it works
GitHub queues a job (runs-on: <your label>)
-> "job queued" webhook from your GitHub App
-> API Gateway + Lambda (github-aws-runners, MIT) checks repo and label
-> scale-up Lambda starts an EC2 machine (spot first, on-demand if spot is full)
-> the machine boots your pre-built image and registers for exactly that job
-> the job runs, the runner exits, the machine is terminated
github-aws-runners is the open-source part that listens for queued jobs and starts and stops the machines.
The pre-built image already has Docker, build tools and the GitHub runner installed, so a job starts in about 35 seconds instead of spending three minutes installing them.
Files
SKILL.md: the full procedure, written for a coding agent (Claude Code skill format) and readable by a person: estimate, AWS access, quota increases, image, spot vs on-demand, small vs large machines, routing, benchmarks, cutover and rollback, and the failure modes we hit.
estimate_ci_savings.py: prices your repo's real CI minutes on each option (gh only).
main.tf, variables.tf: the Terraform root.
runner-image.pkr.hcl: the Packer image.
fetch_upstream.sh: the module release's Lambda zips (attestation-verified) and runner scripts.
ci-runner-reclaim-retry.yml: re-runs a job once when AWS reclaims its spot machine.
To use it as a Claude Code skill, put SKILL.md (and the other files beside it) in .claude/skills/ci-runners-migration/ of your repo.
MIT licensed, like the github-aws-runners module it builds on.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Move a repository's GitHub Actions CI off a hosted runner pool (AWS CodeBuild, GitHub-hosted larger runners, or a runner vendor) onto ephemeral self-hosted EC2 runners in your own AWS account, with the open-source github-aws-runners Terraform module. Covers measuring current CI minutes and estimating savings, AWS access and vCPU quota increases, the runner image, spot vs on-demand, small vs large machines, benchmarking, a variable-based cutover with instant rollback, and the failure modes seen in practice. Use when someone asks to cut CI cost, move off CodeBuild, self-host GitHub runners, or compare runner vendors.
Move CI to ephemeral self-hosted EC2 runners
The goal: every CI job gets its own fresh EC2 machine in your AWS account, created for that job and destroyed when it ends, routed by one repository variable so the move is reversible in one command. This gist is a working template from a real migration (Experiential Labs, November 2026): main.tf and variables.tf (the Terraform root), runner-image.pkr.hcl (the Packer image), fetch_upstream.sh (the module's verified Lambda zips and runner scripts), ci-runner-reclaim-retry.yml (the spot-reclaim re-run) and estimate_ci_savings.py (the savings estimate). Copy them rather than re-deriving; every number below was measured during that migration.
Why it is cheaper (say this plainly to the requester)
The saving is mostly the price per minute, not magic:
A managed CI service charges roughly 3x the raw on-demand price; spot is a further 60 to 70% off. So self-hosted spot runs about 8 to 10x cheaper per minute than CodeBuild, about 3x on all on-demand. On top of that, two independent cuts compound: running only the checks a change can affect (fewer minutes), and giving light jobs 2 or 4 vCPU machines (cheaper minutes). Do not promise 100x; promise what the measurement in step 1 shows.
Two things to raise before any work:
Credits. If AWS credits pay for the current CI, the cash saving is zero until they run out; the benefit is that credits last several times longer. Ask the requester to read the credit balance and expiry from the AWS Billing console (the API does not expose them).
Who operates it. Self-hosting means the team owns the image, module upgrades and the quota. If nobody will, a runner vendor at $0.005 to $0.016 per minute is the honest alternative.
Step 1: measure and estimate
Run scripts/estimate_ci_savings.py --repo <owner/name> --days 7 (needs gh). It sums the wall-clock minutes of completed jobs per runner label over the window, adds a boot allowance per job, and prices the same minutes on each option. Report:
minutes per week and per month, and the jobs that dominate (usually the integration and full-stack suites);
peak concurrent jobs: this sizes the vCPU quota (step 3). The script prints it;
the estimate per option, with on-demand as the conservative case and spot as the expected case.
If the repo runs on CodeBuild, cross-check with the build list (aws codebuild list-builds-for-project plus batch-get-builds), which bills per started minute, and with Cost Explorer (aws ce get-cost-and-usage, RECORD_TYPE=Usage, grouped by SERVICE) to separate gross usage from credits.
Before moving anything, cut minutes that cannot fail for a change: path-scoped suites, heavy non-required jobs skipped on draft PRs (re-run on ready_for_review), one integration mode on PRs and the full matrix nightly, and on single-side changes only the tests that read the other side's files. A required check must still report on every PR; a stacked PR retargeted to main is not re-run, so never skip required checks on stacked PRs.
Step 2: AWS access
Use a dedicated CI account, never the production account. Confirm the profile with aws sts get-caller-identity.
The operator creates Lambda functions, an API Gateway, SQS queues, SSM parameters, IAM roles, an S3 bucket, a launch template and EC2 instances. Admin in the CI account is simplest.
Create once, by hand: the spot service-linked role (aws iam create-service-linked-role --aws-service-name spot.amazonaws.com). Without it every spot launch fails with AuthFailure.ServiceLinkedRoleCreationNotPermitted.
Terraform state goes in a dedicated, versioned, encrypted, private S3 bucket for this root (backend s3 with partial config at init), never a bucket another service owns.
Step 3: quotas (start this first; it is the slow part)
Two separate EC2 quotas, both in vCPUs, per region:
L-1216C47A Running On-Demand Standard instances.
L-34B43A08 All Standard Spot Instance Requests.
Read them with aws service-quotas get-service-quota --service-code ec2 --quota-code <code>. Size each to the measured peak concurrent jobs times 8 vCPU (a peak of about 160 jobs means about 1,280 vCPU). Request both with aws service-quotas request-service-quota-increase. Large asks open a support case that can take days, and the Support API needs a paid support plan, so the requester replies on the case in the AWS Support Center with the reason ("ephemeral GitHub Actions runners, one 8-vCPU instance per job, measured peak N concurrent"). AWS may grant part first. Check what else uses the on-demand quota in that account (an EKS cluster, preview nodes): it is shared, and it is why spot-first matters.
Step 4: the runner stack
Use github-aws-runners/terraform-aws-github-runner (MIT), pinned to an exact release at least two weeks old. main.tf here has all of these set. The settings that mattered:
enable_ephemeral_runners = true (one job per machine) and enable_job_queued_check = true.
job_retry = { enable = true, max_attempts = 3, delay_in_seconds = 90 }. With one attempt, a lost runner request strands the job in the queue.
scale_up_reserved_concurrent_executions = 10. The default of 1 starts machines one batch at a time: a 45-job burst peaked at 28 runners and waited up to 14 minutes with quota to spare. Check the account's Lambda concurrency first (aws lambda get-account-settings).
runners_maximum_count near the measured peak. The quota increase does nothing if this cap is lower.
instance_target_capacity_type = "spot" with enable_runner_on_demand_failover_for_errors = ["InsufficientInstanceCapacity", "MaxSpotInstanceCountExceeded", "UnfulfillableCapacity"], price-capacity-optimized, and eight instance families of the same size (c7i, c7a, m7i, m7a, c6i, c6a, m6i, m6a.2xlarge). Spot and on-demand quotas are separate, so this roughly doubles capacity.
runner_run_as = "root" when moving from CodeBuild: CodeBuild runs jobs as root and some scripts and tests assume it (one test passed only as root). Each machine is single-use, so this is the same exposure.
enable_cloudwatch_agent = false unless the image installs the agent: the start script fails with amazon-cloudwatch-agent-ctl: command not found and every runner dies after registering.
enable_organization_runners = true with runner_group_name set to an org runner group whose access is limited to the one repository (create it with gh api -X POST orgs/<org>/actions/runner-groups -f name=<group> -f visibility=selected -F "selected_repository_ids[]=<repo id>"). In the Default group, another repository's job with the same label can land on these runners. repository_white_list limits the webhook to the repository.
Public subnets of the account's default VPC with associate_public_ipv4_address = true and no inbound rule: no NAT gateway to pay for.
Lambda zips: fetch them for the pinned release and verify each with gh attestation verify (fetch_upstream.sh reads the version from main.tf), because Terraform needs them at plan time.
The org GitHub App is created by an org owner in a browser. The manifest flow makes it one click: a local page POSTs a manifest (permissions: Actions, Checks and Metadata read on the repo; organization self-hosted runners read and write; event workflow_job) to https://github.com/organizations/<org>/settings/apps/new, GitHub redirects to a localhost callback with a code, and POST /app-manifests/<code>/conversions returns the App id, private key and webhook secret. Store the key (base64) and the secret as SSM SecureString parameters and read them in Terraform with data sources; they never go in variables or tfvars. The module's webhook-github-app submodule sets the App's webhook URL after apply. Then the owner installs the App on the one repository.
Each runner's IAM role can read only the SSM token tagged with its own instance id (an ec2:SourceInstanceARN condition) and the module's config path, so one job cannot take another job's runner. Confirm this in the module release you pin.
Step 5: the image
Bake an image with Packer (runner-image.pkr.hcl): the matching Ubuntu base (24.04 for ubuntu-24.04 parity), Docker Engine with the buildx and compose plugins, build tools, the AWS CLI (the start script needs it), and the GitHub runner at a pinned version, plus the module's own install and start scripts (vendored from the pinned release). Without a baked image every job pays three minutes of package installs before it starts; with it, a job starts 35 to 60 seconds after it is queued.
Do not run cloud-init clean at the end of the build: it deletes /var/lib/cloud, the per-boot runner start script with it, and every runner boots idle.
Diff the tools against the pool you leave. Follow every script the routed workflows execute (scripts calling scripts) and list the commands they use. Gaps found moving from CodeBuild: gh (deployed-build checks call gh api) and ruby (a Helm post-render filter). Most other hits are English words or comments; check each.
Terraform pins the image id into the launch template at apply, so after a rebuild re-apply, then deregister old images and delete their snapshots.
Step 6: small and large machines
Light jobs (guards, lint-only jobs, short scripts) rarely need 8 vCPU. Enable the module's dynamic labels (enable_dynamic_labels = true) with an aws_dynamic_labels_policy that allows only a few small types, and have those jobs add ghr-ec2-instance-type:c7i.large (2 vCPU) or c7i.xlarge (4 vCPU) beside the main label:
runs-on: ${{ vars.PR_RUNNER_LABEL != '' && fromJSON(format('["{0}","ghr-ec2-instance-type:c7i.large"]', vars.PR_RUNNER_LABEL)) || <the existing expression> }}
Shrink only after a benchmark: a browser test timed out on 4 vCPU and went back to 8. The feature is marked experimental in the module; if a release drops it, those jobs fall back to the default size.
Step 7: routing and the switch
Prepend one arm to the shared runs-on expression of the pools you are moving, and leave release and deploy pools alone:
runs-on: ${{ vars.PR_RUNNER_LABEL != '' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && vars.PR_RUNNER_LABEL || <the existing expression> }}
Keep the fork check: fork PRs must never reach self-hosted runners.
Name the variable without a reserved prefix (CI_, GITHUB_, RUNNER_, ACTIONS_): release jobs that export every repository variable into a deploy environment refuse those names.
It moves every event of those pools (pull requests, pushes to main, schedules). Say so in the docs.
Unset, nothing changes; that is what makes the merge safe.
Add ci-runner-reclaim-retry.yml (in this gist): on workflow_run completed with failure, first attempt only, if any failed job's annotation says "The self-hosted runner lost communication with the server" (a spot reclaim), call POST /actions/runs/<id>/rerun-failed-jobs once.
Step 8: benchmark before cutover
On a branch that is never merged, add a push-triggered workflow that copies the heaviest jobs from the real workflows at that commit and runs each three times per runner label. Compare medians to the old pool's recent builds. Then:
a burst probe: 45 parallel trivial 8 vCPU jobs (a sleep) to check scale-up speed, peak concurrency and the spot-to-on-demand failover (read the instance lifecycle from instance metadata);
a dynamic-label probe (a job that prints nproc and the instance type);
for any job that fails only on the new runners, reproduce it as the runner user and as root (sudo -E env "PATH=$PATH" ...) before guessing.
Expect real test flakes that also fail on the old pool; check the old pool's history before blaming the runners. One example: a ClickHouse container capped at 1 GB answered 500 on large inserts under Ubuntu 24.04's cgroup v2 and needed 2 GB everywhere.
Step 9: cutover, monitoring, rollback
Merge the routing change with the variable unset.
gh variable set PR_RUNNER_LABEL --repo <repo> --body <label> and record the time.
Watch every five minutes for the first hours: jobs done, running and queued on the label; wait from queued to started (p50, p90, max); failures, split into runner-caused (the "lost communication" annotation, command not found, permission errors) and the change's own; instance count against quota. A monitor can be a short script that polls gh api .../actions/runs and aws ec2 describe-instances.
Roll back if jobs routinely wait more than about five minutes or anything fails because of the runners: gh variable delete PR_RUNNER_LABEL --repo <repo>. New jobs go back at once; jobs already queued on the label still run there.
The first real cutover was rolled back after 29 minutes: a burst of PRs waited up to 17 minutes because scale-up was serial and the on-demand quota was shared. Fixing scale-up concurrency and adding spot first fixed it.
Report back
Measured minutes, peak concurrency, and the estimate per option (on-demand and spot), with the price sources and dates.
Quota requests and their status, and the credit balance if the requester read it.
Benchmark medians against the old pool, burst probe results, and every runner-caused failure with its fix.
The rollback command, where the docs live, and what the team now owns (image rebuilds, module upgrades, quota).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters