Created
December 31, 2019 13:17
-
-
Save nlewo/1565173dab9d948d38b6aa0fa3485568 to your computer and use it in GitHub Desktop.
nixos-deploy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env nix-shell | |
#!nix-shell -p coreutils openssh -i bash | |
# | |
# nixos-deploy deploys nix expression to a target host | |
# | |
# Usage: nixos-deploy.sh <host> <switch-action> <nix-opts> | |
set -euo pipefail | |
### Defaults ### | |
profile=/nix/var/nix/profiles/system | |
### Functions ### | |
log() { | |
echo "--- $*" >&2 | |
} | |
copyToTarget() { | |
echo nix-copy-closure -s --gzip --to "$targetHost" "$@" | |
nix-copy-closure -s --gzip --to "$targetHost" "$@" | |
} | |
### Main ### | |
# Argument parsing | |
targetHost="$1" | |
action="$2" | |
shift | |
shift | |
# Build derivation | |
log "building nix code" | |
outPath=$(nix-build $@) | |
# This is to keep a gcroot for all machines | |
# The output result link looks like: | |
# /nix/store/ndlfs6w5va5mb81f0ccgq6wj3js633wb-nixos-system-tilia-19.09.git.b62916a | |
# We extract the system name from it to generate the link | |
MACHINE=$(realpath ./result | cut -d"-" -f 4) | |
mv -T ./result result-$MACHINE | |
# Upload build results | |
if [[ $targetHost != localhost ]] | |
then | |
log "uploading build results" | |
copyToTarget "$outPath" | |
fi | |
# Upload keys | |
if [[ $targetHost != localhost ]] | |
then | |
log "get keys from pass" | |
KEYS=$(pass show $MACHINE/keys.json | base64) | |
log "copy keys.json to $targetHost" | |
ssh $targetHost -T << EOF | |
mkdir -p /var/keys | |
chmod 0611 /var/keys | |
echo "$KEYS" | base64 -d > /var/keys/keys.json | |
chmod 0600 /var/keys/keys.json | |
EOF | |
fi | |
# Activate | |
log "activating configuration" | |
if [[ $targetHost != localhost ]] | |
then | |
ssh $targetHost nix-env --profile "$profile" --set "$outPath" | |
ssh $targetHost "$outPath/bin/switch-to-configuration" "$action" | |
else | |
sudo nix-env --profile "$profile" --set "$outPath" | |
sudo "$outPath/bin/switch-to-configuration" "$action" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment