aboutsummaryrefslogtreecommitdiff
path: root/sshtool
blob: 24c19af3930a7005b555d320b687f8ea2250e6d0 (plain) (blame)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#!/usr/bin/env bash

CMDFILE="$1"
if [ -z "$CMDFILE" ] || [ ! -f "$CMDFILE" ]; then
	echo "sshtool is not meant to be called on its own."
	echo "See scripts that use it (e.g. deploy_nixos) for usage examples."
	exit 1
fi
shift 1

cd $(dirname $CMDFILE)
CMDFILE=./$(basename $CMDFILE)

CLUSTER="$1"
if [ -z "$CLUSTER" ] || [ ! -d "cluster/$CLUSTER" ]; then
	echo "Usage: $CMDFILE <cluster name>"
	echo "The cluster name must be the name of a subdirectory of cluster/"
	exit 1
fi
shift 1

if [ -z "$1" ]; then
	NIXHOSTLIST=$(ls cluster/$CLUSTER/node | grep '\.nix$' | grep -v '\.site\.')
else
	NIXHOSTLIST="$@"
fi

if [ -z "$ROOT_PASS" ]; then
	read -s -p "Enter remote sudo password: " ROOT_PASS
	echo
fi

SSH_CONFIG=cluster/$CLUSTER/ssh_config

function header {
	cat <<EOF
export DEPLOYTOOL_ROOT_PASSWORD="$ROOT_PASS"
cat > /tmp/deploytool_askpass <<EOG
#!/usr/bin/env sh
echo "\$DEPLOYTOOL_ROOT_PASSWORD"
EOG
chmod +x /tmp/deploytool_askpass
export SUDO_ASKPASS=/tmp/deploytool_askpass
sudo -A sh - <<'EOEVERYTHING'
set -e
EOF
}

function footer {
	echo EOEVERYTHING
	echo rm /tmp/deploytool_askpass
}

function message {
	echo "base64 -d <<EOG"
	echo "$@" | base64
	echo "EOG"
}

function cmd {
	echo "echo '- run $@'"
	echo "$@"
}

function set_env {
	echo "echo '- set $@'"
	echo "export $@"
}

function copy {
	local FROM=$1
	local TO=$2
	cat <<EOF
echo '- write $TO from $FROM'
base64 -d <<EOG | tee $TO > /dev/null
$(base64 <$FROM)
EOG
EOF
}

function copy_secret {
	local FROM=$1
	local TO=$2
	cat <<EOF
echo '- write secret $TO from $FROM'
base64 -d <<EOG | tee $TO > /dev/null
$(base64 <$FROM)
EOG
chown root:root $TO
chmod 0600 $TO
EOF
}

function write_pass {
	local PASSKEY=$1
	local TO=$2
	cat <<EOF
echo '- write secret $TO from pass $PASSKEY'
base64 -d <<EOG | tee $TO > /dev/null
$(pass $PASSKEY | base64)
EOG
chown root:root $TO
chmod 0600 $TO
EOF
}

function pipe_pass {
	local PASSKEY=$1
	local CMD=$2
	cat <<EOF
echo '- pipe secret $PASSKEY to command $CMD'
base64 -d <<EOG | $CMD > /dev/null
$(pass $PASSKEY | base64)
EOG
EOF
}

for NIXHOST in $NIXHOSTLIST; do
	NIXHOST=${NIXHOST%.*}

	if [ -z "$SSH_USER" ]; then
		SSH_DEST=$NIXHOST
	else
		SSH_DEST=$SSH_USER@$NIXHOST
	fi

	echo "==== DOING $NIXHOST ===="

	(header; . $CMDFILE; footer) | ssh -F $SSH_CONFIG $SSH_DEST sh -
done