Skip to content

Instantly share code, notes, and snippets.

@XavM
Last active December 4, 2020 13:21
Show Gist options
  • Save XavM/723b74479735b48e24cbacd97d4f70ff to your computer and use it in GitHub Desktop.
Save XavM/723b74479735b48e24cbacd97d4f70ff to your computer and use it in GitHub Desktop.
git push deployment using git hooks

git push deployment using git hooks

Run sshd in Docker container (Test only)

From Mac

docker run -itp 2222:22 alpine /bin/sh

From container

alias ll="ls -larth"
apk add --no-cache --update-cache openrc openssh git npm
ssh-keygen -A
mkdir /run/openrc/
touch /run/openrc/softlevel
rc-status
vi /etc/ssh/sshd_config
#Uncomment lines :
#  - UseDNS no
adduser xav
/etc/init.d/sshd start

From Mac

ssh-copy-id -i ~/.ssh/id_rsa -p 2222 xav@127.0.0.1
ssh -p '2222' 127.0.0.1

From container

vi /etc/ssh/sshd_config
#Uncomment lines :
#  - PasswordAuthentication no
/etc/init.d/sshd restart

Git push deploy

From container

sudo su 
apk add "git>2.28.0-r0" --repository=http://dl-cdn.alpinelinux.org/alpine/edge/main # git 2.28.0 at least to use --initial-branch

su - xav
mkdir ~/app
git init --bare --initial-branch=main ~/git_push_deploy.git

Git hooh post-receive (in container)

vi ~/git_push_deploy.git/hooks/post-receive
# --- START ----------------------------------
#!/bin/ash

set -eo pipefail

main() {

  TARGET="/home/xav/app"
  GIT_DIR="/home/xav/git_push_deploy.git"
  BRANCH="main"

  while read oldrev newrev ref
  do
    # only checking out the main (or whatever branch you would like to deploy)
    if [ "$ref" = "refs/heads/$BRANCH" ];
    then
      echo "Ref $ref received. Deploying ${BRANCH} branch ..."
      git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f $BRANCH
    else
      echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."
    fi

    hasChanged package.json && {
      echo "package.json has changed: Running npm install --production" \
      && cd $TARGET \
      && npm install --production
    }

  done
}

getChangedFiles() {
  git diff-tree -r --name-only --no-commit-id $1 $2
}

hasChanged() {
  getChangedFiles $oldrev $newrev | grep -q "$1"
}

main
# --- END ------------------------------------

chmod +x ~/git_push_deploy.git/hooks/post-receive
vi /etc/passwd # Switch User shell to /usr/bin/git-shell (no usermod on Alpine)
# --- START ----------------------------------
xav:x:1000:1000:Linux User,,,:/home/xav:/usr/bin/git-shell
# --- END ------------------------------------

From Mac

cd ~/$MY_APP
git remote add dev ssh://xav@127.0.0.1:2222/home/xav/git_push_deploy.git # dev can be replaced with anything; Ex: prod, staging, etc ...
git push dev main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment