Skip to content

with-ssh-key: unlock ssh keys for the duration of a command

Some commands require access to the ssh keys in a non-interactive context. This is a problem when your keys are password protected. I was quite surprised there is no standard solution for this, so here's a quick script.

The problem

I want to run colmena apply to update my servers. That's great normally, but it fails since it can't unlock the ssh keys.

devshell ➜   colmena apply
...
ERROR Failed to push system closure to houre - Last 5 lines of logs:
ERROR  created)
ERROR    state) Running
ERROR   stderr) root@<snip>: Permission denied (publickey).
ERROR   stderr) error: failed to start SSH connection to '<snip>'
ERROR  failure) Child process exited with error code: 1
ERROR -----
ERROR Operation failed with error: Child process exited with error code: 1
Hint: Backtrace available - Use `RUST_BACKTRACE=1` environment variable to display a backtrace

I could load the keys to my ssh agent directly, but that's not desirable since those are then available for all programs on the entire system until the agent is killed. I could manually start a new ssh-agent and load it into that, but then I need to remember to kill it or the current shell session stays insecure.

This script lets you load the keys for just the duration of a single command, without accidentally leaking them to other contexts.

devshell ➜  with-ssh-key colmena apply
Enter passphrase for /Users/.../.ssh/id_ed25519:
 INFO Enumerating nodes...
 INFO Selected all 1 nodes.
houre ✅ 3s Evaluated
houre ✅ 0s Built "/nix/store/5jx36j0djvjv22szcdfnm9684cc896hr-nixos-system-houre-26.05pre-git"
houre ✅ 1s Pushed system closure
houre ✅ 2s Activation successful

The script

#!/usr/bin/env zsh
set -euo pipefail

usage() {
    print -u2 "Usage: ${0:t} [-k key]... [--] [command [args...]]"
}

keys=()
while getopts "k:h" opt; do
    case $opt in
        k) keys+=("$OPTARG") ;;
        h) usage; exit 0 ;;
        *) usage; exit 2 ;;
    esac
done
shift $((OPTIND - 1))

(( $# )) || set -- "${SHELL:-zsh}"

eval "$(ssh-agent -s)" >/dev/null
trap 'ssh-agent -k >/dev/null 2>&1 || true' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP

ssh-add -q "${keys[@]}"

"$@"