2017-02-15 22:32:45 +00:00
|
|
|
{ config, pkgs, ... }:
|
2015-04-10 05:06:52 +01:00
|
|
|
|
|
|
|
let
|
2017-02-15 22:32:45 +00:00
|
|
|
script = ''
|
2018-03-01 19:38:53 +00:00
|
|
|
#!${pkgs.runtimeShell} -eu
|
2015-04-10 05:06:52 +01:00
|
|
|
|
2016-02-04 14:15:19 +00:00
|
|
|
echo "attempting to fetch configuration from EC2 user data..."
|
2015-04-10 05:06:52 +01:00
|
|
|
|
2017-02-15 22:32:45 +00:00
|
|
|
export HOME=/root
|
2016-04-24 12:00:31 +01:00
|
|
|
export PATH=${pkgs.lib.makeBinPath [ config.nix.package pkgs.systemd pkgs.gnugrep pkgs.gnused config.system.build.nixos-rebuild]}:$PATH
|
2019-12-27 19:32:12 +00:00
|
|
|
export NIX_PATH=nixpkgs=/nix/var/nix/profiles/per-user/root/channels/nixos:nixos-config=/etc/nixos/configuration.nix:/nix/var/nix/profiles/per-user/root/channels
|
2015-04-10 05:06:52 +01:00
|
|
|
|
2016-02-04 14:42:49 +00:00
|
|
|
userData=/etc/ec2-metadata/user-data
|
2015-04-10 05:06:52 +01:00
|
|
|
|
2016-02-04 14:42:49 +00:00
|
|
|
if [ -s "$userData" ]; then
|
2015-04-10 05:06:52 +01:00
|
|
|
# If the user-data looks like it could be a nix expression,
|
|
|
|
# copy it over. Also, look for a magic three-hash comment and set
|
|
|
|
# that as the channel.
|
|
|
|
if sed '/^\(#\|SSH_HOST_.*\)/d' < "$userData" | grep -q '\S'; then
|
|
|
|
channels="$(grep '^###' "$userData" | sed 's|###\s*||')"
|
2019-12-27 19:32:12 +00:00
|
|
|
while IFS= read -r channel; do
|
2015-04-10 05:06:52 +01:00
|
|
|
echo "writing channel: $channel"
|
2019-12-27 19:32:12 +00:00
|
|
|
done < <(printf "%s\n" "$channels")
|
2015-04-10 05:06:52 +01:00
|
|
|
|
|
|
|
if [[ -n "$channels" ]]; then
|
|
|
|
printf "%s" "$channels" > /root/.nix-channels
|
|
|
|
nix-channel --update
|
|
|
|
fi
|
|
|
|
|
2016-02-04 14:15:19 +00:00
|
|
|
echo "setting configuration from EC2 user data"
|
2015-04-10 05:06:52 +01:00
|
|
|
cp "$userData" /etc/nixos/configuration.nix
|
|
|
|
else
|
2016-02-04 14:15:19 +00:00
|
|
|
echo "user data does not appear to be a Nix expression; ignoring"
|
|
|
|
exit
|
2015-04-10 05:06:52 +01:00
|
|
|
fi
|
|
|
|
else
|
2016-02-04 14:42:49 +00:00
|
|
|
echo "no user data is available"
|
2016-02-04 14:15:19 +00:00
|
|
|
exit
|
2015-04-10 05:06:52 +01:00
|
|
|
fi
|
|
|
|
|
|
|
|
nixos-rebuild switch
|
|
|
|
'';
|
|
|
|
in {
|
2017-02-15 22:32:45 +00:00
|
|
|
systemd.services.amazon-init = {
|
|
|
|
inherit script;
|
|
|
|
description = "Reconfigure the system from EC2 userdata on startup";
|
|
|
|
|
2017-02-27 16:51:36 +00:00
|
|
|
wantedBy = [ "multi-user.target" ];
|
|
|
|
after = [ "multi-user.target" ];
|
2017-02-15 22:32:45 +00:00
|
|
|
requires = [ "network-online.target" ];
|
|
|
|
|
|
|
|
restartIfChanged = false;
|
|
|
|
unitConfig.X-StopOnRemoval = false;
|
|
|
|
|
|
|
|
serviceConfig = {
|
|
|
|
Type = "oneshot";
|
|
|
|
RemainAfterExit = true;
|
|
|
|
};
|
|
|
|
};
|
2015-04-10 05:06:52 +01:00
|
|
|
}
|
2017-02-15 22:32:45 +00:00
|
|
|
|