Opening the Black Box: Spot Instances and CI/CD
Many teams chase the low‑price appeal of spot instances when they need extra compute for CI/CD pipelines. The headline price looks attractive, but the underlying mechanics of spot termination introduce a class of failures that are invisible until a build disappears mid‑run. This article explains why deploying self‑hosted GitHub Actions runners on spot VMs is a hidden liability and walks you through the internal signals that reveal the problem before it hurts production.
Understanding Spot Instance Volatility
Spot VMs are priced by excess capacity. When the provider reclaims capacity, it sends a termination notice (usually a two‑minute warning) via metadata endpoints or cloud‑specific events. Most CI/CD tools treat a runner as a permanent worker; they do not react to the short‑lived warning, causing abrupt cancellations, lost artifacts, and flaky pipelines.
# Example: Fetching termination notice on AWS EC2
#!/usr/bin/env bash
while true; do
if curl -s http://169.254.169.254/latest/meta-data/spot/termination-time; then
echo "Spot termination detected – draining runner"
# Signal GitHub to stop accepting jobs
curl -X POST -H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$GITHUB_REPO/actions/runners/$RUNNER_ID/remove
break
fi
sleep 5
done
The script above polls the EC2 metadata service for a termination timestamp. When it appears, the runner is deregistered from the repository, preventing new jobs from landing on a VM that will disappear. Unfortunately, most open‑source runner images do not include such a watcher, leaving the termination event unnoticed.
Step‑by‑Step: Building a Safer Runner with Terraform and Systemd
Instead of a blind spot deployment, we will provision a dedicated on‑demand instance for the runner and use Terraform to enforce the correct lifecycle. The tutorial also shows how to embed a termination‑watcher into a systemd service so the runner can gracefully shut down.
# terraform/main.tf – provision a regular EC2 instance for the runner
provider "aws" {
region = "us-east-2"
}
resource "aws_instance" "github_runner" {
ami = "ami-0c55b159cbfafe1f0" # Amazon Linux 2
instance_type = "t3.medium"
key_name = var.ssh_key_name
tags = {
Name = "github-selfhosted-runner"
}
# Ensure the instance is not a spot instance
instance_market_options {
market_type = "on-demand"
}
}
By explicitly setting market_type = "on-demand" we lock the instance to a stable pricing tier. This eliminates the termination notice entirely, at the cost of a higher hourly rate. The trade‑off is intentional: reliability for CI pipelines is non‑negotiable.
# /etc/systemd/system/github-runner.service
[Unit]
Description=GitHub Actions Self‑Hosted Runner
After=network.target
[Service]
Type=simple
User=ec2-user
WorkingDirectory=/home/ec2-user/actions-runner
ExecStart=/home/ec2-user/actions-runner/run.sh
ExecStop=/home/ec2-user/actions-runner/stop.sh
Restart=on-failure
Environment="RUNNER_TOKEN=${RUNNER_TOKEN}"
Environment="RUNNER_NAME=${HOSTNAME}"
Environment="GITHUB_REPO=yourorg/yourrepo"
# Optional: watch for EC2 spot termination (no‑op on on‑demand)
ExecStartPost=/usr/local/bin/spot-watcher.sh
[Install]
WantedBy=multi-user.target
The service definition includes an ExecStartPost hook that runs the watcher script from the previous section. On an on‑demand instance the script will never fire, but the same service can be reused if you later decide to test spot behavior in a controlled environment.
Hidden Internals: How GitHub Handles Runner Lifecycle
When a runner registers, GitHub stores a short‑lived authentication token in its backend. The token is refreshed every 10 minutes via a long‑polling connection. If the VM disappears without deregistering, GitHub eventually marks the runner as offline and re‑queues any in‑flight jobs. However, the original job logs are lost, and any artifacts generated before termination are never uploaded because the upload step runs after the build completes.
# Sample request to GitHub to deregister a runner (used by spot‑watcher)
curl -X DELETE \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$GITHUB_REPO/actions/runners/$RUNNER_ID
The API call above is safe to run even if the runner is already offline; GitHub will simply return a 404 Not Found. Adding this call to the watcher ensures that the runner is removed from the pool before the VM is reclaimed, reducing the chance of “orphaned” jobs.
Security and Best Practices
1. Never embed secrets in the runner image. Use AWS Parameter Store or Secrets Manager to inject RUNNER_TOKEN at launch time.
2. Limit inbound SSH. Restrict the security group to your bastion host and enable key‑based authentication only.
3. Enable IAM instance profile. Grant the instance read‑only access to the repository’s secrets via the GitHub Actions OIDC provider.
4. Monitor termination events. Even on on‑demand VMs, hardware failures can cause abrupt shutdowns. Hook a CloudWatch alarm to the InstanceState metric and trigger a Lambda that deregisters the runner automatically.
By combining these controls you create a “defense‑in‑depth” posture that prevents a single point of failure from cascading into a broken CI pipeline.
“A cheap runner is only as cheap as the downtime it causes.” – Internal DevOps Review, Q1 2026
Conclusion
Spot instances are an excellent fit for stateless, horizontally‑scalable workloads such as batch data processing or transient web servers. CI/CD runners, however, require a steady state and a clean shutdown path. The hidden internals of GitHub’s runner registration expose a fragile edge that spot termination exploits. By provisioning on‑demand instances, wiring a termination watcher, and following the security checklist above, you protect the integrity of your build pipeline without sacrificing operational insight.
The code snippets in this article can be copied directly into a repository, tweaked for your cloud provider, and used to spin up a reliable self‑hosted runner in under ten minutes. Remember: the cheapest compute is not always the smartest choice when the cost of a broken release is measured in lost revenue and developer time.