ansible-infra/roles/common/files/sftp/push_public_key.sh

33 lines
690 B
Bash
Raw Normal View History

2020-11-28 20:47:30 +01:00
#!/bin/bash -e
function usage {
echo "Usage: $0 <host> <public key file>"
}
host="$1"
public_key_file="$2"
if [[ $# -ne 2 ]]; then
>&2 usage
exit 1
fi
authorized_keys_file="/tmp/${host}-authorized_keys"
sshpass -e sftp "${host}" <<-EOF
mkdir .ssh
chmod 0700 .ssh
get .ssh/authorized_keys "${authorized_keys_file}"
EOF
if grep -f "${public_key_file}" "${authorized_keys_file}" > /dev/null; then
exit 0
fi
echo "Adding public key '${public_key_file}' for ${host}"
sshpass -e sftp "${host}" <<-EOF
!cat "${public_key_file}" >> "${authorized_keys_file}"
put "${authorized_keys_file}" .ssh/authorized_keys
chmod 0600 .ssh/authorized_keys
EOF
echo "Public key added!"