Skip to content

Instantly share code, notes, and snippets.

@dcosson
Last active November 26, 2015 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcosson/80d79e9919454806abb5 to your computer and use it in GitHub Desktop.
Save dcosson/80d79e9919454806abb5 to your computer and use it in GitHub Desktop.
Add private key stored in S3 to ssh-agent
#!/bin/bash
#
# Download the specified ssh private key from s3 and add it to the ssh-agent so
# we can make requests to a git remote using it.
#
# Works by piping the ascii key through a named pipe to get it from standard
# out to a file descriptor that the ssh-add utility can read. The benefit of
# this over just saving it to a tmp file is the key never touches disk.
# Parse args
if [[ "$#" -lt 1 ]]; then
echo "Usage: add_ssh_key_from_s3.sh [s3 file path]"
exit 1
fi
_private_key_s3_path="$1"
# If no agent running just exit. Error code 2 used for not running
ssh-add -l &> /dev/null
if [[ "$?" -eq 2 ]]; then
echo "No ssh-agent running, exiting"
exit 1
fi
# Make sure file downloaded successfully
_private_key_contents=$(aws s3 cp "$_private_key_s3_path" -)
if [[ "$?" -ne 0 ]];then
echo "Error downloading s3 file ${_private_key_s3_path}, exiting"
exit 1
fi
# Name the temp file based on the s3 file path
_tmp_file="$(echo -n $_private_key_s3_path | perl -C -pe 's/\W+/-/g')"
mkfifo -m 600 "$_tmp_file"
ssh-add "$_tmp_file" &
echo -e "$_private_key_contents" > "$_tmp_file"
rm "$_tmp_file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment