Setting the Stage: A Minimal Deploy Pipeline
Before we argue why this pattern should be avoided, let’s build a minimal
pipeline that uses a self‑hosted runner on a Linux Ubuntu spot instance.
The goal is to fetch code from a private GitHub repository, build a Docker
image, push it to a container registry, and then SSH into a remote host to
trigger a docker‑compose up -d rollout. All of this can be
expressed in a single .github/workflows/deploy.yml file.
# .github/workflows/deploy.yml
name: Spot‑Runner Deploy
on:
push:
branches: [ main ]
jobs:
build-and-deploy:
runs-on: self-hosted
steps:
- name: Checkout source
uses: actions/checkout@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to Container Registry
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USER }}
password: ${{ secrets.GHCR_TOKEN }}
- name: Build and push image
uses: docker/build-push-action@v4
with:
context: .
push: true
tags: ghcr.io/${{ github.repository_owner }}/app:${{ github.sha }}
- name: Deploy via SSH
uses: appleboy/[email protected]
with:
host: ${{ secrets.PROD_HOST }}
username: ${{ secrets.PROD_USER }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
docker pull ghcr.io/${{ github.repository_owner }}/app:${{ github.sha }}
docker-compose -f /opt/app/docker-compose.yml up -d
The workflow itself is perfectly valid. It relies on three secret values: a container‑registry token, SSH credentials, and the production host address. The runner itself is a small Ubuntu 22.04 VM launched from a spot market on AWS EC2, GCP Preemptible VMs, or Azure Low‑Priority VMs.
Automating the Spot Instance Lifecycle
To keep costs low, many teams spin up a spot instance on demand, register it as a self‑hosted runner, and destroy it after the job finishes. Below is a Bash script that a CI/CD orchestrator (or a simple cron) can execute to provision the runner, attach it to the repository, and clean up.
# provision_spot_runner.sh
#!/usr/bin/env bash
set -euo pipefail
# 1️⃣ Choose the cloud provider – example uses AWS CLI
REGION="us-east-1"
INSTANCE_TYPE="t3.micro"
AMI_ID="ami-0c02fb55956c7d316" # Ubuntu 22.04 LTS
KEY_NAME="github-runner-key"
SECURITY_GROUP="sg-0123456789abcdef0"
# 2️⃣ Request a spot instance
INSTANCE_ID=$(aws ec2 request-spot-instances \
--instance-count 1 \
--type "one-time" \
--launch-specification "{
\"ImageId\":\"${AMI_ID}\",
\"InstanceType\":\"${INSTANCE_TYPE}\",
\"KeyName\":\"${KEY_NAME}\",
\"SecurityGroupIds\":[\"${SECURITY_GROUP}\"],
\"SubnetId\":\"subnet-0abcd1234ef567890\"
}" \
--query "SpotInstanceRequests[0].InstanceId" \
--output text)
echo "Spot request submitted, instance ID: ${INSTANCE_ID}"
# 3️⃣ Wait for the instance to be ready
aws ec2 wait instance-running --instance-ids "${INSTANCE_ID}"
PUBLIC_IP=$(aws ec2 describe-instances \
--instance-ids "${INSTANCE_ID}" \
--query "Reservations[0].Instances[0].PublicIpAddress" \
--output text)
echo "Instance is up at ${PUBLIC_IP}"
# 4️⃣ Install the GitHub runner binary
ssh -o StrictHostKeyChecking=no -i ~/.ssh/${KEY_NAME}.pem ubuntu@${PUBLIC_IP} <<'EOF'
sudo apt-get update && sudo apt-get install -y curl jq
RUNNER_VERSION=$(curl -s https://api.github.com/repos/actions/runner/releases/latest | jq -r .tag_name)
curl -O -L https://github.com/actions/runner/releases/download/${RUNNER_VERSION}/actions-runner-linux-x64-${RUNNER_VERSION:1}.tar.gz
tar xzf actions-runner-linux-x64-${RUNNER_VERSION:1}.tar.gz
./config.sh --url https://github.com/${GITHUB_REPOSITORY} --token ${RUNNER_TOKEN} --labels spot,ubuntu
sudo ./svc.sh install
sudo ./svc.sh start
EOF
# 5️⃣ Store the instance ID for later termination
echo "${INSTANCE_ID}" > /tmp/spot_instance_id
The script demonstrates the mechanics that many “cost‑saving” guides celebrate. However, the hidden side‑effects surface as soon as the spot market decides to reclaim the VM.
The Hidden Internals: Spot Preemption and Its Ripple Effect
Spot instances can be terminated with as little as a two‑minute warning. For a self‑hosted runner this means the following sequence:
- The cloud provider sends a termination notice (often via metadata URL).
- The runner process receives a SIGTERM, attempts a graceful shutdown, but GitHub’s runner daemon does not retry the job.
- The in‑flight deployment step is aborted, leaving the target host
partially updated (e.g., a new image pulled but
docker‑composenever completed). - Because the runner disappears, GitHub marks the job as “cancelled” rather than “failed”, which can hide the problem from dashboards.
The result is a deployment that appears successful in CI logs but is broken in production. Detecting this requires extra instrumentation, such as a health‑check webhook that verifies the service post‑deploy. Adding that check defeats the original “light‑weight” premise.
# health_check.sh – run on the target host after deployment
#!/usr/bin/env bash
set -euo pipefail
URL="http://localhost:8080/health"
EXPECTED="OK"
if curl -sSf "${URL}" | grep -q "${EXPECTED}"; then
echo "Health check passed."
exit 0
else
echo "Health check failed!" >&2
exit 1
fi
Embedding the health check into the workflow forces a second SSH call, increasing the window of failure. Moreover, if the spot instance is terminated between the Docker pull and the health‑check invocation, the job never reaches the verification step, and the failure goes unnoticed.
Why the Pattern Is a Liability for Production
The temptation to “save a few dollars per month” masks several deeper concerns:
- Non‑deterministic availability: Spot capacity fluctuates based on unrelated market demand; a critical release may be delayed indefinitely during a regional shortage.
- Loss of auditability: Because the runner disappears, logs stored only on the VM are lost unless you forward them to an external system in real time.
- Stateful operations break: Any job that writes temporary files, caches layers, or performs multi‑step rollouts assumes the runner persists across steps. Spot termination invalidates those assumptions.
- Compliance risk: Many regulated environments (e.g., PCI‑DSS, HIPAA) require documented, immutable build environments. A transient VM does not satisfy that requirement without additional, costly controls.
For non‑critical, experimental workloads (e.g., nightly builds, PR preview environments) spot‑based runners are acceptable. Production deployments, however, demand a stable, auditable compute surface—typically a dedicated on‑demand instance or a managed CI service with guaranteed SLA.
Alternative: Managed Runners or Reserved Instances
Switching to GitHub’s hosted runners eliminates the need to manage the VM lifecycle entirely, at the cost of higher per‑minute pricing. For teams that need full control, provisioning a small reserved instance (e.g., a t3.small on AWS) and installing the runner once provides the same isolation without preemption risk.
# Example systemd unit for a permanent self‑hosted runner
[Unit]
Description=GitHub Actions Runner
After=network.target
[Service]
User=github-runner
WorkingDirectory=/opt/github-runner
ExecStart=/opt/github-runner/run.sh
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
The unit keeps the runner alive across reboots, and you can pair it with CloudWatch or Stackdriver monitoring to capture logs centrally. This approach removes the “spot surprise” while preserving the self‑hosted flexibility that some organizations require.
Security and Best Practices
Whether you stay with spot instances for low‑risk jobs or move to a permanent host, follow these practices:
- Store all secrets in GitHub Encrypted Secrets; never embed them in the runner image.
- Enable
actions/runnerversion pinning to avoid accidental upgrades that could introduce regressions. - Forward logs to a central logging
♥ Enjoyed this article? Use the like banner at the top of the page to let us know — you can like it more than once! Each additional like from the same reader carries a little less weight than the first, so our appreciation scores reflect genuine enthusiasm rather than accidental clicks. Your feedback helps us understand which topics resonate most.