Add script to provision SSH keys
This commit is contained in:
69
provisioners/setup-ssh-key.sh
Executable file
69
provisioners/setup-ssh-key.sh
Executable file
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env bash
|
||||
# This script allows SSH keys to be stored off the vagrant machine in a persistent directory and consistently restored
|
||||
|
||||
# These key location were chosen based off of current practices by the PV team
|
||||
key_locations=(
|
||||
"/media/data"
|
||||
"/media/data/keys"
|
||||
)
|
||||
preferred_key_location=${key_locations[1]}
|
||||
|
||||
# These key types and their order are based on the order in which ssh will try to use them
|
||||
key_types=(
|
||||
"id_rsa"
|
||||
"id_dsa"
|
||||
"id_ecdsa"
|
||||
"id_ed25519"
|
||||
)
|
||||
|
||||
# The place where ssh keys are ultimately place
|
||||
key_destination=/home/vagrant/.ssh
|
||||
mkdir -p ${key_destination}
|
||||
|
||||
# Track if a key has been found
|
||||
key_found=""
|
||||
for location in "${key_locations[@]}"; do
|
||||
for key in "${key_types[@]}"; do
|
||||
pubkey="${key}.pub" # Check for public keys too
|
||||
|
||||
if [ -r "${location}/${key}" ] && [ -r "${location}/${pubkey}" ]; then
|
||||
key_found="true"
|
||||
key_path=${location}/${key}
|
||||
pub_key_path=${location}/${pubkey}
|
||||
fi
|
||||
|
||||
# Copy keys and append public key to authorized keys
|
||||
if [ "${key_path}" ] && [ "${pub_key_path}" ]; then
|
||||
cp "${key_path}" ~vagrant/.ssh/
|
||||
cp "${pub_key_path}" ~vagrant/.ssh/
|
||||
chmod 600 ~vagrant/.ssh/"$(basename "${pub_key_path}")" ~vagrant/.ssh/"$(basename "${key_path}")"
|
||||
public_key=$(cat "${pub_key_path}")
|
||||
if grep -q "${public_key}" ~vagrant/.ssh/authorized_keys; then
|
||||
echo "Public key was found in authorized_keys file, skipping addition of this key..."
|
||||
else
|
||||
echo "Public key was not found in authorized_keys file, adding this key..."
|
||||
cat "${pub_key_path}" >> ~vagrant/.ssh/authorized_keys
|
||||
fi
|
||||
fi
|
||||
done
|
||||
if [ ${key_found} ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
# If no key is found, generate a passwordless rsa key and move it to /d/keys
|
||||
if [ ! ${key_found} ]; then
|
||||
echo "No key found in known key locations."
|
||||
echo "Creating ~/.ssh/id_rsa and ~/.ssh/id_rsa.pub and copying to /d/keys"
|
||||
ssh-keygen -b 4096 -f ~vagrant/.ssh/id_rsa -N ""
|
||||
if [ -r "${preferred_key_location}" ]; then
|
||||
mkdir -p ${preferred_key_location}
|
||||
cp ~vagrant/.ssh/id_rsa ${preferred_key_location}
|
||||
cp ~vagrant/.ssh/id_rsa.pub ${preferred_key_location}
|
||||
cat ~vagrant/.ssh/id_rsa.pub >> ~vagrant/.ssh/authorized_hosts
|
||||
else
|
||||
echo "The preferred directory '${preferred_key_location}' directory doesn't exist."
|
||||
echo "Something must be real messed up, bailing out"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
Reference in New Issue
Block a user