Subscribe

Installing and registering a GitLab Runner on EC2 with the Docker executor

Run shorty's GitLab CI jobs on your own EC2 instance: create the runner in the UI, keep the glrt- token in SSM Parameter Store, install GitLab Runner 19.5 and Docker with Terraform user data, and read config.toml line by line.

Installing and registering a GitLab Runner on EC2 with the Docker executor

In the GitLab CI from zero post shorty's pipeline ran on gitlab.com's hosted runners. That's fine to start. But sooner or later you want your own: jobs that need to reach something inside your VPC, a bigger machine for the Go builds, or just not paying per minute.

In this blog we will put a GitLab Runner on one EC2 instance with the Docker executor, register it with the new runner authentication token (the one that starts with glrt-) and go through config.toml. Level is beginner, but you should be okay with basic Terraform (your first EC2 instance with Terraform covers it) and have a GitLab project with the .gitlab-ci.yml from the last post.

Versions: GitLab Runner 19.5.3, Amazon Linux 2023, Terraform 1.17.1 with the AWS provider 6.x. Account ID and names are placeholders.

Registration tokens are on their way out

Older guides tell you to copy a "registration token" from the Runners page and run gitlab-runner register with it. Don't. That flow was deprecated back in GitLab 15.6. Since GitLab 17.0 an admin or a top level group owner can switch it off, and when it is off register fails with 410 Gone - runner registration disallowed. The removal date has moved more than once (18.0 was the plan at one point, then it got pushed out), and the current docs do not promise a version. I wouldn't build anything new on it.

Basically the new flow is the other way round. You create the runner in the GitLab UI first, with its tags and settings, and GitLab hands you a runner authentication token. The machine then registers with that token.

Create the runner in GitLab

In the project, go to Settings > CI/CD, expand Runners and select Create project runner. Fill in:

  • Tags: shorty, docker
  • Leave "Run untagged jobs" off. I want jobs to ask for this runner on purpose.
  • A description, I used shorty-ec2-docker.

GitLab shows the token once. It starts with glrt-. Copy it.

Tags now lives on the server. That surprised me a bit when I tried it. I passed --tag-list to register like in the old days, and the runner refused straight away:

FATAL: Runner configuration other than name and executor configuration is reserved
(specifically --locked, --access-level, --run-untagged, --maximum-timeout, --paused,
--tag-list, and --maintenance-note) and cannot be specified when registering with a
runner authentication token. This configuration is specified on the GitLab server.

So tags, locked, run-untagged and timeout are set in the UI only. Name, executor and the executor's own settings are still yours.

Keep the token in SSM Parameter Store

See, the token is a credential. Anyone with it can pull jobs from your project, and with them the CI/CD variables. I don't want it in Terraform code, in Terraform state or in plain user data (anyone with ec2:DescribeInstanceAttribute can read user data). So it goes into Parameter Store as a SecureString, by hand, once:

aws ssm put-parameter \
  --name /gitlab-runner/shorty/token \
  --type SecureString \
  --value 'glrt-PASTE_YOUR_TOKEN'

The instance reads it at boot with its own role. This is the same pattern I use for the blog's own box, which I run with SSM instead of SSH.

The instance with Terraform

The full code is a bit long, so here are the parts that matter. The security group has no ingress at all. The runner only makes outgoing HTTPS calls to GitLab and polls for jobs, nothing connects to it.

resource "aws_security_group" "runner" {
  name        = "gitlab-runner-shorty"
  description = "GitLab runner, egress only"
  vpc_id      = data.aws_subnet.this.vpc_id

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

The role gets AmazonSSMManagedInstanceCore so I can open a shell with Session Manager, plus read access to exactly one parameter:

data "aws_iam_policy_document" "read_token" {
  statement {
    actions   = ["ssm:GetParameter"]
    resources = ["arn:aws:ssm:${var.region}:${data.aws_caller_identity.current.account_id}:parameter${var.token_parameter}"]
  }
}

The default aws/ssm key is used for SecureString here, so no extra KMS permission is needed. If you use your own KMS key, add kms:Decrypt on it.

And the instance itself:

resource "aws_instance" "runner" {
  ami                    = data.aws_ssm_parameter.al2023.value
  instance_type          = var.instance_type # t3.medium
  subnet_id              = var.subnet_id
  vpc_security_group_ids = [aws_security_group.runner.id]
  iam_instance_profile   = aws_iam_instance_profile.runner.name

  user_data = templatefile("${path.module}/user_data.sh.tftpl", {
    region          = var.region
    token_parameter = var.token_parameter
  })
  user_data_replace_on_change = true

  metadata_options {
    http_tokens = "required"
  }

  root_block_device {
    volume_size = 40
    volume_type = "gp3"
    encrypted   = true
  }

  lifecycle {
    ignore_changes = [ami]
  }
}

I went with t3.medium and 40 GB. My own blog runs on a 2 GB t3.small, but a Go build with -race plus a Postgres service container wants more memory than that, and Docker images eat disk fast. ignore_changes = [ami] stops Terraform from replacing the runner every time Amazon publishes a new AL2023 image.

terraform validate passed on this with Terraform 1.17.1. The subnet needs a way out to the internet (public IP or a NAT), else the runner can't reach gitlab.com.

Installing Docker and the runner

This is the user data template:

#!/bin/bash
set -euo pipefail

# Docker from the Amazon Linux 2023 repo
dnf install -y docker
systemctl enable --now docker

# GitLab Runner from the official package repo
curl -fsSL "https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.rpm.sh" -o /tmp/script.rpm.sh
bash /tmp/script.rpm.sh
dnf install -y gitlab-runner

# The glrt- token lives in SSM Parameter Store, never in Terraform state or user data
TOKEN=$(aws ssm get-parameter --region "${region}" --name "${token_parameter}" \
  --with-decryption --query Parameter.Value --output text)

gitlab-runner register \
  --non-interactive \
  --url "https://gitlab.com" \
  --token "$TOKEN" \
  --name "shorty-ec2-docker" \
  --executor "docker" \
  --docker-image "alpine:3.22" \
  --docker-pull-policy "if-not-present" \
  --request-concurrency 2

# A bit more than the default of 1 job at a time
sed -i 's/^concurrent = .*/concurrent = 2/' /etc/gitlab-runner/config.toml
systemctl restart gitlab-runner

${region} and ${token_parameter} are filled in by Terraform's templatefile, while $TOKEN (no braces) is left for bash. The package script is the one from GitLab's install docs; they suggest you read it before you pipe it into bash, and that's fair advice.

register does talk to GitLab, it is not just writing a file. To see what happens I ran it in the gitlab/gitlab-runner:v19.5.3 image with a fake token and a URL where nothing listens:

ERROR: Verifying runner... failed    ... couldn't execute POST against
http://127.0.0.1:9/api/v4/runners/verify: ... connect: connection refused
PANIC: Failed to verify the runner.

So if your instance has no route out, this is the line you will find in /var/log/cloud-init-output.log.

config.toml, line by line

After registration file looks like this (I added the memory and CPU limits by hand):

concurrent = 2
check_interval = 0
shutdown_timeout = 0

[session_server]
  session_timeout = 1800

[[runners]]
  name = "shorty-ec2-docker"
  url = "https://gitlab.com"
  token = "glrt-REPLACE_ME"
  executor = "docker"
  request_concurrency = 2
  output_limit = 8192
  [runners.cache]
    MaxUploadedArchiveSize = 0
  [runners.docker]
    image = "alpine:3.22"
    pull_policy = ["if-not-present"]
    privileged = false
    disable_cache = false
    volumes = ["/cache"]
    memory = "3g"
    cpus = "2"
    shm_size = 0
  • concurrent is global: how many jobs this machine runs at once, over all [[runners]] entries.
  • request_concurrency is how many "give me a job" requests one runner keeps open at a time. The default is 1.
  • image is only used when a job doesn't say image:. shorty's jobs all do.
  • privileged = false. Keep it that way unless you really need Docker in Docker.
  • volumes = ["/cache"] is where the local cache lives on this machine.
  • memory and cpus stop one runaway test from starving the other job.

About request_concurrency: I only added it because the runner told me to. When I started 19.5.3 with a config that didn't have it, the log said "Long polling issues detected" and "Request bottleneck: 1 runners have request_concurrency=1, causing job delays during long polling". With 2 the warning went away. A small thing, but it was actually new to me.

I checked that the runner parses this file with gitlab-runner list, which prints the name, executor and URL. One catch I found while doing that: a misspelled key (I tried cpu_requestz in another config) was not reported, by list or by run. The runner just ignores it. Read your keys twice.

Point the jobs at the runner

Since the runner doesn't take untagged jobs, add the tag in .gitlab-ci.yml:

default:
  tags:
    - shorty

Push, and the jobs page shows shorty-ec2-docker as the runner. In the project's Runners page the runner should have a green dot. If it doesn't, open a session with aws ssm start-session --target <instance-id> and run:

sudo gitlab-runner status
sudo gitlab-runner list
sudo journalctl -u gitlab-runner --since "15 min ago"

Disk fills up

Every job pulls images and leaves containers and volumes behind for the cache. On a busy runner that 40 GB goes faster than you think. The package ships a cleanup script, /usr/share/gitlab-runner/clear-docker-cache. I read it in the 19.5.3 image: by default it runs prune-volumes, which removes unused containers, images and volumes, and only the ones carrying the com.gitlab.gitlab-runner.managed=true label, so your other Docker things are left alone.

sudo /usr/share/gitlab-runner/clear-docker-cache space          # how much is used
sudo /usr/share/gitlab-runner/clear-docker-cache prune-volumes  # clean up

Run it from a systemd timer once a week. The volumes hold the local cache, so the first pipeline after a clean up is slower.

What I could not test

I did not start this instance on a real AWS account for this post, and I have no GitLab instance here. What I did run: terraform fmt and terraform validate, the rendered user data through bash -n, the register and list commands in the official runner image, and the config file through gitlab-runner run pointed at a dead URL. Everything that needs a real GitLab (the green dot, a job picked up) you will see for yourself.

That's it. Once one runner works, the next question is scaling, and that's where Kubernetes or the docker-autoscaler come in.