Skip to content

Instantly share code, notes, and snippets.

@lleger
Created April 4, 2019 18:42
Show Gist options
  • Save lleger/6947bdecddac6563a05ead204d95af8e to your computer and use it in GitHub Desktop.
Save lleger/6947bdecddac6563a05ead204d95af8e to your computer and use it in GitHub Desktop.
Sync SSH keys from an S3 bucket
#!/bin/sh -e
AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION:-us-west-1}
S3_BUCKET=team-ssh-keys
SSH_USER=${SSH_USER:-ubuntu}
MARKER="# KEYS_BELOW_MANAGED_BY_TEAM_SSH_KEYS"
KEYS_FILE=/home/$SSH_USER/.ssh/authorized_keys
TEMP_KEYS_FILE=$(mktemp /tmp/authorized_keys.XXXXXX)
PUB_KEYS_DIR=/home/$SSH_USER/.ssh/team_ssh_keys
mkdir -p "$PUB_KEYS_DIR"
# Add marker, if not present, and copy existing keys
grep -Fxq "$MARKER" "$KEYS_FILE" || printf "\\n%s\\n" "$MARKER" >> "$KEYS_FILE"
line=$(grep -n "$MARKER" "$KEYS_FILE" | cut -d ":" -f 1)
head -n "$line" "$KEYS_FILE" > "$TEMP_KEYS_FILE"
# Synchronize keys from bucket
aws s3 sync --delete --exact-timestamps \
s3://${S3_BUCKET}/internal --region "$AWS_DEFAULT_REGION" "$PUB_KEYS_DIR" \
--sse aws:kms
for filename in "$PUB_KEYS_DIR"/*; do
[ -f "$filename" ] || continue
sed 's/\n\?$/\n/' < "$filename" >> "$TEMP_KEYS_FILE"
done
# Move the new authorized keys in place
mv "$TEMP_KEYS_FILE" "$KEYS_FILE"
chown -R "$SSH_USER":"$SSH_USER" /home/$SSH_USER/.ssh
chmod 600 "$KEYS_FILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment