Skip to content

Commit

Permalink
improve get_ssh_key
Browse files Browse the repository at this point in the history
  • Loading branch information
bartekpacia committed Nov 19, 2023
1 parent 69d2f1c commit 5fe246e
Showing 1 changed file with 41 additions and 8 deletions.
49 changes: 41 additions & 8 deletions bin/get_ssh_key
Original file line number Diff line number Diff line change
@@ -1,23 +1,56 @@
#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$0")"

# This file contains functions that make it easier to for me to
# access my SSH and GPG keys on a new machine.
# access my SSH a new machine.
# Example usage:
# $ get_ssh_key "id_rsa_raspi"
# $ get_ssh_key "Personal" "git commit signing key"

vault_name="${1:-}"
key_name="${2:-}"

key_name="${1:-}"
if [ -z "$vault_name" ]; then
echo "vault_name not passed as 1st argument. Nothing was done."
exit 1
fi

if [ -z "$key_name" ]; then
echo "key_name not passed as argument. Nothing was done."
echo "key_name not passed as 2nd argument. Nothing was done."
exit 1
fi

key_path="$HOME/.ssh/$key_name"
private_key_path="id_ed25519"
public_key_path="id_ed25519.pub"

if [ -f "$key_path" ]; then
echo "$key_path already exists. Nothing was done to it."
if [ -f "$private_key_path" ]; then
echo "$private_key_path already exists. Nothing was done."
exit 2
fi

op document get "$key_name" >"$key_path" && chmod 400 "$key_path"
if [ -f "public_key_path" ]; then
echo "public_key_path already exists. Nothing was done."
exit 2
fi

op read \
--out-file "$private_key_path" \
"op://$vault_name/$key_name/private key?ssh-format=openssh"

# Apply workaround for:
# https://1password.community/discussion/142733/bad-characters-when-exporting-ssh-private-key-via-cli
private_key_content="$(cat "$private_key_path")"
printf "%s" "$private_key_content" | tr -d '\r' > "$private_key_path"

op read \
--out-file "$public_key_path" \
"op://$vault_name/$key_name/public key"

# Add a comment (if it exists)
comment="$(op read "op://Personal/git commit signing key/comment" 2>/dev/null || true)"
if [ -n "$comment" ]; then
pubkey_content="$(tr -d '\n' < "$public_key_path")"
true > "$public_key_path"
printf "%s %s\n" "$pubkey_content" "$comment" > "$public_key_path"
fi

0 comments on commit 5fe246e

Please sign in to comment.