From 998083f2adb123f4bad30309f0994b9db9190b3d Mon Sep 17 00:00:00 2001 From: Tom McLaughlin Date: Mon, 12 Sep 2022 12:41:54 -0700 Subject: github-runner: configurable user, environment, service overrides + multiple runners --- nixos/modules/module-list.nix | 1 + .../continuous-integration/github-runner.nix | 392 +-------------------- .../github-runner/options.nix | 162 +++++++++ .../github-runner/service.nix | 247 +++++++++++++ .../continuous-integration/github-runners.nix | 51 +++ 5 files changed, 473 insertions(+), 380 deletions(-) create mode 100644 nixos/modules/services/continuous-integration/github-runner/options.nix create mode 100644 nixos/modules/services/continuous-integration/github-runner/service.nix create mode 100644 nixos/modules/services/continuous-integration/github-runners.nix (limited to 'nixos') diff --git a/nixos/modules/module-list.nix b/nixos/modules/module-list.nix index 494df03e3a367..8584a4eb1d23c 100644 --- a/nixos/modules/module-list.nix +++ b/nixos/modules/module-list.nix @@ -346,6 +346,7 @@ ./services/continuous-integration/hercules-ci-agent/default.nix ./services/continuous-integration/hydra/default.nix ./services/continuous-integration/github-runner.nix + ./services/continuous-integration/github-runners.nix ./services/continuous-integration/gitlab-runner.nix ./services/continuous-integration/gocd-agent/default.nix ./services/continuous-integration/gocd-server/default.nix diff --git a/nixos/modules/services/continuous-integration/github-runner.nix b/nixos/modules/services/continuous-integration/github-runner.nix index 2ece75722a1d3..1b435b019215b 100644 --- a/nixos/modules/services/continuous-integration/github-runner.nix +++ b/nixos/modules/services/continuous-integration/github-runner.nix @@ -1,396 +1,28 @@ -{ config, pkgs, lib, ... }: +{ config +, pkgs +, lib +, ... +}@args: + with lib; + let cfg = config.services.github-runner; svcName = "github-runner"; - systemdDir = "${svcName}/${cfg.name}"; - # %t: Runtime directory root (usually /run); see systemd.unit(5) - runtimeDir = "%t/${systemdDir}"; - # %S: State directory root (usually /var/lib); see systemd.unit(5) - stateDir = "%S/${systemdDir}"; - # %L: Log directory root (usually /var/log); see systemd.unit(5) - logsDir = "%L/${systemdDir}"; - # Name of file stored in service state directory - currentConfigTokenFilename = ".current-token"; -in -{ - options.services.github-runner = { - enable = mkOption { - default = false; - example = true; - description = lib.mdDoc '' - Whether to enable GitHub Actions runner. - - Note: GitHub recommends using self-hosted runners with private repositories only. Learn more here: - [About self-hosted runners](https://docs.github.com/en/actions/hosting-your-own-runners/about-self-hosted-runners). - ''; - type = lib.types.bool; - }; - - url = mkOption { - type = types.str; - description = lib.mdDoc '' - Repository to add the runner to. - - Changing this option triggers a new runner registration. - - IMPORTANT: If your token is org-wide (not per repository), you need to - provide a github org link, not a single repository, so do it like this - `https://github.com/nixos`, not like this - `https://github.com/nixos/nixpkgs`. - Otherwise, you are going to get a `404 NotFound` - from `POST https://api.github.com/actions/runner-registration` - in the configure script. - ''; - example = "https://github.com/nixos/nixpkgs"; - }; - - tokenFile = mkOption { - type = types.path; - description = lib.mdDoc '' - The full path to a file which contains either a runner registration token or a - personal access token (PAT). - The file should contain exactly one line with the token without any newline. - If a registration token is given, it can be used to re-register a runner of the same - name but is time-limited. If the file contains a PAT, the service creates a new - registration token on startup as needed. Make sure the PAT has a scope of - `admin:org` for organization-wide registrations or a scope of - `repo` for a single repository. - - Changing this option or the file's content triggers a new runner registration. - ''; - example = "/run/secrets/github-runner/nixos.token"; - }; - - name = mkOption { - # Same pattern as for `networking.hostName` - type = types.strMatching "^$|^[[:alnum:]]([[:alnum:]_-]{0,61}[[:alnum:]])?$"; - description = lib.mdDoc '' - Name of the runner to configure. Defaults to the hostname. - - Changing this option triggers a new runner registration. - ''; - example = "nixos"; - default = config.networking.hostName; - defaultText = literalExpression "config.networking.hostName"; - }; - - runnerGroup = mkOption { - type = types.nullOr types.str; - description = lib.mdDoc '' - Name of the runner group to add this runner to (defaults to the default runner group). - - Changing this option triggers a new runner registration. - ''; - default = null; - }; - extraLabels = mkOption { - type = types.listOf types.str; - description = lib.mdDoc '' - Extra labels in addition to the default (`["self-hosted", "Linux", "X64"]`). - - Changing this option triggers a new runner registration. - ''; - example = literalExpression ''[ "nixos" ]''; - default = [ ]; - }; - - replace = mkOption { - type = types.bool; - description = lib.mdDoc '' - Replace any existing runner with the same name. - - Without this flag, registering a new runner with the same name fails. - ''; - default = false; - }; - - extraPackages = mkOption { - type = types.listOf types.package; - description = lib.mdDoc '' - Extra packages to add to `PATH` of the service to make them available to workflows. - ''; - default = [ ]; - }; - - package = mkOption { - type = types.package; - description = lib.mdDoc '' - Which github-runner derivation to use. - ''; - default = pkgs.github-runner; - defaultText = literalExpression "pkgs.github-runner"; - }; - - ephemeral = mkOption { - type = types.bool; - description = lib.mdDoc '' - If enabled, causes the following behavior: - - - Passes the `--ephemeral` flag to the runner configuration script - - De-registers and stops the runner with GitHub after it has processed one job - - On stop, systemd wipes the runtime directory (this always happens, even without using the ephemeral option) - - Restarts the service after its successful exit - - On start, wipes the state directory and configures a new runner +in - You should only enable this option if `tokenFile` points to a file which contains a - personal access token (PAT). If you're using the option with a registration token, restarting the - service will fail as soon as the registration token expired. - ''; - default = false; - }; - }; +{ + options.services.github-runner = import ./github-runner/options.nix args; config = mkIf cfg.enable { warnings = optionals (isStorePath cfg.tokenFile) [ '' - `services.github-runner.tokenFile` points to the Nix store and, therefore, is world-readable. + `services.${svgName}.tokenFile` points to the Nix store and, therefore, is world-readable. Consider using a path outside of the Nix store to keep the token private. '' ]; - systemd.services.${svcName} = { - description = "GitHub Actions runner"; - - wantedBy = [ "multi-user.target" ]; - wants = [ "network-online.target" ]; - after = [ "network.target" "network-online.target" ]; - - environment = { - HOME = runtimeDir; - RUNNER_ROOT = stateDir; - }; - - path = (with pkgs; [ - bash - coreutils - git - gnutar - gzip - ]) ++ [ - config.nix.package - ] ++ cfg.extraPackages; - - serviceConfig = rec { - ExecStart = "${cfg.package}/bin/Runner.Listener run --startuptype service"; - - # Does the following, sequentially: - # - If the module configuration or the token has changed, purge the state directory, - # and create the current and the new token file with the contents of the configured - # token. While both files have the same content, only the later is accessible by - # the service user. - # - Configure the runner using the new token file. When finished, delete it. - # - Set up the directory structure by creating the necessary symlinks. - ExecStartPre = - let - # Wrapper script which expects the full path of the state, runtime and logs - # directory as arguments. Overrides the respective systemd variables to provide - # unambiguous directory names. This becomes relevant, for example, if the - # caller overrides any of the StateDirectory=, RuntimeDirectory= or LogDirectory= - # to contain more than one directory. This causes systemd to set the respective - # environment variables with the path of all of the given directories, separated - # by a colon. - writeScript = name: lines: pkgs.writeShellScript "${svcName}-${name}.sh" '' - set -euo pipefail - - STATE_DIRECTORY="$1" - RUNTIME_DIRECTORY="$2" - LOGS_DIRECTORY="$3" - - ${lines} - ''; - runnerRegistrationConfig = getAttrs [ "name" "tokenFile" "url" "runnerGroup" "extraLabels" "ephemeral" ] cfg; - newConfigPath = builtins.toFile "${svcName}-config.json" (builtins.toJSON runnerRegistrationConfig); - currentConfigPath = "$STATE_DIRECTORY/.nixos-current-config.json"; - newConfigTokenPath= "$STATE_DIRECTORY/.new-token"; - currentConfigTokenPath = "$STATE_DIRECTORY/${currentConfigTokenFilename}"; - - runnerCredFiles = [ - ".credentials" - ".credentials_rsaparams" - ".runner" - ]; - unconfigureRunner = writeScript "unconfigure" '' - copy_tokens() { - # Copy the configured token file to the state dir and allow the service user to read the file - install --mode=666 ${escapeShellArg cfg.tokenFile} "${newConfigTokenPath}" - # Also copy current file to allow for a diff on the next start - install --mode=600 ${escapeShellArg cfg.tokenFile} "${currentConfigTokenPath}" - } - - clean_state() { - find "$STATE_DIRECTORY/" -mindepth 1 -delete - copy_tokens - } - - diff_config() { - changed=0 - - # Check for module config changes - [[ -f "${currentConfigPath}" ]] \ - && ${pkgs.diffutils}/bin/diff -q '${newConfigPath}' "${currentConfigPath}" >/dev/null 2>&1 \ - || changed=1 - - # Also check the content of the token file - [[ -f "${currentConfigTokenPath}" ]] \ - && ${pkgs.diffutils}/bin/diff -q "${currentConfigTokenPath}" ${escapeShellArg cfg.tokenFile} >/dev/null 2>&1 \ - || changed=1 - - # If the config has changed, remove old state and copy tokens - if [[ "$changed" -eq 1 ]]; then - echo "Config has changed, removing old runner state." - echo "The old runner will still appear in the GitHub Actions UI." \ - "You have to remove it manually." - clean_state - fi - } - - if [[ "${optionalString cfg.ephemeral "1"}" ]]; then - # In ephemeral mode, we always want to start with a clean state - clean_state - elif [[ "$(ls -A "$STATE_DIRECTORY")" ]]; then - # There are state files from a previous run; diff them to decide if we need a new registration - diff_config - else - # The state directory is entirely empty which indicates a first start - copy_tokens - fi - ''; - configureRunner = writeScript "configure" '' - if [[ -e "${newConfigTokenPath}" ]]; then - echo "Configuring GitHub Actions Runner" - - args=( - --unattended - --disableupdate - --work "$RUNTIME_DIRECTORY" - --url ${escapeShellArg cfg.url} - --labels ${escapeShellArg (concatStringsSep "," cfg.extraLabels)} - --name ${escapeShellArg cfg.name} - ${optionalString cfg.replace "--replace"} - ${optionalString (cfg.runnerGroup != null) "--runnergroup ${escapeShellArg cfg.runnerGroup}"} - ${optionalString cfg.ephemeral "--ephemeral"} - ) - - # If the token file contains a PAT (i.e., it starts with "ghp_"), we have to use the --pat option, - # if it is not a PAT, we assume it contains a registration token and use the --token option - token=$(<"${newConfigTokenPath}") - if [[ "$token" =~ ^ghp_* ]]; then - args+=(--pat "$token") - else - args+=(--token "$token") - fi - - ${cfg.package}/bin/config.sh "''${args[@]}" - - # Move the automatically created _diag dir to the logs dir - mkdir -p "$STATE_DIRECTORY/_diag" - cp -r "$STATE_DIRECTORY/_diag/." "$LOGS_DIRECTORY/" - rm -rf "$STATE_DIRECTORY/_diag/" - - # Cleanup token from config - rm "${newConfigTokenPath}" - - # Symlink to new config - ln -s '${newConfigPath}' "${currentConfigPath}" - fi - ''; - setupRuntimeDir = writeScript "setup-runtime-dirs" '' - # Link _diag dir - ln -s "$LOGS_DIRECTORY" "$RUNTIME_DIRECTORY/_diag" - - # Link the runner credentials to the runtime dir - ln -s "$STATE_DIRECTORY"/{${lib.concatStringsSep "," runnerCredFiles}} "$RUNTIME_DIRECTORY/" - ''; - in - map (x: "${x} ${escapeShellArgs [ stateDir runtimeDir logsDir ]}") [ - "+${unconfigureRunner}" # runs as root - configureRunner - setupRuntimeDir - ]; - - # If running in ephemeral mode, restart the service on-exit (i.e., successful de-registration of the runner) - # to trigger a fresh registration. - Restart = if cfg.ephemeral then "on-success" else "no"; - - # Contains _diag - LogsDirectory = [ systemdDir ]; - # Default RUNNER_ROOT which contains ephemeral Runner data - RuntimeDirectory = [ systemdDir ]; - # Home of persistent runner data, e.g., credentials - StateDirectory = [ systemdDir ]; - StateDirectoryMode = "0700"; - WorkingDirectory = runtimeDir; - - InaccessiblePaths = [ - # Token file path given in the configuration, if visible to the service - "-${cfg.tokenFile}" - # Token file in the state directory - "${stateDir}/${currentConfigTokenFilename}" - ]; - - # By default, use a dynamically allocated user - DynamicUser = true; - - KillSignal = "SIGINT"; - - # Hardening (may overlap with DynamicUser=) - # The following options are only for optimizing: - # systemd-analyze security github-runner - AmbientCapabilities = ""; - CapabilityBoundingSet = ""; - # ProtectClock= adds DeviceAllow=char-rtc r - DeviceAllow = ""; - NoNewPrivileges = true; - PrivateDevices = true; - PrivateMounts = true; - PrivateTmp = true; - PrivateUsers = true; - ProtectClock = true; - ProtectControlGroups = true; - ProtectHome = true; - ProtectHostname = true; - ProtectKernelLogs = true; - ProtectKernelModules = true; - ProtectKernelTunables = true; - ProtectSystem = "strict"; - RemoveIPC = true; - RestrictNamespaces = true; - RestrictRealtime = true; - RestrictSUIDSGID = true; - UMask = "0066"; - ProtectProc = "invisible"; - SystemCallFilter = [ - "~@clock" - "~@cpu-emulation" - "~@module" - "~@mount" - "~@obsolete" - "~@raw-io" - "~@reboot" - "~capset" - "~setdomainname" - "~sethostname" - ]; - RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" "AF_NETLINK" ]; - - # Needs network access - PrivateNetwork = false; - # Cannot be true due to Node - MemoryDenyWriteExecute = false; - - # The more restrictive "pid" option makes `nix` commands in CI emit - # "GC Warning: Couldn't read /proc/stat" - # You may want to set this to "pid" if not using `nix` commands - ProcSubset = "all"; - # Coverage programs for compiled code such as `cargo-tarpaulin` disable - # ASLR (address space layout randomization) which requires the - # `personality` syscall - # You may want to set this to `true` if not using coverage tooling on - # compiled code - LockPersonality = false; - }; - }; + systemd.services.${svcName} = import ./github-runner/service.nix (args // { inherit svcName; }); }; } diff --git a/nixos/modules/services/continuous-integration/github-runner/options.nix b/nixos/modules/services/continuous-integration/github-runner/options.nix new file mode 100644 index 0000000000000..82517caccc416 --- /dev/null +++ b/nixos/modules/services/continuous-integration/github-runner/options.nix @@ -0,0 +1,162 @@ +{ config, lib, pkgs, ... }: + +with lib; + +{ + enable = mkOption { + default = false; + example = true; + description = lib.mdDoc '' + Whether to enable GitHub Actions runner. + + Note: GitHub recommends using self-hosted runners with private repositories only. Learn more here: + [About self-hosted runners](https://docs.github.com/en/actions/hosting-your-own-runners/about-self-hosted-runners). + ''; + type = lib.types.bool; + }; + + url = mkOption { + type = types.str; + description = lib.mdDoc '' + Repository to add the runner to. + + Changing this option triggers a new runner registration. + + IMPORTANT: If your token is org-wide (not per repository), you need to + provide a github org link, not a single repository, so do it like this + `https://github.com/nixos`, not like this + `https://github.com/nixos/nixpkgs`. + Otherwise, you are going to get a `404 NotFound` + from `POST https://api.github.com/actions/runner-registration` + in the configure script. + ''; + example = "https://github.com/nixos/nixpkgs"; + }; + + tokenFile = mkOption { + type = types.path; + description = lib.mdDoc '' + The full path to a file which contains either a runner registration token or a + personal access token (PAT). + The file should contain exactly one line with the token without any newline. + If a registration token is given, it can be used to re-register a runner of the same + name but is time-limited. If the file contains a PAT, the service creates a new + registration token on startup as needed. Make sure the PAT has a scope of + `admin:org` for organization-wide registrations or a scope of + `repo` for a single repository. + + Changing this option or the file's content triggers a new runner registration. + ''; + example = "/run/secrets/github-runner/nixos.token"; + }; + + name = mkOption { + # Same pattern as for `networking.hostName` + type = types.strMatching "^$|^[[:alnum:]]([[:alnum:]_-]{0,61}[[:alnum:]])?$"; + description = lib.mdDoc '' + Name of the runner to configure. Defaults to the hostname. + + Changing this option triggers a new runner registration. + ''; + example = "nixos"; + default = config.networking.hostName; + defaultText = literalExpression "config.networking.hostName"; + }; + + runnerGroup = mkOption { + type = types.nullOr types.str; + description = lib.mdDoc '' + Name of the runner group to add this runner to (defaults to the default runner group). + + Changing this option triggers a new runner registration. + ''; + default = null; + }; + + extraLabels = mkOption { + type = types.listOf types.str; + description = lib.mdDoc '' + Extra labels in addition to the default (`["self-hosted", "Linux", "X64"]`). + + Changing this option triggers a new runner registration. + ''; + example = literalExpression ''[ "nixos" ]''; + default = [ ]; + }; + + replace = mkOption { + type = types.bool; + description = lib.mdDoc '' + Replace any existing runner with the same name. + + Without this flag, registering a new runner with the same name fails. + ''; + default = false; + }; + + extraPackages = mkOption { + type = types.listOf types.package; + description = lib.mdDoc '' + Extra packages to add to `PATH` of the service to make them available to workflows. + ''; + default = [ ]; + }; + + extraEnvironment = mkOption { + type = types.attrs; + description = '' + Extra environment variables to set for the runner, as an attrset. + ''; + example = { + GIT_CONFIG = "/path/to/git/config"; + }; + default = {}; + }; + + serviceOverrides = mkOption { + type = types.attrs; + description = '' + Overrides for the systemd service. Can be used to adjust the sandboxing options. + ''; + example = { + ProtectHome = false; + }; + default = {}; + }; + + package = mkOption { + type = types.package; + description = lib.mdDoc '' + Which github-runner derivation to use. + ''; + default = pkgs.github-runner; + defaultText = literalExpression "pkgs.github-runner"; + }; + + ephemeral = mkOption { + type = types.bool; + description = lib.mdDoc '' + If enabled, causes the following behavior: + + - Passes the `--ephemeral` flag to the runner configuration script + - De-registers and stops the runner with GitHub after it has processed one job + - On stop, systemd wipes the runtime directory (this always happens, even without using the ephemeral option) + - Restarts the service after its successful exit + - On start, wipes the state directory and configures a new runner + + You should only enable this option if `tokenFile` points to a file which contains a + personal access token (PAT). If you're using the option with a registration token, restarting the + service will fail as soon as the registration token expired. + ''; + default = false; + }; + + user = mkOption { + type = types.string; + description = '' + User under which to run the service. If null, will use a systemd dynamic user. + ''; + default = null; + defaultText = literalExpression "username"; + }; +} diff --git a/nixos/modules/services/continuous-integration/github-runner/service.nix b/nixos/modules/services/continuous-integration/github-runner/service.nix new file mode 100644 index 0000000000000..16bb75a56a574 --- /dev/null +++ b/nixos/modules/services/continuous-integration/github-runner/service.nix @@ -0,0 +1,247 @@ +{ config +, lib +, pkgs + +, cfg ? config.services.github-runner +, svcName + +, systemdDir ? "${svcName}/${cfg.name}" + # %t: Runtime directory root (usually /run); see systemd.unit(5) +, runtimeDir ? "%t/${systemdDir}" + # %S: State directory root (usually /var/lib); see systemd.unit(5) +, stateDir ? "%S/${systemdDir}" + # %L: Log directory root (usually /var/log); see systemd.unit(5) +, logsDir ? "%L/${systemdDir}" + # Name of file stored in service state directory +, currentConfigTokenFilename ? ".current-token" + +, ... +}: + +with lib; + +{ + description = "GitHub Actions runner"; + + wantedBy = [ "multi-user.target" ]; + wants = [ "network-online.target" ]; + after = [ "network.target" "network-online.target" ]; + + environment = { + HOME = runtimeDir; + RUNNER_ROOT = stateDir; + } // cfg.extraEnvironment; + + path = (with pkgs; [ + bash + coreutils + git + gnutar + gzip + ]) ++ [ + config.nix.package + ] ++ cfg.extraPackages; + + serviceConfig = rec { + ExecStart = "${cfg.package}/bin/Runner.Listener run --startuptype service"; + + # Does the following, sequentially: + # - If the module configuration or the token has changed, purge the state directory, + # and create the current and the new token file with the contents of the configured + # token. While both files have the same content, only the later is accessible by + # the service user. + # - Configure the runner using the new token file. When finished, delete it. + # - Set up the directory structure by creating the necessary symlinks. + ExecStartPre = + let + # Wrapper script which expects the full path of the state, runtime and logs + # directory as arguments. Overrides the respective systemd variables to provide + # unambiguous directory names. This becomes relevant, for example, if the + # caller overrides any of the StateDirectory=, RuntimeDirectory= or LogDirectory= + # to contain more than one directory. This causes systemd to set the respective + # environment variables with the path of all of the given directories, separated + # by a colon. + writeScript = name: lines: pkgs.writeShellScript "${svcName}-${name}.sh" '' + set -euo pipefail + + STATE_DIRECTORY="$1" + RUNTIME_DIRECTORY="$2" + LOGS_DIRECTORY="$3" + + ${lines} + ''; + currentConfigPath = "$STATE_DIRECTORY/.nixos-current-config.json"; + runnerRegistrationConfig = getAttrs [ "name" "tokenFile" "url" "runnerGroup" "extraLabels" "ephemeral" ] cfg; + newConfigPath = builtins.toFile "${svcName}-config.json" (builtins.toJSON runnerRegistrationConfig); + newConfigTokenFilename = ".new-token"; + runnerCredFiles = [ + ".credentials" + ".credentials_rsaparams" + ".runner" + ]; + unconfigureRunner = writeScript "unconfigure" '' + differs= + + if [[ "$(ls -A "$STATE_DIRECTORY")" ]]; then + # State directory is not empty + # Set `differs = 1` if current and new runner config differ or if `currentConfigPath` does not exist + ${pkgs.diffutils}/bin/diff -q '${newConfigPath}' "${currentConfigPath}" >/dev/null 2>&1 || differs=1 + # Also trigger a registration if the token content changed + ${pkgs.diffutils}/bin/diff -q \ + "$STATE_DIRECTORY"/${currentConfigTokenFilename} \ + ${escapeShellArg cfg.tokenFile} \ + >/dev/null 2>&1 || differs=1 + # If .credentials does not exist, assume a previous run de-registered the runner on stop (ephemeral mode) + [[ ! -f "$STATE_DIRECTORY/.credentials" ]] && differs=1 + fi + + if [[ -n "$differs" ]]; then + echo "Config has changed, removing old runner state." + # In ephemeral mode, the runner deletes the `.credentials` file after de-registering it with GitHub + [[ -f "$STATE_DIRECTORY/.credentials" ]] && echo "The old runner will still appear in the GitHub Actions UI." \ + "You have to remove it manually." + find "$STATE_DIRECTORY/" -mindepth 1 -delete + + # Copy the configured token file to the state dir and allow the service user to read the file + install --mode=666 ${escapeShellArg cfg.tokenFile} "$STATE_DIRECTORY/${newConfigTokenFilename}" + # Also copy current file to allow for a diff on the next start + install --mode=600 ${escapeShellArg cfg.tokenFile} "$STATE_DIRECTORY/${currentConfigTokenFilename}" + fi + ''; + configureRunner = writeScript "configure" '' + if [[ -e "$STATE_DIRECTORY/${newConfigTokenFilename}" ]]; then + echo "Configuring GitHub Actions Runner" + + args=( + --unattended + --disableupdate + --work "$RUNTIME_DIRECTORY" + --url ${escapeShellArg cfg.url} + --labels ${escapeShellArg (concatStringsSep "," cfg.extraLabels)} + --name ${escapeShellArg cfg.name} + ${optionalString cfg.replace "--replace"} + ${optionalString (cfg.runnerGroup != null) "--runnergroup ${escapeShellArg cfg.runnerGroup}"} + ${optionalString cfg.ephemeral "--ephemeral"} + ) + + # If the token file contains a PAT (i.e., it starts with "ghp_"), we have to use the --pat option, + # if it is not a PAT, we assume it contains a registration token and use the --token option + token=$(<"$STATE_DIRECTORY/${newConfigTokenFilename}") + if [[ "$token" =~ ^ghp_* ]]; then + args+=(--pat "$token") + else + args+=(--token "$token") + fi + + ${cfg.package}/bin/config.sh "''${args[@]}" + + # Move the automatically created _diag dir to the logs dir + mkdir -p "$STATE_DIRECTORY/_diag" + cp -r "$STATE_DIRECTORY/_diag/." "$LOGS_DIRECTORY/" + rm -rf "$STATE_DIRECTORY/_diag/" + + # Cleanup token from config + rm "$STATE_DIRECTORY/${newConfigTokenFilename}" + + # Symlink to new config + ln -s '${newConfigPath}' "${currentConfigPath}" + fi + ''; + setupRuntimeDir = writeScript "setup-runtime-dirs" '' + # Link _diag dir + ln -s "$LOGS_DIRECTORY" "$RUNTIME_DIRECTORY/_diag" + + # Link the runner credentials to the runtime dir + ln -s "$STATE_DIRECTORY"/{${lib.concatStringsSep "," runnerCredFiles}} "$RUNTIME_DIRECTORY/" + ''; + in + map (x: "${x} ${escapeShellArgs [ stateDir runtimeDir logsDir ]}") [ + "+${unconfigureRunner}" # runs as root + configureRunner + setupRuntimeDir + ]; + + # If running in ephemeral mode, restart the service on-exit (i.e., successful de-registration of the runner) + # to trigger a fresh registration. + Restart = if cfg.ephemeral then "on-success" else "no"; + + # Contains _diag + LogsDirectory = [ systemdDir ]; + # Default RUNNER_ROOT which contains ephemeral Runner data + RuntimeDirectory = [ systemdDir ]; + # Home of persistent runner data, e.g., credentials + StateDirectory = [ systemdDir ]; + StateDirectoryMode = "0700"; + WorkingDirectory = runtimeDir; + + InaccessiblePaths = [ + # Token file path given in the configuration + cfg.tokenFile + # Token file in the state directory + "${stateDir}/${currentConfigTokenFilename}" + ]; + + # By default, use a dynamically allocated user + DynamicUser = true; + + KillSignal = "SIGINT"; + + # Hardening (may overlap with DynamicUser=) + # The following options are only for optimizing: + # systemd-analyze security github-runner + AmbientCapabilities = ""; + CapabilityBoundingSet = ""; + # ProtectClock= adds DeviceAllow=char-rtc r + DeviceAllow = ""; + NoNewPrivileges = true; + PrivateDevices = true; + PrivateMounts = true; + PrivateTmp = true; + PrivateUsers = true; + ProtectClock = true; + ProtectControlGroups = true; + ProtectHome = true; + ProtectHostname = true; + ProtectKernelLogs = true; + ProtectKernelModules = true; + ProtectKernelTunables = true; + ProtectSystem = "strict"; + RemoveIPC = true; + RestrictNamespaces = true; + RestrictRealtime = true; + RestrictSUIDSGID = true; + UMask = "0066"; + ProtectProc = "invisible"; + SystemCallFilter = [ + "~@clock" + "~@cpu-emulation" + "~@module" + "~@mount" + "~@obsolete" + "~@raw-io" + "~@reboot" + "~capset" + "~setdomainname" + "~sethostname" + ]; + RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" "AF_NETLINK" ]; + + # Needs network access + PrivateNetwork = false; + # Cannot be true due to Node + MemoryDenyWriteExecute = false; + + # The more restrictive "pid" option makes `nix` commands in CI emit + # "GC Warning: Couldn't read /proc/stat" + # You may want to set this to "pid" if not using `nix` commands + ProcSubset = "all"; + # Coverage programs for compiled code such as `cargo-tarpaulin` disable + # ASLR (address space layout randomization) which requires the + # `personality` syscall + # You may want to set this to `true` if not using coverage tooling on + # compiled code + LockPersonality = false; + } // ( + if cfg.user == null then { DynamicUser = true; } else { User = cfg.user; } + ) // cfg.serviceOverrides; +} diff --git a/nixos/modules/services/continuous-integration/github-runners.nix b/nixos/modules/services/continuous-integration/github-runners.nix new file mode 100644 index 0000000000000..3e62d29736a07 --- /dev/null +++ b/nixos/modules/services/continuous-integration/github-runners.nix @@ -0,0 +1,51 @@ +{ config +, pkgs +, lib +, ... +}@args: + +with lib; + +let + cfg = config.services.github-runners; + +in + +{ + options.services.github-runners = mkOption { + default = {}; + type = with types; attrsOf (submodule { options = import ./github-runner/options.nix args; }); + example = { + runner1 = { + enable = true; + url = "https://github.com/owner/repo"; + name = "runner1"; + tokenFile = "/secrets/token1"; + }; + + runner2 = { + enable = true; + url = "https://github.com/owner/repo"; + name = "runner2"; + tokenFile = "/secrets/token2"; + }; + }; + description = '' + Multiple GitHub Runners. + ''; + }; + + config = { + systemd.services = flip mapAttrs' cfg (n: v: + let + svcName = "github-runner-${n}"; + in + nameValuePair svcName + (import ./github-runner/service.nix (args // { + inherit svcName; + cfg = v; + systemdDir = svcName; + })) + ); + }; +} -- cgit 1.4.1 From f13759e21fd938b3b7dfd9002e791a0532903ff3 Mon Sep 17 00:00:00 2001 From: Tom McLaughlin Date: Wed, 14 Sep 2022 21:26:50 -0700 Subject: Fix a deprecated types.string -> types.str --- nixos/modules/services/continuous-integration/github-runner/options.nix | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'nixos') diff --git a/nixos/modules/services/continuous-integration/github-runner/options.nix b/nixos/modules/services/continuous-integration/github-runner/options.nix index 82517caccc416..9c11b7f9172d6 100644 --- a/nixos/modules/services/continuous-integration/github-runner/options.nix +++ b/nixos/modules/services/continuous-integration/github-runner/options.nix @@ -152,7 +152,7 @@ with lib; }; user = mkOption { - type = types.string; + type = types.str; description = '' User under which to run the service. If null, will use a systemd dynamic user. ''; -- cgit 1.4.1 From 327e05c382991496e37ddb40a5044b8be2a80f99 Mon Sep 17 00:00:00 2001 From: Tom McLaughlin Date: Thu, 15 Sep 2022 01:05:28 -0700 Subject: Get rid of DynamicUser flag --- .../modules/services/continuous-integration/github-runner/service.nix | 3 --- 1 file changed, 3 deletions(-) (limited to 'nixos') diff --git a/nixos/modules/services/continuous-integration/github-runner/service.nix b/nixos/modules/services/continuous-integration/github-runner/service.nix index 16bb75a56a574..eb1f9caddae1e 100644 --- a/nixos/modules/services/continuous-integration/github-runner/service.nix +++ b/nixos/modules/services/continuous-integration/github-runner/service.nix @@ -181,9 +181,6 @@ with lib; "${stateDir}/${currentConfigTokenFilename}" ]; - # By default, use a dynamically allocated user - DynamicUser = true; - KillSignal = "SIGINT"; # Hardening (may overlap with DynamicUser=) -- cgit 1.4.1 From b3de807a6a691c48d433c45437d4192cae8c4818 Mon Sep 17 00:00:00 2001 From: Tom McLaughlin Date: Mon, 19 Sep 2022 02:11:16 -0600 Subject: Update descriptions to use lib.mdDoc --- .../services/continuous-integration/github-runner/options.nix | 6 +++--- nixos/modules/services/continuous-integration/github-runners.nix | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'nixos') diff --git a/nixos/modules/services/continuous-integration/github-runner/options.nix b/nixos/modules/services/continuous-integration/github-runner/options.nix index 9c11b7f9172d6..daae32c9e81f0 100644 --- a/nixos/modules/services/continuous-integration/github-runner/options.nix +++ b/nixos/modules/services/continuous-integration/github-runner/options.nix @@ -104,7 +104,7 @@ with lib; extraEnvironment = mkOption { type = types.attrs; - description = '' + description = lib.mdDoc '' Extra environment variables to set for the runner, as an attrset. ''; example = { @@ -115,7 +115,7 @@ with lib; serviceOverrides = mkOption { type = types.attrs; - description = '' + description = lib.mdDoc '' Overrides for the systemd service. Can be used to adjust the sandboxing options. ''; example = { @@ -153,7 +153,7 @@ with lib; user = mkOption { type = types.str; - description = '' + description = lib.mdDoc '' User under which to run the service. If null, will use a systemd dynamic user. ''; default = null; diff --git a/nixos/modules/services/continuous-integration/github-runners.nix b/nixos/modules/services/continuous-integration/github-runners.nix index 3e62d29736a07..693dc17076fff 100644 --- a/nixos/modules/services/continuous-integration/github-runners.nix +++ b/nixos/modules/services/continuous-integration/github-runners.nix @@ -30,7 +30,7 @@ in tokenFile = "/secrets/token2"; }; }; - description = '' + description = lib.mdDoc '' Multiple GitHub Runners. ''; }; -- cgit 1.4.1 From b744fee8805876a96c816aa1ec425160d63c3cab Mon Sep 17 00:00:00 2001 From: Tom McLaughlin Date: Sun, 25 Sep 2022 05:07:50 -0600 Subject: Re-add `DynamicUser = true` per review discussion --- .../services/continuous-integration/github-runner/service.nix | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'nixos') diff --git a/nixos/modules/services/continuous-integration/github-runner/service.nix b/nixos/modules/services/continuous-integration/github-runner/service.nix index eb1f9caddae1e..208ada4f31a30 100644 --- a/nixos/modules/services/continuous-integration/github-runner/service.nix +++ b/nixos/modules/services/continuous-integration/github-runner/service.nix @@ -238,7 +238,11 @@ with lib; # You may want to set this to `true` if not using coverage tooling on # compiled code LockPersonality = false; + + # Note that this has some interactions with the User setting; so you may + # want to consult the systemd docs if using both. + DynamicUser = true; } // ( - if cfg.user == null then { DynamicUser = true; } else { User = cfg.user; } + lib.optionalAttrs (cfg.user != null) { User = cfg.user; } ) // cfg.serviceOverrides; } -- cgit 1.4.1 From 9a7f38040b43a275f2606023ddef61c2a1ebe3de Mon Sep 17 00:00:00 2001 From: Tom McLaughlin Date: Mon, 26 Sep 2022 05:01:35 -0600 Subject: Fix user type --- nixos/modules/services/continuous-integration/github-runner/options.nix | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'nixos') diff --git a/nixos/modules/services/continuous-integration/github-runner/options.nix b/nixos/modules/services/continuous-integration/github-runner/options.nix index daae32c9e81f0..8cb1999a63f9c 100644 --- a/nixos/modules/services/continuous-integration/github-runner/options.nix +++ b/nixos/modules/services/continuous-integration/github-runner/options.nix @@ -152,7 +152,7 @@ with lib; }; user = mkOption { - type = types.str; + type = types.nullOr types.str; description = lib.mdDoc '' User under which to run the service. If null, will use a systemd dynamic user. ''; -- cgit 1.4.1 From 0b67081ad824fe917535bb86cd768cd0ffdce2f8 Mon Sep 17 00:00:00 2001 From: Tom McLaughlin Date: Tue, 11 Oct 2022 06:10:11 -0600 Subject: Cherry-pick 499748b --- .../github-runner/service.nix | 84 ++++++++++++---------- 1 file changed, 45 insertions(+), 39 deletions(-) (limited to 'nixos') diff --git a/nixos/modules/services/continuous-integration/github-runner/service.nix b/nixos/modules/services/continuous-integration/github-runner/service.nix index 208ada4f31a30..4dc8445495a60 100644 --- a/nixos/modules/services/continuous-integration/github-runner/service.nix +++ b/nixos/modules/services/continuous-integration/github-runner/service.nix @@ -70,48 +70,59 @@ with lib; ${lines} ''; - currentConfigPath = "$STATE_DIRECTORY/.nixos-current-config.json"; runnerRegistrationConfig = getAttrs [ "name" "tokenFile" "url" "runnerGroup" "extraLabels" "ephemeral" ] cfg; newConfigPath = builtins.toFile "${svcName}-config.json" (builtins.toJSON runnerRegistrationConfig); - newConfigTokenFilename = ".new-token"; + currentConfigPath = "$STATE_DIRECTORY/.nixos-current-config.json"; + newConfigTokenPath= "$STATE_DIRECTORY/.new-token"; + currentConfigTokenPath = "$STATE_DIRECTORY/${currentConfigTokenFilename}"; + runnerCredFiles = [ ".credentials" ".credentials_rsaparams" ".runner" ]; unconfigureRunner = writeScript "unconfigure" '' - differs= - - if [[ "$(ls -A "$STATE_DIRECTORY")" ]]; then - # State directory is not empty - # Set `differs = 1` if current and new runner config differ or if `currentConfigPath` does not exist - ${pkgs.diffutils}/bin/diff -q '${newConfigPath}' "${currentConfigPath}" >/dev/null 2>&1 || differs=1 - # Also trigger a registration if the token content changed - ${pkgs.diffutils}/bin/diff -q \ - "$STATE_DIRECTORY"/${currentConfigTokenFilename} \ - ${escapeShellArg cfg.tokenFile} \ - >/dev/null 2>&1 || differs=1 - # If .credentials does not exist, assume a previous run de-registered the runner on stop (ephemeral mode) - [[ ! -f "$STATE_DIRECTORY/.credentials" ]] && differs=1 - fi - - if [[ -n "$differs" ]]; then - echo "Config has changed, removing old runner state." - # In ephemeral mode, the runner deletes the `.credentials` file after de-registering it with GitHub - [[ -f "$STATE_DIRECTORY/.credentials" ]] && echo "The old runner will still appear in the GitHub Actions UI." \ - "You have to remove it manually." - find "$STATE_DIRECTORY/" -mindepth 1 -delete - + copy_tokens() { # Copy the configured token file to the state dir and allow the service user to read the file - install --mode=666 ${escapeShellArg cfg.tokenFile} "$STATE_DIRECTORY/${newConfigTokenFilename}" + install --mode=666 ${escapeShellArg cfg.tokenFile} "${newConfigTokenPath}" # Also copy current file to allow for a diff on the next start - install --mode=600 ${escapeShellArg cfg.tokenFile} "$STATE_DIRECTORY/${currentConfigTokenFilename}" - fi - ''; + install --mode=600 ${escapeShellArg cfg.tokenFile} "${currentConfigTokenPath}" + } + clean_state() { + find "$STATE_DIRECTORY/" -mindepth 1 -delete + copy_tokens + } + diff_config() { + changed=0 + # Check for module config changes + [[ -f "${currentConfigPath}" ]] \ + && ${pkgs.diffutils}/bin/diff -q '${newConfigPath}' "${currentConfigPath}" >/dev/null 2>&1 \ + || changed=1 + # Also check the content of the token file + [[ -f "${currentConfigTokenPath}" ]] \ + && ${pkgs.diffutils}/bin/diff -q "${currentConfigTokenPath}" ${escapeShellArg cfg.tokenFile} >/dev/null 2>&1 \ + || changed=1 + # If the config has changed, remove old state and copy tokens + if [[ "$changed" -eq 1 ]]; then + echo "Config has changed, removing old runner state." + echo "The old runner will still appear in the GitHub Actions UI." \ + "You have to remove it manually." + clean_state + fi + } + if [[ "${optionalString cfg.ephemeral "1"}" ]]; then + # In ephemeral mode, we always want to start with a clean state + clean_state + elif [[ "$(ls -A "$STATE_DIRECTORY")" ]]; then + # There are state files from a previous run; diff them to decide if we need a new registration + diff_config + else + # The state directory is entirely empty which indicates a first start + copy_tokens + fi ''; configureRunner = writeScript "configure" '' - if [[ -e "$STATE_DIRECTORY/${newConfigTokenFilename}" ]]; then + if [[ -e "${newConfigTokenPath}" ]]; then echo "Configuring GitHub Actions Runner" - args=( --unattended --disableupdate @@ -123,26 +134,21 @@ with lib; ${optionalString (cfg.runnerGroup != null) "--runnergroup ${escapeShellArg cfg.runnerGroup}"} ${optionalString cfg.ephemeral "--ephemeral"} ) - # If the token file contains a PAT (i.e., it starts with "ghp_"), we have to use the --pat option, # if it is not a PAT, we assume it contains a registration token and use the --token option - token=$(<"$STATE_DIRECTORY/${newConfigTokenFilename}") + token=$(<"${newConfigTokenPath}") if [[ "$token" =~ ^ghp_* ]]; then args+=(--pat "$token") else args+=(--token "$token") fi - ${cfg.package}/bin/config.sh "''${args[@]}" - # Move the automatically created _diag dir to the logs dir mkdir -p "$STATE_DIRECTORY/_diag" cp -r "$STATE_DIRECTORY/_diag/." "$LOGS_DIRECTORY/" rm -rf "$STATE_DIRECTORY/_diag/" - # Cleanup token from config - rm "$STATE_DIRECTORY/${newConfigTokenFilename}" - + rm "${newConfigTokenPath}" # Symlink to new config ln -s '${newConfigPath}' "${currentConfigPath}" fi @@ -175,8 +181,8 @@ with lib; WorkingDirectory = runtimeDir; InaccessiblePaths = [ - # Token file path given in the configuration - cfg.tokenFile + # Token file path given in the configuration, if visible to the service + "-${cfg.tokenFile}" # Token file in the state directory "${stateDir}/${currentConfigTokenFilename}" ]; -- cgit 1.4.1 From cf1b9529884999621a9cf06036df8fba4aee99b3 Mon Sep 17 00:00:00 2001 From: Tom McLaughlin Date: Thu, 13 Oct 2022 18:49:02 -0600 Subject: Update nixos/modules/services/continuous-integration/github-runner.nix Co-authored-by: Vincent Haupert --- nixos/modules/services/continuous-integration/github-runner.nix | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'nixos') diff --git a/nixos/modules/services/continuous-integration/github-runner.nix b/nixos/modules/services/continuous-integration/github-runner.nix index 1b435b019215b..3e0cefb8c26f4 100644 --- a/nixos/modules/services/continuous-integration/github-runner.nix +++ b/nixos/modules/services/continuous-integration/github-runner.nix @@ -18,7 +18,7 @@ in config = mkIf cfg.enable { warnings = optionals (isStorePath cfg.tokenFile) [ '' - `services.${svgName}.tokenFile` points to the Nix store and, therefore, is world-readable. + `services.${svcName}.tokenFile` points to the Nix store and, therefore, is world-readable. Consider using a path outside of the Nix store to keep the token private. '' ]; -- cgit 1.4.1 From 69d9538b345e48a74c2ed3b279f8cb4a73a8261f Mon Sep 17 00:00:00 2001 From: Tom McLaughlin Date: Thu, 13 Oct 2022 18:53:25 -0600 Subject: Update nixos/modules/services/continuous-integration/github-runners.nix Co-authored-by: Vincent Haupert --- nixos/modules/services/continuous-integration/github-runners.nix | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'nixos') diff --git a/nixos/modules/services/continuous-integration/github-runners.nix b/nixos/modules/services/continuous-integration/github-runners.nix index 693dc17076fff..7160e1cbc156b 100644 --- a/nixos/modules/services/continuous-integration/github-runners.nix +++ b/nixos/modules/services/continuous-integration/github-runners.nix @@ -44,7 +44,7 @@ in (import ./github-runner/service.nix (args // { inherit svcName; cfg = v; - systemdDir = svcName; + systemdDir = "github-runner/${n}"; })) ); }; -- cgit 1.4.1 From fc8fdb03a0255e1720bab16c01a5c5e8a9152ae1 Mon Sep 17 00:00:00 2001 From: Tom McLaughlin Date: Thu, 13 Oct 2022 19:12:52 -0600 Subject: Try simpler github-runner.nix --- .../modules/services/continuous-integration/github-runner.nix | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) (limited to 'nixos') diff --git a/nixos/modules/services/continuous-integration/github-runner.nix b/nixos/modules/services/continuous-integration/github-runner.nix index 3e0cefb8c26f4..f9f3cc5befa14 100644 --- a/nixos/modules/services/continuous-integration/github-runner.nix +++ b/nixos/modules/services/continuous-integration/github-runner.nix @@ -8,21 +8,12 @@ with lib; let cfg = config.services.github-runner; - svcName = "github-runner"; - in { options.services.github-runner = import ./github-runner/options.nix args; config = mkIf cfg.enable { - warnings = optionals (isStorePath cfg.tokenFile) [ - '' - `services.${svcName}.tokenFile` points to the Nix store and, therefore, is world-readable. - Consider using a path outside of the Nix store to keep the token private. - '' - ]; - - systemd.services.${svcName} = import ./github-runner/service.nix (args // { inherit svcName; }); + services.github-runners.${cfg.name} = cfg; }; } -- cgit 1.4.1 From 2c099d1a143e7fd5a573a1f4c4288b290383dd46 Mon Sep 17 00:00:00 2001 From: Tom McLaughlin Date: Fri, 14 Oct 2022 05:31:50 -0600 Subject: Set runner name to attr name for github-runners.${name} --- .../modules/services/continuous-integration/github-runner.nix | 2 +- .../services/continuous-integration/github-runner/options.nix | 8 +++++++- .../modules/services/continuous-integration/github-runners.nix | 10 +++++----- 3 files changed, 13 insertions(+), 7 deletions(-) (limited to 'nixos') diff --git a/nixos/modules/services/continuous-integration/github-runner.nix b/nixos/modules/services/continuous-integration/github-runner.nix index f9f3cc5befa14..5535044409aca 100644 --- a/nixos/modules/services/continuous-integration/github-runner.nix +++ b/nixos/modules/services/continuous-integration/github-runner.nix @@ -11,7 +11,7 @@ let in { - options.services.github-runner = import ./github-runner/options.nix args; + options.services.github-runner = import ./github-runner/options.nix (args // { includeNameDefault = true; }); config = mkIf cfg.enable { services.github-runners.${cfg.name} = cfg; diff --git a/nixos/modules/services/continuous-integration/github-runner/options.nix b/nixos/modules/services/continuous-integration/github-runner/options.nix index 8cb1999a63f9c..e021127a979b0 100644 --- a/nixos/modules/services/continuous-integration/github-runner/options.nix +++ b/nixos/modules/services/continuous-integration/github-runner/options.nix @@ -1,4 +1,9 @@ -{ config, lib, pkgs, ... }: +{ config +, lib +, pkgs +, includeNameDefault +, ... +}: with lib; @@ -59,6 +64,7 @@ with lib; Changing this option triggers a new runner registration. ''; example = "nixos"; + } // lib.optionalAttrs includeNameDefault { default = config.networking.hostName; defaultText = literalExpression "config.networking.hostName"; }; diff --git a/nixos/modules/services/continuous-integration/github-runners.nix b/nixos/modules/services/continuous-integration/github-runners.nix index 7160e1cbc156b..c41e99ccfe5a7 100644 --- a/nixos/modules/services/continuous-integration/github-runners.nix +++ b/nixos/modules/services/continuous-integration/github-runners.nix @@ -14,7 +14,7 @@ in { options.services.github-runners = mkOption { default = {}; - type = with types; attrsOf (submodule { options = import ./github-runner/options.nix args; }); + type = with types; attrsOf (submodule { options = import ./github-runner/options.nix (args // { includeNameDefault = false; }); }); example = { runner1 = { enable = true; @@ -36,15 +36,15 @@ in }; config = { - systemd.services = flip mapAttrs' cfg (n: v: + systemd.services = flip mapAttrs' cfg (name: v: let - svcName = "github-runner-${n}"; + svcName = "github-runner-${name}"; in nameValuePair svcName (import ./github-runner/service.nix (args // { inherit svcName; - cfg = v; - systemdDir = "github-runner/${n}"; + cfg = v // { inherit name; }; + systemdDir = "github-runner/${name}"; })) ); }; -- cgit 1.4.1 From 5221e7af04db06e4847ea1af55e16fb140c02b92 Mon Sep 17 00:00:00 2001 From: Tom McLaughlin Date: Mon, 17 Oct 2022 00:04:52 -0700 Subject: Add comments to explain about the name defaults --- nixos/modules/services/continuous-integration/github-runner.nix | 6 +++++- nixos/modules/services/continuous-integration/github-runners.nix | 5 ++++- 2 files changed, 9 insertions(+), 2 deletions(-) (limited to 'nixos') diff --git a/nixos/modules/services/continuous-integration/github-runner.nix b/nixos/modules/services/continuous-integration/github-runner.nix index 5535044409aca..24d02c931a4ae 100644 --- a/nixos/modules/services/continuous-integration/github-runner.nix +++ b/nixos/modules/services/continuous-integration/github-runner.nix @@ -11,7 +11,11 @@ let in { - options.services.github-runner = import ./github-runner/options.nix (args // { includeNameDefault = true; }); + options.services.github-runner = import ./github-runner/options.nix (args // { + # Users don't need to specify options.services.github-runner.name; it will default + # to the hostname. + includeNameDefault = true; + }); config = mkIf cfg.enable { services.github-runners.${cfg.name} = cfg; diff --git a/nixos/modules/services/continuous-integration/github-runners.nix b/nixos/modules/services/continuous-integration/github-runners.nix index c41e99ccfe5a7..dfa37c1c76e88 100644 --- a/nixos/modules/services/continuous-integration/github-runners.nix +++ b/nixos/modules/services/continuous-integration/github-runners.nix @@ -14,7 +14,10 @@ in { options.services.github-runners = mkOption { default = {}; - type = with types; attrsOf (submodule { options = import ./github-runner/options.nix (args // { includeNameDefault = false; }); }); + type = with types; attrsOf (submodule { options = import ./github-runner/options.nix (args // { + # services.github-runners.${name}.name doesn't have a default; instead it is set to ${name} below. + includeNameDefault = false; + }); }); example = { runner1 = { enable = true; -- cgit 1.4.1 From c2cc9aeafdc4cc04b62da83bc93dd407e7a5f799 Mon Sep 17 00:00:00 2001 From: Tom McLaughlin Date: Wed, 19 Oct 2022 02:35:44 -0700 Subject: Use config name by default, falling back to attr name --- .../continuous-integration/github-runner/options.nix | 12 ++++++++---- .../services/continuous-integration/github-runners.nix | 12 +++++++----- 2 files changed, 15 insertions(+), 9 deletions(-) (limited to 'nixos') diff --git a/nixos/modules/services/continuous-integration/github-runner/options.nix b/nixos/modules/services/continuous-integration/github-runner/options.nix index e021127a979b0..ae89d3a3bfb6c 100644 --- a/nixos/modules/services/continuous-integration/github-runner/options.nix +++ b/nixos/modules/services/continuous-integration/github-runner/options.nix @@ -55,19 +55,23 @@ with lib; example = "/run/secrets/github-runner/nixos.token"; }; - name = mkOption { + name = let # Same pattern as for `networking.hostName` - type = types.strMatching "^$|^[[:alnum:]]([[:alnum:]_-]{0,61}[[:alnum:]])?$"; + baseType = types.strMatching "^$|^[[:alnum:]]([[:alnum:]_-]{0,61}[[:alnum:]])?$"; + in mkOption { + type = if includeNameDefault then baseType else types.nullOr baseType; description = lib.mdDoc '' Name of the runner to configure. Defaults to the hostname. Changing this option triggers a new runner registration. ''; example = "nixos"; - } // lib.optionalAttrs includeNameDefault { + } // (if includeNameDefault then { default = config.networking.hostName; defaultText = literalExpression "config.networking.hostName"; - }; + } else { + default = null; + }); runnerGroup = mkOption { type = types.nullOr types.str; diff --git a/nixos/modules/services/continuous-integration/github-runners.nix b/nixos/modules/services/continuous-integration/github-runners.nix index dfa37c1c76e88..78b57f9c7a256 100644 --- a/nixos/modules/services/continuous-integration/github-runners.nix +++ b/nixos/modules/services/continuous-integration/github-runners.nix @@ -15,7 +15,7 @@ in options.services.github-runners = mkOption { default = {}; type = with types; attrsOf (submodule { options = import ./github-runner/options.nix (args // { - # services.github-runners.${name}.name doesn't have a default; instead it is set to ${name} below. + # services.github-runners.${name}.name doesn't have a default; it falls back to ${name} below. includeNameDefault = false; }); }); example = { @@ -39,15 +39,17 @@ in }; config = { - systemd.services = flip mapAttrs' cfg (name: v: + systemd.services = flip mapAttrs' cfg (n: v: let - svcName = "github-runner-${name}"; + svcName = "github-runner-${n}"; in nameValuePair svcName (import ./github-runner/service.nix (args // { inherit svcName; - cfg = v // { inherit name; }; - systemdDir = "github-runner/${name}"; + cfg = v // { + name = if v.name != null then v.name else n; + }; + systemdDir = "github-runner/${n}"; })) ); }; -- cgit 1.4.1