1{ config, pkgs, modulesPath, ... }: 2 3# This attempts to pull a nix expression from this EC2 instance's user-data. 4 5let 6 bootScript = pkgs.writeScript "bootscript.sh" '' 7 #!${pkgs.stdenv.shell} -eu 8 9 echo "attempting to fetch configuration from EC2 user data..." 10 11 export PATH=${config.nix.package}/bin:${pkgs.systemd}/bin:${pkgs.gnugrep}/bin:${pkgs.gnused}/bin:${config.system.build.nixos-rebuild}/bin:$PATH 12 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 13 14 userData=/etc/ec2-metadata/user-data 15 16 if [ -s "$userData" ]; then 17 18 # If the user-data looks like it could be a nix expression, 19 # copy it over. Also, look for a magic three-hash comment and set 20 # that as the channel. 21 if sed '/^\(#\|SSH_HOST_.*\)/d' < "$userData" | grep -q '\S'; then 22 channels="$(grep '^###' "$userData" | sed 's|###\s*||')" 23 printf "%s" "$channels" | while read channel; do 24 echo "writing channel: $channel" 25 done 26 27 if [[ -n "$channels" ]]; then 28 printf "%s" "$channels" > /root/.nix-channels 29 nix-channel --update 30 fi 31 32 echo "setting configuration from EC2 user data" 33 cp "$userData" /etc/nixos/configuration.nix 34 else 35 echo "user data does not appear to be a Nix expression; ignoring" 36 exit 37 fi 38 else 39 echo "no user data is available" 40 exit 41 fi 42 43 nixos-rebuild switch 44 ''; 45in { 46 boot.postBootCommands = '' 47 ${bootScript} & 48 ''; 49}