Skip to content

Commit 1b21ec5

Browse files
committed
get_ssh_key: add support for SSH key field "name"
1 parent 07ffea7 commit 1b21ec5

File tree

1 file changed

+20
-19
lines changed

1 file changed

+20
-19
lines changed

bin/get_ssh_key

+20-19
Original file line numberDiff line numberDiff line change
@@ -7,48 +7,49 @@ set -euo pipefail
77
# $ get_ssh_key "Personal" "git commit signing key"
88

99
vault_name="${1:-}"
10-
key_name="${2:-}"
10+
item_name="${2:-}"
1111

1212
if [ -z "$vault_name" ]; then
1313
echo "vault_name not passed as 1st argument. Nothing was done."
1414
exit 1
1515
fi
1616

17-
if [ -z "$key_name" ]; then
18-
echo "key_name not passed as 2nd argument. Nothing was done."
17+
if [ -z "$item_name" ]; then
18+
echo "item_name not passed as 2nd argument. Nothing was done."
1919
exit 1
2020
fi
2121

22-
private_key_path="id_ed25519"
23-
public_key_path="id_ed25519.pub"
22+
# First try to get custom key name.
23+
private_key_name="$(op read "op://$vault_name/$item_name/name" 2>/dev/null || printf "id_ed25519")"
24+
public_key_name="$private_key_name.pub"
2425

25-
if [ -f "$private_key_path" ]; then
26-
echo "$private_key_path already exists. Nothing was done."
26+
if [ -f "$private_key_name" ]; then
27+
echo "$private_key_name already exists. Nothing was done."
2728
exit 2
2829
fi
2930

30-
if [ -f "public_key_path" ]; then
31-
echo "public_key_path already exists. Nothing was done."
31+
if [ -f "$public_key_name" ]; then
32+
echo "$public_key_name already exists. Nothing was done."
3233
exit 2
3334
fi
3435

3536
op read \
36-
--out-file "$private_key_path" \
37-
"op://$vault_name/$key_name/private key?ssh-format=openssh"
37+
--out-file "$private_key_name" \
38+
"op://$vault_name/$item_name/private key?ssh-format=openssh"
3839

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

4445
op read \
45-
--out-file "$public_key_path" \
46-
"op://$vault_name/$key_name/public key"
46+
--out-file "$public_key_name" \
47+
"op://$vault_name/$item_name/public key"
4748

4849
# Add a comment (if it exists)
49-
comment="$(op read "op://Personal/git commit signing key/comment" 2>/dev/null || true)"
50+
comment="$(op read "op://$vault_name/$item_name/comment" 2>/dev/null || true)"
5051
if [ -n "$comment" ]; then
51-
pubkey_content="$(tr -d '\n' < "$public_key_path")"
52-
true > "$public_key_path"
53-
printf "%s %s\n" "$pubkey_content" "$comment" > "$public_key_path"
52+
pubkey_content="$(tr -d '\n' < "$public_key_name")"
53+
true > "$public_key_name"
54+
printf "%s %s\n" "$pubkey_content" "$comment" > "$public_key_name"
5455
fi

0 commit comments

Comments
 (0)