From 437193219337831201725116d3e6c0e639115ef9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jean-Fran=C3=A7ois=20Roche?= Date: Fri, 31 Mar 2023 11:54:44 +0200 Subject: [PATCH] fix(rebuild): use sudo if rebuild with another user than root In order to switch the NixOS configuration, we must have root access. If we are connecting to the target host with a non-root user, we use the "sudo" command. We could instead use `nixos-rebuild --use-remote-sudo --target-host` but it would evaluate the nixos system again. --- terraform/nixos-rebuild/deploy.sh | 19 +++++++++++++------ terraform/nixos-rebuild/main.tf | 2 +- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/terraform/nixos-rebuild/deploy.sh b/terraform/nixos-rebuild/deploy.sh index 1ffcf89..841e793 100755 --- a/terraform/nixos-rebuild/deploy.sh +++ b/terraform/nixos-rebuild/deploy.sh @@ -2,16 +2,19 @@ set -uex -o pipefail -if [ "$#" -ne 3 ]; then - echo "USAGE: $0 NIXOS_SYSTEM TARGET_HOST TARGET_PORT" >&2 +if [ "$#" -ne 4 ]; then + echo "USAGE: $0 NIXOS_SYSTEM TARGET_USER TARGET_HOST TARGET_PORT" >&2 exit 1 fi NIXOS_SYSTEM=$1 -TARGET_HOST=$2 -TARGET_PORT=$3 +TARGET_USER=$2 +TARGET_HOST=$3 +TARGET_PORT=$4 shift 3 +TARGET="${TARGET_USER}@${TARGET_HOST}" + workDir=$(mktemp -d) trap 'rm -rf "$workDir"' EXIT @@ -31,7 +34,7 @@ if [[ -n ${SSH_KEY+x} && ${SSH_KEY} != "-" ]]; then fi try=1 -until NIX_SSHOPTS="${sshOpts[*]}" nix copy -s --experimental-features nix-command --to "ssh://$TARGET_HOST" "$NIXOS_SYSTEM"; do +until NIX_SSHOPTS="${sshOpts[*]}" nix copy -s --experimental-features nix-command --to "ssh://$TARGET" "$NIXOS_SYSTEM"; do if [[ $try -gt 10 ]]; then echo "retries exhausted" >&2 exit 1 @@ -40,5 +43,9 @@ until NIX_SSHOPTS="${sshOpts[*]}" nix copy -s --experimental-features nix-comman try=$((try + 1)) done +switchCommand="nix-env -p /nix/var/nix/profiles/system --set $(printf "%q" "$NIXOS_SYSTEM"); /nix/var/nix/profiles/system/bin/switch-to-configuration switch" +if [[ $TARGET_USER != "root" ]]; then + switchCommand="sudo bash -c '$switchCommand'" +fi # shellcheck disable=SC2029 -ssh "${sshOpts[@]}" "$TARGET_HOST" "nix-env -p /nix/var/nix/profiles/system --set $(printf "%q" "$NIXOS_SYSTEM"); /nix/var/nix/profiles/system/bin/switch-to-configuration switch" || : +ssh "${sshOpts[@]}" "$TARGET" "$switchCommand" diff --git a/terraform/nixos-rebuild/main.tf b/terraform/nixos-rebuild/main.tf index c70c9db..a8f6443 100644 --- a/terraform/nixos-rebuild/main.tf +++ b/terraform/nixos-rebuild/main.tf @@ -7,6 +7,6 @@ resource "null_resource" "nixos-rebuild" { SSH_KEY = var.ssh_private_key } - command = "${path.module}/deploy.sh ${var.nixos_system} ${var.target_user}@${var.target_host} ${var.target_port}" + command = "${path.module}/deploy.sh ${var.nixos_system} ${var.target_user} ${var.target_host} ${var.target_port}" } }