Skip to content

Instantly share code, notes, and snippets.

@tyru
Last active September 4, 2016 11:21
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 tyru/a0cfa08978e9138ee506bf7d944a3d40 to your computer and use it in GitHub Desktop.
Save tyru/a0cfa08978e9138ee506bf7d944a3d40 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -eu
set -x
KEY_COPY_DEST_DIR=/mnt/to/sshkeys/dir
GITLAB_HOST=gitlab-root.url
GITLAB_HOST_LIST='gitlabA gitlabB gitlabC'
GITLAB_GIT_REMOTE=git@${GITLAB_HOST}:etckeeper/etckeeper-$(hostname).git
get_gitlab_ip_list() {
local host
for host in $GITLAB_HOST $GITLAB_HOST_LIST; do
getent hosts $host || true
done | awk '$0=$1' | sort -u | paste -d , -s
}
if [ "$(id -u)" -ne 0 ]; then
echo "Error: you must be root." >&2
exit 1
fi
gitlab_ipaddr_list=$(get_gitlab_ip_list)
hostname=$(hostname)
sshdir=/root/.ssh
privkey=gitlab-$hostname
pubkey="$privkey.pub"
keydestdir="$KEY_COPY_DEST_DIR/$hostname/"
if [ ! -f "$keydestdir/$pubkey" ]; then
# Make the keys to push to GitLab.
rm -f "$sshdir/$privkey" "$sshdir/$pubkey"
ssh-keygen -t rsa -C "${hostname}@${GITLAB_HOST}" -N '' -f "$sshdir/$privkey"
cat <<CONFIG >>$sshdir/config
Host $GITLAB_HOST
User $hostname
IdentityFile $sshdir/gitlab-$hostname
CONFIG
# Copy the public key to mounted directory.
mkdir -p "$keydestdir"
cp -f "$sshdir/$pubkey" "$keydestdir/$pubkey"
fi
# Update GitLab entry in known_hosts.
[ -f $sshdir/known_hosts ] && ssh-keygen -R $GITLAB_HOST
ssh-keyscan $GITLAB_HOST |
awk -v "hosts=$gitlab_ipaddr_list" '$1 = $1 "," hosts' \
>>$sshdir/known_hosts
# Let etckeeper push to GitLab via
# daily cron job (/etc/cron.daily/etckeeper).
etckeeper init
etckeeper vcs remote rm gitlab || true
etckeeper vcs remote add gitlab $GITLAB_GIT_REMOTE
sed -i -E 's/PUSH_REMOTE=""/PUSH_REMOTE="gitlab"/' /etc/etckeeper/etckeeper.conf
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment