Skip to content

Instantly share code, notes, and snippets.

@dertin
Last active January 17, 2024 12:40
Show Gist options
  • Save dertin/cb9bf0ff276b54803f898c5240b27d3b to your computer and use it in GitHub Desktop.
Save dertin/cb9bf0ff276b54803f898c5240b27d3b to your computer and use it in GitHub Desktop.
Setup git deploy for AWS ec2 Ubuntu instance

Git deploy setup:

copy your public key to your ec2 instance:

$ cat ~/.ssh/id_rsa.pub | ssh -i ~/.ssh/your_pemfile.pem ubuntu@your_ip_addr "cat>> .ssh/authorized_keys"

on remote server: create bare git directory

$ cd ~

$ mkdir ProjectDir.git && cd ProjectDir.git

$ git init --bare

on remote server: create post-receive hook

$ nano hooks/post-receive

echo '--- --- --- --- --- --- --- --- --- --- ---'
echo 'Deploying site...'
echo '--- --- --- --- --- --- --- --- --- --- ---'

if ! [ -t 0 ]; then
    read -a ref
fi

IFS='/' read -ra REF <<< "${ref[2]}"
branch="${REF[2]}"

# Master Branch
if [ "master" == "$branch" ]; then
	echo "Master Post Receive"
	readonly HTTP_HOST=example.com
	readonly REMOTE_TARGET=/var/www/webdisk/${HTTP_HOST}/htdocs/

	GIT_WORK_TREE=${REMOTE_TARGET}
	export GIT_WORK_TREE
	git checkout -f

	echo "End Post Receive"
fi

echo '--- --- --- --- --- --- --- --- --- --- ---'

$ chmod +x hooks/post-receive

on local machine: init repo and add remote repository

$ git init

$ git remote add ec2 ssh://ubuntu@your_ip_addr/home/ubuntu/ProjectDir.git

$ git push ec2 +master:refs/heads/master

note: only have to use “+master:refs/heads/master for 1st push

to push to remote repo in future:

$ git push ec2 master

Push to multiple remote repos with one command

add to .git/config in local repo

[remote "all"]
        url = https://github.com/YourGitAccount/ProjectDir.git
        url = ssh://ubuntu@your_ip_addr/home/ubuntu/projects/ProjectDir.git

push to both repos simultaneously

$ git push all master

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment