···
1
-
{ config, pkgs, lib, ... }:
cfg = config.services.github-runner;
5
-
svcName = "github-runner";
6
-
systemdDir = "${svcName}/${cfg.name}";
7
-
# %t: Runtime directory root (usually /run); see systemd.unit(5)
8
-
runtimeDir = "%t/${systemdDir}";
9
-
# %S: State directory root (usually /var/lib); see systemd.unit(5)
10
-
stateDir = "%S/${systemdDir}";
11
-
# %L: Log directory root (usually /var/log); see systemd.unit(5)
12
-
logsDir = "%L/${systemdDir}";
13
-
# Name of file stored in service state directory
14
-
currentConfigTokenFilename = ".current-token";
17
-
options.services.github-runner = {
21
-
description = lib.mdDoc ''
22
-
Whether to enable GitHub Actions runner.
24
-
Note: GitHub recommends using self-hosted runners with private repositories only. Learn more here:
25
-
[About self-hosted runners](https://docs.github.com/en/actions/hosting-your-own-runners/about-self-hosted-runners).
27
-
type = lib.types.bool;
32
-
description = lib.mdDoc ''
33
-
Repository to add the runner to.
35
-
Changing this option triggers a new runner registration.
37
-
IMPORTANT: If your token is org-wide (not per repository), you need to
38
-
provide a github org link, not a single repository, so do it like this
39
-
`https://github.com/nixos`, not like this
40
-
`https://github.com/nixos/nixpkgs`.
41
-
Otherwise, you are going to get a `404 NotFound`
42
-
from `POST https://api.github.com/actions/runner-registration`
43
-
in the configure script.
45
-
example = "https://github.com/nixos/nixpkgs";
48
-
tokenFile = mkOption {
50
-
description = lib.mdDoc ''
51
-
The full path to a file which contains either a runner registration token or a
52
-
personal access token (PAT).
53
-
The file should contain exactly one line with the token without any newline.
54
-
If a registration token is given, it can be used to re-register a runner of the same
55
-
name but is time-limited. If the file contains a PAT, the service creates a new
56
-
registration token on startup as needed. Make sure the PAT has a scope of
57
-
`admin:org` for organization-wide registrations or a scope of
58
-
`repo` for a single repository.
60
-
Changing this option or the file's content triggers a new runner registration.
62
-
example = "/run/secrets/github-runner/nixos.token";
66
-
# Same pattern as for `networking.hostName`
67
-
type = types.strMatching "^$|^[[:alnum:]]([[:alnum:]_-]{0,61}[[:alnum:]])?$";
68
-
description = lib.mdDoc ''
69
-
Name of the runner to configure. Defaults to the hostname.
71
-
Changing this option triggers a new runner registration.
74
-
default = config.networking.hostName;
75
-
defaultText = literalExpression "config.networking.hostName";
78
-
runnerGroup = mkOption {
79
-
type = types.nullOr types.str;
80
-
description = lib.mdDoc ''
81
-
Name of the runner group to add this runner to (defaults to the default runner group).
83
-
Changing this option triggers a new runner registration.
88
-
extraLabels = mkOption {
89
-
type = types.listOf types.str;
90
-
description = lib.mdDoc ''
91
-
Extra labels in addition to the default (`["self-hosted", "Linux", "X64"]`).
93
-
Changing this option triggers a new runner registration.
95
-
example = literalExpression ''[ "nixos" ]'';
99
-
replace = mkOption {
101
-
description = lib.mdDoc ''
102
-
Replace any existing runner with the same name.
104
-
Without this flag, registering a new runner with the same name fails.
109
-
extraPackages = mkOption {
110
-
type = types.listOf types.package;
111
-
description = lib.mdDoc ''
112
-
Extra packages to add to `PATH` of the service to make them available to workflows.
117
-
package = mkOption {
118
-
type = types.package;
119
-
description = lib.mdDoc ''
120
-
Which github-runner derivation to use.
122
-
default = pkgs.github-runner;
123
-
defaultText = literalExpression "pkgs.github-runner";
126
-
ephemeral = mkOption {
128
-
description = lib.mdDoc ''
129
-
If enabled, causes the following behavior:
131
-
- Passes the `--ephemeral` flag to the runner configuration script
132
-
- De-registers and stops the runner with GitHub after it has processed one job
133
-
- On stop, systemd wipes the runtime directory (this always happens, even without using the ephemeral option)
134
-
- Restarts the service after its successful exit
135
-
- On start, wipes the state directory and configures a new runner
137
-
You should only enable this option if `tokenFile` points to a file which contains a
138
-
personal access token (PAT). If you're using the option with a registration token, restarting the
139
-
service will fail as soon as the registration token expired.
14
+
options.services.github-runner = import ./github-runner/options.nix (args // {
15
+
# Users don't need to specify options.services.github-runner.name; it will default
17
+
includeNameDefault = true;
config = mkIf cfg.enable {
146
-
warnings = optionals (isStorePath cfg.tokenFile) [
148
-
`services.github-runner.tokenFile` points to the Nix store and, therefore, is world-readable.
149
-
Consider using a path outside of the Nix store to keep the token private.
153
-
systemd.services.${svcName} = {
154
-
description = "GitHub Actions runner";
156
-
wantedBy = [ "multi-user.target" ];
157
-
wants = [ "network-online.target" ];
158
-
after = [ "network.target" "network-online.target" ];
162
-
RUNNER_ROOT = stateDir;
165
-
path = (with pkgs; [
173
-
] ++ cfg.extraPackages;
175
-
serviceConfig = rec {
176
-
ExecStart = "${cfg.package}/bin/Runner.Listener run --startuptype service";
178
-
# Does the following, sequentially:
179
-
# - If the module configuration or the token has changed, purge the state directory,
180
-
# and create the current and the new token file with the contents of the configured
181
-
# token. While both files have the same content, only the later is accessible by
182
-
# the service user.
183
-
# - Configure the runner using the new token file. When finished, delete it.
184
-
# - Set up the directory structure by creating the necessary symlinks.
187
-
# Wrapper script which expects the full path of the state, runtime and logs
188
-
# directory as arguments. Overrides the respective systemd variables to provide
189
-
# unambiguous directory names. This becomes relevant, for example, if the
190
-
# caller overrides any of the StateDirectory=, RuntimeDirectory= or LogDirectory=
191
-
# to contain more than one directory. This causes systemd to set the respective
192
-
# environment variables with the path of all of the given directories, separated
194
-
writeScript = name: lines: pkgs.writeShellScript "${svcName}-${name}.sh" ''
197
-
STATE_DIRECTORY="$1"
198
-
RUNTIME_DIRECTORY="$2"
199
-
LOGS_DIRECTORY="$3"
203
-
runnerRegistrationConfig = getAttrs [ "name" "tokenFile" "url" "runnerGroup" "extraLabels" "ephemeral" ] cfg;
204
-
newConfigPath = builtins.toFile "${svcName}-config.json" (builtins.toJSON runnerRegistrationConfig);
205
-
currentConfigPath = "$STATE_DIRECTORY/.nixos-current-config.json";
206
-
newConfigTokenPath= "$STATE_DIRECTORY/.new-token";
207
-
currentConfigTokenPath = "$STATE_DIRECTORY/${currentConfigTokenFilename}";
209
-
runnerCredFiles = [
211
-
".credentials_rsaparams"
214
-
unconfigureRunner = writeScript "unconfigure" ''
216
-
# Copy the configured token file to the state dir and allow the service user to read the file
217
-
install --mode=666 ${escapeShellArg cfg.tokenFile} "${newConfigTokenPath}"
218
-
# Also copy current file to allow for a diff on the next start
219
-
install --mode=600 ${escapeShellArg cfg.tokenFile} "${currentConfigTokenPath}"
223
-
find "$STATE_DIRECTORY/" -mindepth 1 -delete
230
-
# Check for module config changes
231
-
[[ -f "${currentConfigPath}" ]] \
232
-
&& ${pkgs.diffutils}/bin/diff -q '${newConfigPath}' "${currentConfigPath}" >/dev/null 2>&1 \
235
-
# Also check the content of the token file
236
-
[[ -f "${currentConfigTokenPath}" ]] \
237
-
&& ${pkgs.diffutils}/bin/diff -q "${currentConfigTokenPath}" ${escapeShellArg cfg.tokenFile} >/dev/null 2>&1 \
240
-
# If the config has changed, remove old state and copy tokens
241
-
if [[ "$changed" -eq 1 ]]; then
242
-
echo "Config has changed, removing old runner state."
243
-
echo "The old runner will still appear in the GitHub Actions UI." \
244
-
"You have to remove it manually."
249
-
if [[ "${optionalString cfg.ephemeral "1"}" ]]; then
250
-
# In ephemeral mode, we always want to start with a clean state
252
-
elif [[ "$(ls -A "$STATE_DIRECTORY")" ]]; then
253
-
# There are state files from a previous run; diff them to decide if we need a new registration
256
-
# The state directory is entirely empty which indicates a first start
260
-
configureRunner = writeScript "configure" ''
261
-
if [[ -e "${newConfigTokenPath}" ]]; then
262
-
echo "Configuring GitHub Actions Runner"
267
-
--work "$RUNTIME_DIRECTORY"
268
-
--url ${escapeShellArg cfg.url}
269
-
--labels ${escapeShellArg (concatStringsSep "," cfg.extraLabels)}
270
-
--name ${escapeShellArg cfg.name}
271
-
${optionalString cfg.replace "--replace"}
272
-
${optionalString (cfg.runnerGroup != null) "--runnergroup ${escapeShellArg cfg.runnerGroup}"}
273
-
${optionalString cfg.ephemeral "--ephemeral"}
276
-
# If the token file contains a PAT (i.e., it starts with "ghp_"), we have to use the --pat option,
277
-
# if it is not a PAT, we assume it contains a registration token and use the --token option
278
-
token=$(<"${newConfigTokenPath}")
279
-
if [[ "$token" =~ ^ghp_* ]]; then
280
-
args+=(--pat "$token")
282
-
args+=(--token "$token")
285
-
${cfg.package}/bin/config.sh "''${args[@]}"
287
-
# Move the automatically created _diag dir to the logs dir
288
-
mkdir -p "$STATE_DIRECTORY/_diag"
289
-
cp -r "$STATE_DIRECTORY/_diag/." "$LOGS_DIRECTORY/"
290
-
rm -rf "$STATE_DIRECTORY/_diag/"
292
-
# Cleanup token from config
293
-
rm "${newConfigTokenPath}"
295
-
# Symlink to new config
296
-
ln -s '${newConfigPath}' "${currentConfigPath}"
299
-
setupRuntimeDir = writeScript "setup-runtime-dirs" ''
301
-
ln -s "$LOGS_DIRECTORY" "$RUNTIME_DIRECTORY/_diag"
303
-
# Link the runner credentials to the runtime dir
304
-
ln -s "$STATE_DIRECTORY"/{${lib.concatStringsSep "," runnerCredFiles}} "$RUNTIME_DIRECTORY/"
307
-
map (x: "${x} ${escapeShellArgs [ stateDir runtimeDir logsDir ]}") [
308
-
"+${unconfigureRunner}" # runs as root
313
-
# If running in ephemeral mode, restart the service on-exit (i.e., successful de-registration of the runner)
314
-
# to trigger a fresh registration.
315
-
Restart = if cfg.ephemeral then "on-success" else "no";
318
-
LogsDirectory = [ systemdDir ];
319
-
# Default RUNNER_ROOT which contains ephemeral Runner data
320
-
RuntimeDirectory = [ systemdDir ];
321
-
# Home of persistent runner data, e.g., credentials
322
-
StateDirectory = [ systemdDir ];
323
-
StateDirectoryMode = "0700";
324
-
WorkingDirectory = runtimeDir;
326
-
InaccessiblePaths = [
327
-
# Token file path given in the configuration, if visible to the service
328
-
"-${cfg.tokenFile}"
329
-
# Token file in the state directory
330
-
"${stateDir}/${currentConfigTokenFilename}"
333
-
# By default, use a dynamically allocated user
334
-
DynamicUser = true;
336
-
KillSignal = "SIGINT";
338
-
# Hardening (may overlap with DynamicUser=)
339
-
# The following options are only for optimizing:
340
-
# systemd-analyze security github-runner
341
-
AmbientCapabilities = "";
342
-
CapabilityBoundingSet = "";
343
-
# ProtectClock= adds DeviceAllow=char-rtc r
345
-
NoNewPrivileges = true;
346
-
PrivateDevices = true;
347
-
PrivateMounts = true;
349
-
PrivateUsers = true;
350
-
ProtectClock = true;
351
-
ProtectControlGroups = true;
352
-
ProtectHome = true;
353
-
ProtectHostname = true;
354
-
ProtectKernelLogs = true;
355
-
ProtectKernelModules = true;
356
-
ProtectKernelTunables = true;
357
-
ProtectSystem = "strict";
359
-
RestrictNamespaces = true;
360
-
RestrictRealtime = true;
361
-
RestrictSUIDSGID = true;
363
-
ProtectProc = "invisible";
364
-
SystemCallFilter = [
376
-
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" "AF_NETLINK" ];
378
-
# Needs network access
379
-
PrivateNetwork = false;
380
-
# Cannot be true due to Node
381
-
MemoryDenyWriteExecute = false;
383
-
# The more restrictive "pid" option makes `nix` commands in CI emit
384
-
# "GC Warning: Couldn't read /proc/stat"
385
-
# You may want to set this to "pid" if not using `nix` commands
386
-
ProcSubset = "all";
387
-
# Coverage programs for compiled code such as `cargo-tarpaulin` disable
388
-
# ASLR (address space layout randomization) which requires the
389
-
# `personality` syscall
390
-
# You may want to set this to `true` if not using coverage tooling on
392
-
LockPersonality = false;
21
+
services.github-runners.${cfg.name} = cfg;