Projects & Stories

Gitlab runner clean-up caches

If you are using the gitlab runner on your system you probably already saw the pile of cache containers he leaves after running pipelines.

Thats nessecary cause .. well its a cache and could be reused. But I think after a certain amount of time its ok to clean-up the mess.

If you search for it you probably end up with the gitlab-runner-docker-cleanup repository. It will clean-up cache containers after a certain threshold is reached.

Since the gitlab runner is not the only system allocating storage on my harddrive I was more interested in a time related solution.

So what about good old cron?

Well if you checkout the gitlab-runner-docker-cleanup source code you'll find the heart of it somewhere around line 250:

func isCacheContainer(names ...string) bool {
	for _, name := range names {
		if strings.Contains(name, "runner-") &&
			strings.Contains(name, "-project-") &&
			strings.Contains(name, "-concurrent-") &&
			strings.Contains(name, "-cache-") {
			return true
		}
	}
	return false
}

That can be easily translated to shell and put into a cronjob:

docker rm $(docker ps -q -a --filter exited=0 --filter name=runner-.*-project-.*-concurrent-.*-cache-.*$)

All it does is to search for containers with the regular expression runner-.*-project-.*-concurrent-.*-cache-.*$ and if the container has a exit code of zero.

Putting that into cron could look like this crontab -l:

# m h  dom mon dow   command

0 5 * * * docker rm $(docker ps -q -a --filter exited=0 --filter name=runner-.*-project-.*-concurrent-.*-cache-.*$)

That one will run every day at 5am.

// Lukas