-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthorize_ssh_key.cgr
More file actions
62 lines (55 loc) · 2.53 KB
/
authorize_ssh_key.cgr
File metadata and controls
62 lines (55 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
--- authorize local SSH key on remote hosts ---
#
# Copies your local public key to each host using ssh-copy-id.
# Each host gets its own step with independent skip-if and state tracking.
# Prompts are sequential (1 at a time) so they never collide.
#
# Usage:
# cgr apply authorize_ssh_key.cgr --set hosts="192.168.1.10,192.168.1.11"
# cgr apply authorize_ssh_key.cgr --set hosts="web01,web02,db01" --set ssh_user=admin
# cgr apply authorize_ssh_key.cgr --set hosts="host1" --set ssh_port=2222
#
# Variables:
# hosts — comma-separated list of hostnames or IPs (required)
# ssh_user — remote user (default: $USER from environment)
# ssh_port — SSH port (default: 22)
set hosts = "192.168.1.10,192.168.1.11,192.168.1.12"
set ssh_user = env("USER", "ubuntu")
set ssh_port = "22"
target "local" local:
[check prerequisites]:
run $ missing=""; \
command -v ssh-copy-id > /dev/null 2>&1 || missing="$missing ssh-copy-id"; \
command -v ssh-keyscan > /dev/null 2>&1 || missing="$missing ssh-keyscan"; \
[ -z "$missing" ] || { echo "Missing tools:$missing (install openssh-client)"; exit 1; }; \
key="$HOME/.ssh/id_ed25519.pub"; \
test -f "$key" || key="$HOME/.ssh/id_rsa.pub"; \
test -f "$key" || { echo "No public key found in ~/.ssh/. Run: ssh-keygen"; exit 1; }; \
echo "Key: $(awk '{print $1, substr($2,1,16)"...", $3}' "$key")"
timeout 5s
[authorize hosts]:
first [check prerequisites]
# 1 at a time: interactive password prompts must not run concurrently
each host in ${hosts}, 1 at a time:
[${host}]:
skip if $ ssh -o BatchMode=yes \
-o ConnectTimeout=5 \
-o StrictHostKeyChecking=no \
-p ${ssh_port} \
"${ssh_user}@${host}" true 2>/dev/null
run $ key="$HOME/.ssh/id_ed25519.pub"; \
test -f "$key" || key="$HOME/.ssh/id_rsa.pub"; \
ssh-keyscan -p ${ssh_port} -H "${host}" >> "$HOME/.ssh/known_hosts" 2>/dev/null; \
ssh-copy-id -i "$key" -p ${ssh_port} "${ssh_user}@${host}"
timeout 60s
[verify all hosts]:
first [authorize hosts]
# Run verification in parallel — no interaction needed
each host in ${hosts}:
[${host}]:
run $ ssh -o BatchMode=yes \
-o ConnectTimeout=10 \
-p ${ssh_port} \
"${ssh_user}@${host}" \
echo "OK ${host}"
timeout 15s