Skip to content

Instantly share code, notes, and snippets.

@plexus
Created June 4, 2020 07:59
Show Gist options
  • Save plexus/797cf37ed7e7d67474af3765704e0351 to your computer and use it in GitHub Desktop.
Save plexus/797cf37ed7e7d67474af3765704e0351 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Import SSH keys from Github to ~/.ssh/authorize_keys for all members of a
# given Github organization.
#
# Will replace authorized_keys, if it looks like authorized_keys was not
# previously created by this script then a backup copy is made.
#
# Depends on jq, will download it if not available (assumes Linux) to ~/bin/jq
#
# GITHUB_ORG can be set, defaults to lambdaisland
# SSH_DIR and/or KEYS_FILE can be set, default to ~/.ssh and ~/.ssh/authorized_keys
#
# Will create the SSH_DIR if it does not exist, and set permissions on dir and
# file (700 and 600 respectively).
#
# Only works when OVERWRITE_SSH_AUTHORIZED_KEYS=OK
#
# Will exit early if anything goes wrong, so authorized_keys is only touched if
# all Github API/HTTP calls succeed.
if [[ "${OVERWRITE_SSH_AUTHORIZED_KEYS}" != "OK" ]]; then
echo "CAREFUL! This script will replace your ~/.ssh/authorized_keys. If you are sure that is what you want then run it with OVERWRITE_SSH_AUTHORIZED_KEYS=OK to continue."
exit 1
fi
GITHUB_ORG=${GITHUB_ORG:-"lambdaisland"}
JQ="$(command -v jq)"
set -e
# Follow links, no extraneous output, fail (non-zero exit) on non-200 responses
CURL="curl -Ls --fail"
if [[ ! -x "$JQ" ]]; then
JQ="$HOME/bin/jq"
if [[ ! -x "$JQ" ]]; then
mkdir -p "$HOME/bin"
$CURL https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64 -o ~/bin/jq
chmod +x "$JQ"
fi
fi
MEMBERS=$($CURL "https://api.github.com/orgs/${GITHUB_ORG}/public_members")
AUTHORIZED_KEYS="# $(date)\n# Created by: ${0}\n# Imported keys for: https://github.com/${GITHUB_ORG}"
for keys_link in $(echo $MEMBERS | "$JQ" -r '.[].html_url+".keys"'); do
KEYS=$($CURL $keys_link)
AUTHORIZED_KEYS="${AUTHORIZED_KEYS}\n\n# ${keys_link}\n${KEYS}"
done
SSH_DIR=${SSH_DIR:-"$HOME/.ssh"}
mkdir -p $SSH_DIR
chmod 700 $SSH_DIR
KEYS_FILE=${KEYS_FILE:-"$SSH_DIR/authorized_keys"}
if [[ -f "$KEYS_FILE" ]] && ! grep 'Imported keys for' "$KEYS_FILE" >/dev/null; then
cp "$KEYS_FILE" "${KEYS_FILE}.$(date +'%Y%m%d_%H%M%S')"
fi
echo -e "$AUTHORIZED_KEYS" > "$KEYS_FILE"
chmod 600 "$KEYS_FILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment