1{ config, pkgs, ... }:
2
3let
4 script = ''
5 #!${pkgs.runtimeShell} -eu
6
7 echo "attempting to fetch configuration from EC2 user data..."
8
9 export HOME=/root
10 export PATH=${pkgs.lib.makeBinPath [ config.nix.package pkgs.systemd pkgs.gnugrep pkgs.gnused config.system.build.nixos-rebuild]}:$PATH
11 export NIX_PATH=/nix/var/nix/profiles/per-user/root/channels/nixos:nixos-config=/etc/nixos/configuration.nix:/nix/var/nix/profiles/per-user/root/channels
12
13 userData=/etc/ec2-metadata/user-data
14
15 if [ -s "$userData" ]; then
16 # If the user-data looks like it could be a nix expression,
17 # copy it over. Also, look for a magic three-hash comment and set
18 # that as the channel.
19 if sed '/^\(#\|SSH_HOST_.*\)/d' < "$userData" | grep -q '\S'; then
20 channels="$(grep '^###' "$userData" | sed 's|###\s*||')"
21 printf "%s" "$channels" | while read channel; do
22 echo "writing channel: $channel"
23 done
24
25 if [[ -n "$channels" ]]; then
26 printf "%s" "$channels" > /root/.nix-channels
27 nix-channel --update
28 fi
29
30 echo "setting configuration from EC2 user data"
31 cp "$userData" /etc/nixos/configuration.nix
32 else
33 echo "user data does not appear to be a Nix expression; ignoring"
34 exit
35 fi
36 else
37 echo "no user data is available"
38 exit
39 fi
40
41 nixos-rebuild switch
42 '';
43in {
44 systemd.services.amazon-init = {
45 inherit script;
46 description = "Reconfigure the system from EC2 userdata on startup";
47
48 wantedBy = [ "multi-user.target" ];
49 after = [ "multi-user.target" ];
50 requires = [ "network-online.target" ];
51
52 restartIfChanged = false;
53 unitConfig.X-StopOnRemoval = false;
54
55 serviceConfig = {
56 Type = "oneshot";
57 RemainAfterExit = true;
58 };
59 };
60}
61