Skip to content

Instantly share code, notes, and snippets.

@mlakkadshaw
Last active December 25, 2015 12:28
Show Gist options
  • Save mlakkadshaw/18ef45096e47d8626b43 to your computer and use it in GitHub Desktop.
Save mlakkadshaw/18ef45096e47d8626b43 to your computer and use it in GitHub Desktop.
Setup automatic deployment on your server using this shell script. After this shell script is executed you can deploy code using "git push server master"
#!/bin/bash
# A bash script to setup GIT like deployment on your server
echo "Enter your server address e.g 25.32.132.1 or yourserver.com"
read serverAddress
echo "Enter Username which you use to login to your server e.g ubuntu"
read username
echo "Enter path of the private key (optional)"
read privateKeyPath
echo "Path of your server directory where code should reside: e.g ~/code or /var/www (required)"
read tempPath
echo "Path of your local directory: (required)"
read localDirectory
echo "Enter name of your application: (required)"
read appName
echo "Command to run after each deployment: (optional) "
read deployCommand
#TODO: Validate user input and show approproate errors.
#Checking if the ssh-keys are present in the system
if [ ! -f ~/.ssh/id_rsa ]; then
echo "SSH-KEYS not found, generating ssh-keys"
echo "Enter your email:"
read email
ssh-keygen -t rsa -b 4096 -C "$email"
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa
fi
#Adding the SSH key as Authorized Key in the remote server
echo "Trying to SSH into the server "$serverAddress" as "$username
if [ ! -z "$privateKeyPath"]; then
echo "Using private key "$privateKeyPath
fi
echo "Adding SSH into Server's Authorized Keys.."
if [ ! -z "$privateKeyPath"]; then
cat ~/.ssh/id_rsa.pub | ssh $username@$serverAddress -i $privateKeyPath 'mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys'
else
cat ~/.ssh/id_rsa.pub | ssh $username@$serverAddress 'mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys'
fi
git -C $localDirectory status
if [ ! $? -eq 0 ]; then
echo "Please initalise git in your "$localDirectory" first".
exit
fi
REMOTE_HOME="$(ssh $username@$serverAddress 'echo $HOME')"
wait
remoteDirPath="${tempPath/\~/$REMOTE_HOME}"
echo $remoteDirPath
text="#!/bin/sh\ngit --work-tree="$remoteDirPath" --git-dir="$REMOTE_HOME"/_repo/"$appName".git checkout -f\n"$deployCommand
ssh $username@$serverAddress 'sudo -S apt-get install -y git && mkdir -p _repo && cd _repo && mkdir -p '$appName'.git && cd '$appName'.git && git init --bare && cd hooks && printf "'$text'" > post-receive && chmod +x ./post-receive && mkdir -p '$remoteDirPath
git -C $localDirectory remote add server ssh://$username@$serverAddress$REMOTE_HOME/_repo/$appName.git
echo "All Set"
echo "Now you can deploy your code using 'git push server master'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment