Skip to content

Instantly share code, notes, and snippets.

@woozyking
Last active March 22, 2018 18:53
Show Gist options
  • Save woozyking/9139157 to your computer and use it in GitHub Desktop.
Save woozyking/9139157 to your computer and use it in GitHub Desktop.
Git push to deploy leveraging Linux user:group as a "container/sandbox"
#!/usr/bin/env bash
#######################################################
# Git Based Push to Deploy Env Setup
# To Use:
# ./push_to_deploy.sh <name of user> [optional crontab]
#######################################################
set -e
if [ "$#" -eq 0 ]; then
echo 'Usage: ./push_to_deploy.sh <name of user> [optional crontab]'
exit 1
elif [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
echo 'Usage: ./push_to_deploy.sh <name of user> [optional crontab]'
exit 0
fi
#########
# Configs
#########
# Deploy username
DEPLOY_USER="$1"
DEPLOY_HOME="/home/$DEPLOY_USER"
# Deploy app dir and git bare repo
DEPLOY_DIRNAME=deploy
DEPLOY_GITNAME=repo.git
DEPLOY_LOGNAME=logs
DEPLOY_DIR="$DEPLOY_HOME/$DEPLOY_DIRNAME"
DEPLOY_GIT="$DEPLOY_HOME/$DEPLOY_GITNAME"
DEPLOY_LOG="$DEPLOY_HOME/$DEPLOY_LOGNAME"
###################
# Deploy User Setup
###################
# Add deploy user:group, create its home folder
sudo useradd "$DEPLOY_USER" -m || true
# Ensure ~/.ssh/authorized_keys exists
sudo -H -u "$DEPLOY_USER" sh -c "mkdir -p $DEPLOY_HOME/.ssh && touch $DEPLOY_HOME/.ssh/authorized_keys"
sudo -H -u "$DEPLOY_USER" sh -c "chmod 700 $DEPLOY_HOME/.ssh && chmod 600 $DEPLOY_HOME/.ssh/authorized_keys"
# Create app dir and git bare repo as deploy user
sudo -H -u "$DEPLOY_USER" sh -c "mkdir -p $DEPLOY_DIR $DEPLOY_GIT $DEPLOY_LOG"
# Make git bare repo
sudo -H -u "$DEPLOY_USER" sh -c "cd $DEPLOY_GIT && git init --bare"
# Create crontab if its given
if [ -n "$2" ]; then
sudo -H -u "$DEPLOY_USER" sh -c "(crontab -l ; echo $2) | crontab -"
fi
# Prepare post-receive hook
touch "$HOME/post-receive"
# save stdout to fd 3; redirect fd 1 to post-receive
exec 3>&1 >"$HOME/post-receive"
# the content of post-receive
echo "git --work-tree=$DEPLOY_HOME/deploy --git-dir=$DEPLOY_HOME/repo.git checkout -f"
echo "cd $DEPLOY_HOME/deploy"
echo "./start"
echo
# restore original stdout to fd 1
exec >&3-
# make post-receive executable
chmod +x "$HOME/post-receive"
# copy over post-receive
sudo cp "$HOME/post-receive" "$DEPLOY_GIT/hooks/post-receive"
# ensure to grant correct permission
sudo chown "$DEPLOY_USER":"$DEPLOY_USER" "$DEPLOY_GIT/hooks/post-receive"
# What's next
# append in participants public keys to .ssh/authorized_keys
# see http://www.cyberciti.biz/faq/install-ssh-identity-key-remote-host/ for a great technique
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment