aboutsummaryrefslogtreecommitdiff
path: root/tests/nixos/containers/systemd-nspawn.nix
blob: f54f32f2af5fd33624b1a974487afdee600e7b02 (plain)
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
{ nixpkgs }:

let

  machine = { config, pkgs, ... }:
    {
      system.stateVersion = "22.05";
      boot.isContainer = true;
      systemd.services.console-getty.enable = false;
      networking.dhcpcd.enable = false;

      services.httpd = {
        enable = true;
        adminAddr = "nixos@example.org";
      };

      systemd.services.test = {
        wantedBy = [ "multi-user.target" ];
        after = [ "httpd.service" ];
        script = ''
          source /.env
          echo "Hello World" > $out/msg
          ls -lR /dev > $out/dev
          ${pkgs.curl}/bin/curl -sS --fail http://localhost/ > $out/page.html
        '';
        unitConfig = {
          FailureAction = "exit-force";
          FailureActionExitStatus = 42;
          SuccessAction = "exit-force";
        };
      };
    };

  cfg = (import (nixpkgs + "/nixos/lib/eval-config.nix") {
    modules = [ machine ];
    system = "x86_64-linux";
  });

  config = cfg.config;

in

with cfg._module.args.pkgs;

runCommand "test"
  { buildInputs = [ config.system.path ];
    requiredSystemFeatures = [ "uid-range" ];
    toplevel = config.system.build.toplevel;
  }
  ''
    root=$(pwd)/root
    mkdir -p $root $root/etc

    export > $root/.env

    # Make /run a tmpfs to shut up a systemd warning.
    mkdir /run
    mount -t tmpfs none /run

    mount -t cgroup2 none /sys/fs/cgroup

    mkdir -p $out

    chmod +w /etc
    touch /etc/os-release
    echo a5ea3f98dedc0278b6f3cc8c37eeaeac > /etc/machine-id

    SYSTEMD_NSPAWN_UNIFIED_HIERARCHY=1 \
      ${config.systemd.package}/bin/systemd-nspawn \
      --keep-unit \
      -M ${config.networking.hostName} -D "$root" \
      --register=no \
      --resolv-conf=off \
      --bind-ro=/nix/store \
      --bind=$out \
      --private-network \
      $toplevel/init
  ''