about summary refs log tree commit diff
path: root/nixos/modules/services/continuous-integration/gitlab-runner.nix
blob: 1771ca0b980b9af19a6b71a77e424404fe3ee60c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
{ config, lib, pkgs, ... }:

let
  inherit (builtins)
    hashString
    map
    substring
    toJSON
    toString
    unsafeDiscardStringContext
    ;

  inherit (lib)
    any
    assertMsg
    attrValues
    concatStringsSep
    escapeShellArg
    filterAttrs
    hasPrefix
    isStorePath
    literalExpression
    mapAttrs'
    mapAttrsToList
    mkDefault
    mkEnableOption
    mkIf
    mkOption
    mkPackageOption
    mkRemovedOptionModule
    mkRenamedOptionModule
    nameValuePair
    optional
    optionalAttrs
    optionals
    teams
    toShellVar
    types
    ;

  cfg = config.services.gitlab-runner;
  hasDocker = config.virtualisation.docker.enable;

  /* The whole logic of this module is to diff the hashes of the desired vs existing runners
  The hash is recorded in the runner's name because we can't do better yet
  See https://gitlab.com/gitlab-org/gitlab-runner/-/issues/29350 for more details
  */
  genRunnerName = name: service: let
      hash = substring 0 12 (hashString "md5" (unsafeDiscardStringContext (toJSON service)));
    in if service ? description && service.description != null
    then "${hash} ${service.description}"
    else "${name}_${config.networking.hostName}_${hash}";

  hashedServices = mapAttrs'
    (name: service: nameValuePair (genRunnerName name service) service) cfg.services;
  configPath = ''"$HOME"/.gitlab-runner/config.toml'';
  configureScript = pkgs.writeShellApplication {
    name = "gitlab-runner-configure";
    runtimeInputs = [ cfg.package ] ++ (with pkgs; [
        bash
        gawk
        jq
        moreutils
        remarshal
        util-linux
        perl
        python3
    ]);
    text = if (cfg.configFile != null) then ''
      cp ${cfg.configFile} ${configPath}
      # make config file readable by service
      chown -R --reference="$HOME" "$(dirname ${configPath})"
    '' else ''
      export CONFIG_FILE=${configPath}

      mkdir -p "$(dirname ${configPath})"
      touch ${configPath}

      # update global options
      remarshal --if toml --of json ${configPath} \
        | jq -cM 'with_entries(select([.key] | inside(["runners"])))' \
        | jq -scM '.[0] + .[1]' - <(echo ${escapeShellArg (toJSON cfg.settings)}) \
        | remarshal --if json --of toml \
        | sponge ${configPath}

      # remove no longer existing services
      gitlab-runner verify --delete

      ${toShellVar "NEEDED_SERVICES" (lib.mapAttrs (name: value: 1) hashedServices)}

      declare -A REGISTERED_SERVICES

      while IFS="," read -r name token;
      do
        REGISTERED_SERVICES["$name"]="$token"
      done < <(gitlab-runner --log-format json list 2>&1 | grep Token  | jq -r '.msg +"," + .Token')

      echo "NEEDED_SERVICES: " "''${!NEEDED_SERVICES[@]}"
      echo "REGISTERED_SERVICES:" "''${!REGISTERED_SERVICES[@]}"

      # difference between current and desired state
      declare -A NEW_SERVICES
      for name in "''${!NEEDED_SERVICES[@]}"; do
        if [ ! -v 'REGISTERED_SERVICES[$name]' ]; then
          NEW_SERVICES[$name]=1
        fi
      done

      declare -A OLD_SERVICES
      # shellcheck disable=SC2034
      for name in "''${!REGISTERED_SERVICES[@]}"; do
        if [ ! -v 'NEEDED_SERVICES[$name]' ]; then
          OLD_SERVICES[$name]=1
        fi
      done

      # register new services
      ${concatStringsSep "\n" (mapAttrsToList (name: service: ''
        # TODO so here we should mention NEW_SERVICES
        if [ -v 'NEW_SERVICES["${name}"]' ] ; then
          bash -c ${escapeShellArg (concatStringsSep " \\\n " ([
            "set -a && source ${
              if service.registrationConfigFile != null
              then service.registrationConfigFile
              else service.authenticationTokenConfigFile} &&"
            "gitlab-runner register"
            "--non-interactive"
            "--name '${name}'"
            "--executor ${service.executor}"
            "--limit ${toString service.limit}"
            "--request-concurrency ${toString service.requestConcurrency}"
          ]
            ++ optional (service.authenticationTokenConfigFile == null)
            "--maximum-timeout ${toString service.maximumTimeout}"
            ++ service.registrationFlags
            ++ optional (service.buildsDir != null)
            "--builds-dir ${service.buildsDir}"
            ++ optional (service.cloneUrl != null)
            "--clone-url ${service.cloneUrl}"
            ++ optional (service.preCloneScript != null)
            "--pre-clone-script ${service.preCloneScript}"
            ++ optional (service.preBuildScript != null)
            "--pre-build-script ${service.preBuildScript}"
            ++ optional (service.postBuildScript != null)
            "--post-build-script ${service.postBuildScript}"
            ++ optional (service.authenticationTokenConfigFile == null && service.tagList != [ ])
            "--tag-list ${concatStringsSep "," service.tagList}"
            ++ optional (service.authenticationTokenConfigFile == null && service.runUntagged)
            "--run-untagged"
            ++ optional (service.authenticationTokenConfigFile == null && service.protected)
            "--access-level ref_protected"
            ++ optional service.debugTraceDisabled
            "--debug-trace-disabled"
            ++ map (e: "--env ${escapeShellArg e}") (mapAttrsToList (name: value: "${name}=${value}") service.environmentVariables)
            ++ optionals (hasPrefix "docker" service.executor) (
              assert (
                assertMsg (service.dockerImage != null)
                  "dockerImage option is required for ${service.executor} executor (${name})");
              [ "--docker-image ${service.dockerImage}" ]
              ++ optional service.dockerDisableCache
              "--docker-disable-cache"
              ++ optional service.dockerPrivileged
              "--docker-privileged"
              ++ map (v: "--docker-volumes ${escapeShellArg v}") service.dockerVolumes
              ++ map (v: "--docker-extra-hosts ${escapeShellArg v}") service.dockerExtraHosts
              ++ map (v: "--docker-allowed-images ${escapeShellArg v}") service.dockerAllowedImages
              ++ map (v: "--docker-allowed-services ${escapeShellArg v}") service.dockerAllowedServices
            )
          ))} && sleep 1 || exit 1
        fi
      '') hashedServices)}

      # check key is in array https://stackoverflow.com/questions/30353951/how-to-check-if-dictionary-contains-a-key-in-bash

      echo "NEW_SERVICES: ''${NEW_SERVICES[*]}"
      echo "OLD_SERVICES: ''${OLD_SERVICES[*]}"
      # unregister old services
      for NAME in "''${!OLD_SERVICES[@]}"
      do
        [ -n "$NAME" ] && gitlab-runner unregister \
          --name "$NAME" && sleep 1
      done

      # make config file readable by service
      chown -R --reference="$HOME" "$(dirname ${configPath})"
    '';
  };
  startScript = pkgs.writeShellScriptBin "gitlab-runner-start" ''
    export CONFIG_FILE=${configPath}
    exec gitlab-runner run --working-directory $HOME
  '';
in {
  options.services.gitlab-runner = {
    enable = mkEnableOption "Gitlab Runner";
    configFile = mkOption {
      type = types.nullOr types.path;
      default = null;
      description = ''
        Configuration file for gitlab-runner.

        {option}`configFile` takes precedence over {option}`services`.
        {option}`checkInterval` and {option}`concurrent` will be ignored too.

        This option is deprecated, please use {option}`services` instead.
        You can use {option}`registrationConfigFile` and
        {option}`registrationFlags`
        for settings not covered by this module.
      '';
    };
    settings = mkOption {
      type = types.submodule {
        freeformType = (pkgs.formats.json { }).type;
      };
      default = { };
      description = ''
        Global gitlab-runner configuration. See
        <https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-global-section>
        for supported values.
      '';
    };
    gracefulTermination = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Finish all remaining jobs before stopping.
        If not set gitlab-runner will stop immediately without waiting
        for jobs to finish, which will lead to failed builds.
      '';
    };
    gracefulTimeout = mkOption {
      type = types.str;
      default = "infinity";
      example = "5min 20s";
      description = ''
        Time to wait until a graceful shutdown is turned into a forceful one.
      '';
    };
    package = mkPackageOption pkgs "gitlab-runner" {
      example = "gitlab-runner_1_11";
    };
    extraPackages = mkOption {
      type = types.listOf types.package;
      default = [ ];
      description = ''
        Extra packages to add to PATH for the gitlab-runner process.
      '';
    };
    services = mkOption {
      description = "GitLab Runner services.";
      default = { };
      example = literalExpression ''
        {
          # runner for building in docker via host's nix-daemon
          # nix store will be readable in runner, might be insecure
          nix = {
            # File should contain at least these two variables:
            # - `CI_SERVER_URL`
            # - `REGISTRATION_TOKEN`
            #
            # NOTE: Support for runner registration tokens will be removed in GitLab 18.0.
            # Please migrate to runner authentication tokens soon. For reference, the example
            # runners below this one are configured with authentication tokens instead.
            registrationConfigFile = "/run/secrets/gitlab-runner-registration";

            dockerImage = "alpine";
            dockerVolumes = [
              "/nix/store:/nix/store:ro"
              "/nix/var/nix/db:/nix/var/nix/db:ro"
              "/nix/var/nix/daemon-socket:/nix/var/nix/daemon-socket:ro"
            ];
            dockerDisableCache = true;
            preBuildScript = pkgs.writeScript "setup-container" '''
              mkdir -p -m 0755 /nix/var/log/nix/drvs
              mkdir -p -m 0755 /nix/var/nix/gcroots
              mkdir -p -m 0755 /nix/var/nix/profiles
              mkdir -p -m 0755 /nix/var/nix/temproots
              mkdir -p -m 0755 /nix/var/nix/userpool
              mkdir -p -m 1777 /nix/var/nix/gcroots/per-user
              mkdir -p -m 1777 /nix/var/nix/profiles/per-user
              mkdir -p -m 0755 /nix/var/nix/profiles/per-user/root
              mkdir -p -m 0700 "$HOME/.nix-defexpr"

              . ''${pkgs.nix}/etc/profile.d/nix.sh

              ''${pkgs.nix}/bin/nix-env -i ''${concatStringsSep " " (with pkgs; [ nix cacert git openssh ])}

              ''${pkgs.nix}/bin/nix-channel --add https://nixos.org/channels/nixpkgs-unstable
              ''${pkgs.nix}/bin/nix-channel --update nixpkgs
            ''';
            environmentVariables = {
              ENV = "/etc/profile";
              USER = "root";
              NIX_REMOTE = "daemon";
              PATH = "/nix/var/nix/profiles/default/bin:/nix/var/nix/profiles/default/sbin:/bin:/sbin:/usr/bin:/usr/sbin";
              NIX_SSL_CERT_FILE = "/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt";
            };
            tagList = [ "nix" ];
          };
          # runner for building docker images
          docker-images = {
            # File should contain at least these two variables:
            # `CI_SERVER_URL`
            # `CI_SERVER_TOKEN`
            authenticationTokenConfigFile = "/run/secrets/gitlab-runner-docker-images-token-env";

            dockerImage = "docker:stable";
            dockerVolumes = [
              "/var/run/docker.sock:/var/run/docker.sock"
            ];
            tagList = [ "docker-images" ];
          };
          # runner for executing stuff on host system (very insecure!)
          # make sure to add required packages (including git!)
          # to `environment.systemPackages`
          shell = {
            # File should contain at least these two variables:
            # `CI_SERVER_URL`
            # `CI_SERVER_TOKEN`
            authenticationTokenConfigFile = "/run/secrets/gitlab-runner-shell-token-env";

            executor = "shell";
            tagList = [ "shell" ];
          };
          # runner for everything else
          default = {
            # File should contain at least these two variables:
            # `CI_SERVER_URL`
            # `CI_SERVER_TOKEN`
            authenticationTokenConfigFile = "/run/secrets/gitlab-runner-default-token-env";
            dockerImage = "debian:stable";
          };
        }
      '';
      type = types.attrsOf (types.submodule {
        options = {
          authenticationTokenConfigFile = mkOption {
            type = with types; nullOr path;
            default = null;
            description = ''
              Absolute path to a file containing environment variables used for
              gitlab-runner registrations with *runner authentication tokens*.
              They replace the deprecated *runner registration tokens*, as
              outlined in the [GitLab documentation].

              A list of all supported environment variables can be found with
              `gitlab-runner register --help`.

              The ones you probably want to set are:
              - `CI_SERVER_URL=<CI server URL>`
              - `CI_SERVER_TOKEN=<runner authentication token secret>`

              ::: {.warning}
              Make sure to use a quoted absolute path,
              or it is going to be copied to Nix Store.
              :::

              [GitLab documentation]: https://docs.gitlab.com/17.0/ee/ci/runners/new_creation_workflow.html#estimated-time-frame-for-planned-changes
            '';
          };
          registrationConfigFile = mkOption {
            type = with types; nullOr path;
            default = null;
            description = ''
              Absolute path to a file with environment variables
              used for gitlab-runner registration with *runner registration
              tokens*.

              A list of all supported environment variables can be found in
              `gitlab-runner register --help`.

              The ones you probably want to set are:
              - `CI_SERVER_URL=<CI server URL>`
              - `REGISTRATION_TOKEN=<registration secret>`

              Support for *runner registration tokens* is deprecated since
              GitLab 16.0, has been disabled by default in GitLab 17.0 and
              will be removed in GitLab 18.0, as outlined in the
              [GitLab documentation]. Please consider migrating to
              [runner authentication tokens] and check the documentation on
              {option}`services.gitlab-runner.services.<name>.authenticationTokenConfigFile`.

              ::: {.warning}
              Make sure to use a quoted absolute path,
              or it is going to be copied to Nix Store.
              :::

              [GitLab documentation]: https://docs.gitlab.com/17.0/ee/ci/runners/new_creation_workflow.html#estimated-time-frame-for-planned-changes
              [runner authentication tokens]: https://docs.gitlab.com/17.0/ee/ci/runners/new_creation_workflow.html#the-new-runner-registration-workflow
            '';
          };
          registrationFlags = mkOption {
            type = types.listOf types.str;
            default = [ ];
            example = [ "--docker-helper-image my/gitlab-runner-helper" ];
            description = ''
              Extra command-line flags passed to
              `gitlab-runner register`.
              Execute `gitlab-runner register --help`
              for a list of supported flags.
            '';
          };
          environmentVariables = mkOption {
            type = types.attrsOf types.str;
            default = { };
            example = { NAME = "value"; };
            description = ''
              Custom environment variables injected to build environment.
              For secrets you can use {option}`registrationConfigFile`
              with `RUNNER_ENV` variable set.
            '';
          };
          description = mkOption {
            type = types.nullOr types.str;
            default = null;
            description = ''
              Name/description of the runner.
            '';
          };
          executor = mkOption {
            type = types.str;
            default = "docker";
            description = ''
              Select executor, eg. shell, docker, etc.
              See [runner documentation](https://docs.gitlab.com/runner/executors/README.html) for more information.
            '';
          };
          buildsDir = mkOption {
            type = types.nullOr types.path;
            default = null;
            example = "/var/lib/gitlab-runner/builds";
            description = ''
              Absolute path to a directory where builds will be stored
              in context of selected executor (Locally, Docker, SSH).
            '';
          };
          cloneUrl = mkOption {
            type = types.nullOr types.str;
            default = null;
            example = "http://gitlab.example.local";
            description = ''
              Overwrite the URL for the GitLab instance. Used if the Runner can’t connect to GitLab on the URL GitLab exposes itself.
            '';
          };
          dockerImage = mkOption {
            type = types.nullOr types.str;
            default = null;
            description = ''
              Docker image to be used.
            '';
          };
          dockerVolumes = mkOption {
            type = types.listOf types.str;
            default = [ ];
            example = [ "/var/run/docker.sock:/var/run/docker.sock" ];
            description = ''
              Bind-mount a volume and create it
              if it doesn't exist prior to mounting.
            '';
          };
          dockerDisableCache = mkOption {
            type = types.bool;
            default = false;
            description = ''
              Disable all container caching.
            '';
          };
          dockerPrivileged = mkOption {
            type = types.bool;
            default = false;
            description = ''
              Give extended privileges to container.
            '';
          };
          dockerExtraHosts = mkOption {
            type = types.listOf types.str;
            default = [ ];
            example = [ "other-host:127.0.0.1" ];
            description = ''
              Add a custom host-to-IP mapping.
            '';
          };
          dockerAllowedImages = mkOption {
            type = types.listOf types.str;
            default = [ ];
            example = [ "ruby:*" "python:*" "php:*" "my.registry.tld:5000/*:*" ];
            description = ''
              Whitelist allowed images.
            '';
          };
          dockerAllowedServices = mkOption {
            type = types.listOf types.str;
            default = [ ];
            example = [ "postgres:9" "redis:*" "mysql:*" ];
            description = ''
              Whitelist allowed services.
            '';
          };
          preCloneScript = mkOption {
            type = types.nullOr types.path;
            default = null;
            description = ''
              Runner-specific command script executed before code is pulled.
            '';
          };
          preBuildScript = mkOption {
            type = types.nullOr types.path;
            default = null;
            description = ''
              Runner-specific command script executed after code is pulled,
              just before build executes.
            '';
          };
          postBuildScript = mkOption {
            type = types.nullOr types.path;
            default = null;
            description = ''
              Runner-specific command script executed after code is pulled
              and just after build executes.
            '';
          };
          tagList = mkOption {
            type = types.listOf types.str;
            default = [ ];
            description = ''
              Tag list.

              This option has no effect for runners registered with an runner
              authentication tokens and will be ignored.
            '';
          };
          runUntagged = mkOption {
            type = types.bool;
            default = false;
            description = ''
              Register to run untagged builds; defaults to
              `true` when {option}`tagList` is empty.

              This option has no effect for runners registered with an runner
              authentication tokens and will be ignored.
            '';
          };
          limit = mkOption {
            type = types.int;
            default = 0;
            description = ''
              Limit how many jobs can be handled concurrently by this service.
              0 (default) simply means don't limit.
            '';
          };
          requestConcurrency = mkOption {
            type = types.int;
            default = 0;
            description = ''
              Limit number of concurrent requests for new jobs from GitLab.
            '';
          };
          maximumTimeout = mkOption {
            type = types.int;
            default = 0;
            description = ''
              What is the maximum timeout (in seconds) that will be set for
              job when using this Runner. 0 (default) simply means don't limit.

              This option has no effect for runners registered with an runner
              authentication tokens and will be ignored.
            '';
          };
          protected = mkOption {
            type = types.bool;
            default = false;
            description = ''
              When set to true Runner will only run on pipelines
              triggered on protected branches.

              This option has no effect for runners registered with an runner
              authentication tokens and will be ignored.
            '';
          };
          debugTraceDisabled = mkOption {
            type = types.bool;
            default = false;
            description = ''
              When set to true Runner will disable the possibility of
              using the `CI_DEBUG_TRACE` feature.
            '';
          };
        };
      });
    };
    clear-docker-cache = {
      enable = mkOption {
        type = types.bool;
        default = false;
        description = ''
          Whether to periodically prune gitlab runner's Docker resources. If
          enabled, a systemd timer will run {command}`clear-docker-cache` as
          specified by the `dates` option.
        '';
      };

      flags = mkOption {
        type = types.listOf types.str;
        default = [ ];
        example = [ "prune" ];
        description = ''
          Any additional flags passed to {command}`clear-docker-cache`.
        '';
      };

      dates = mkOption {
        default = "weekly";
        type = types.str;
        description = ''
          Specification (in the format described by
          {manpage}`systemd.time(7)`) of the time at
          which the prune will occur.
        '';
      };

      package = mkOption {
        default = config.virtualisation.docker.package;
        defaultText = literalExpression "config.virtualisation.docker.package";
        example = literalExpression "pkgs.docker";
        description = "Docker package to use for clearing up docker cache.";
      };
    };
  };
  config = mkIf cfg.enable {
    assertions =
      mapAttrsToList (name: serviceConfig: {
        assertion = serviceConfig.registrationConfigFile == null || serviceConfig.authenticationTokenConfigFile == null;
        message = "`services.gitlab-runner.${name}.registrationConfigFile` and `services.gitlab-runner.services.${name}.authenticationTokenConfigFile` are mutually exclusive.";
      }) cfg.services;

    warnings =
      mapAttrsToList
        (name: serviceConfig: "services.gitlab-runner.services.${name}.`registrationConfigFile` points to a file in Nix Store. You should use quoted absolute path to prevent this.")
        (filterAttrs (name: serviceConfig: isStorePath serviceConfig.registrationConfigFile) cfg.services)
      ++ mapAttrsToList
        (name: serviceConfig: "services.gitlab-runner.services.${name}.`authenticationTokenConfigFile` points to a file in Nix Store. You should use quoted absolute path to prevent this.")
        (filterAttrs (name: serviceConfig: isStorePath serviceConfig.authenticationTokenConfigFile) cfg.services)
      ++ mapAttrsToList
        (name: serviceConfig: ''
          Runner registration tokens have been deprecated and disabled by default in GitLab >= 17.0.
          Consider migrating to runner authentication tokens by setting `services.gitlab-runner.services.${name}.authenticationTokenConfigFile`.
          https://docs.gitlab.com/17.0/ee/ci/runners/new_creation_workflow.html''
        )
        (
          filterAttrs (name: serviceConfig:
            serviceConfig.authenticationTokenConfigFile == null
          ) cfg.services
        )
      ++ mapAttrsToList
        (name: serviceConfig: ''
          `services.gitlab-runner.services.${name}.protected` with runner authentication tokens has no effect and will be ignored. Please remove it from your configuration.''
        )
        (
          filterAttrs (name: serviceConfig:
            serviceConfig.authenticationTokenConfigFile != null && serviceConfig.protected == true
          ) cfg.services
        )
      ++ mapAttrsToList
        (name: serviceConfig: ''
          `services.gitlab-runner.services.${name}.runUntagged` with runner authentication tokens has no effect and will be ignored. Please remove it from your configuration.''
        )
        (
          filterAttrs (name: serviceConfig:
            serviceConfig.authenticationTokenConfigFile != null && serviceConfig.runUntagged == true
          ) cfg.services
        )
      ++ mapAttrsToList
        (name: v: ''
          `services.gitlab-runner.services.${name}.maximumTimeout` with runner authentication tokens has no effect and will be ignored. Please remove it from your configuration.''
        )
        (
          filterAttrs (name: serviceConfig:
            serviceConfig.authenticationTokenConfigFile != null && serviceConfig.maximumTimeout != 0
          ) cfg.services
        )
      ++ mapAttrsToList
        (name: v: ''
          `services.gitlab-runner.services.${name}.tagList` with runner authentication tokens has no effect and will be ignored. Please remove it from your configuration.''
        )
        (
          filterAttrs (serviceName: serviceConfig:
            serviceConfig.authenticationTokenConfigFile != null && serviceConfig.tagList != [ ]
          ) cfg.services
        )
      ;

    environment.systemPackages = [ cfg.package ];
    systemd.services.gitlab-runner = {
      description = "Gitlab Runner";
      documentation = [ "https://docs.gitlab.com/runner/" ];
      after = [ "network.target" ]
        ++ optional hasDocker "docker.service";
      requires = optional hasDocker "docker.service";
      wantedBy = [ "multi-user.target" ];
      environment = config.networking.proxy.envVars // {
        HOME = "/var/lib/gitlab-runner";
      };

      path =
        (with pkgs; [
          bash
          gawk
          jq
          moreutils
          remarshal
          util-linux
        ])
        ++ [ cfg.package ]
        ++ cfg.extraPackages;

      reloadIfChanged = true;
      serviceConfig = {
        # Set `DynamicUser` under `systemd.services.gitlab-runner.serviceConfig`
        # to `lib.mkForce false` in your configuration to run this service as root.
        # You can also set `User` and `Group` options to run this service as desired user.
        # Make sure to restart service or changes won't apply.
        DynamicUser = true;
        StateDirectory = "gitlab-runner";
        SupplementaryGroups = optional hasDocker "docker";
        ExecStartPre = "!${configureScript}/bin/gitlab-runner-configure";
        ExecStart = "${startScript}/bin/gitlab-runner-start";
        ExecReload = "!${configureScript}/bin/gitlab-runner-configure";
      } // optionalAttrs cfg.gracefulTermination {
        TimeoutStopSec = "${cfg.gracefulTimeout}";
        KillSignal = "SIGQUIT";
        KillMode = "process";
      };
    };
    # Enable periodic clear-docker-cache script
    systemd.services.gitlab-runner-clear-docker-cache = mkIf (cfg.clear-docker-cache.enable && (any (s: s.executor == "docker") (attrValues cfg.services))) {
      description = "Prune gitlab-runner docker resources";
      restartIfChanged = false;
      unitConfig.X-StopOnRemoval = false;

      serviceConfig.Type = "oneshot";

      path = [ cfg.clear-docker-cache.package pkgs.gawk ];

      script = ''
        ${pkgs.gitlab-runner}/bin/clear-docker-cache ${toString cfg.clear-docker-cache.flags}
      '';

      startAt = cfg.clear-docker-cache.dates;
    };
    # Enable docker if `docker` executor is used in any service
    virtualisation.docker.enable = mkIf (
      any (s: s.executor == "docker") (attrValues cfg.services)
    ) (mkDefault true);
  };
  imports = [
    (mkRenamedOptionModule [ "services" "gitlab-runner" "packages" ] [ "services" "gitlab-runner" "extraPackages" ] )
    (mkRemovedOptionModule [ "services" "gitlab-runner" "configOptions" ] "Use services.gitlab-runner.services option instead" )
    (mkRemovedOptionModule [ "services" "gitlab-runner" "workDir" ] "You should move contents of workDir (if any) to /var/lib/gitlab-runner" )

    (mkRenamedOptionModule [ "services" "gitlab-runner" "checkInterval" ] [ "services" "gitlab-runner" "settings" "check_interval" ] )
    (mkRenamedOptionModule [ "services" "gitlab-runner" "concurrent" ] [ "services" "gitlab-runner" "settings" "concurrent" ] )
    (mkRenamedOptionModule [ "services" "gitlab-runner" "sentryDSN" ] [ "services" "gitlab-runner" "settings" "sentry_dsn" ] )
    (mkRenamedOptionModule [ "services" "gitlab-runner" "prometheusListenAddress" ] [ "services" "gitlab-runner" "settings" "listen_address" ] )

    (mkRenamedOptionModule [ "services" "gitlab-runner" "sessionServer" "listenAddress" ] [ "services" "gitlab-runner" "settings" "session_server" "listen_address" ] )
    (mkRenamedOptionModule [ "services" "gitlab-runner" "sessionServer" "advertiseAddress" ] [ "services" "gitlab-runner" "settings" "session_server" "advertise_address" ] )
    (mkRenamedOptionModule [ "services" "gitlab-runner" "sessionServer" "sessionTimeout" ] [ "services" "gitlab-runner" "settings" "session_server" "session_timeout" ] )
  ];

  meta.maintainers = teams.gitlab.members;
}