Anuj Kaushal

Shell script to deploy your code using SSH command

February 6, 2021, by anuj, category Bash, Blog, Command, Hosting, Shell

So we have awesome ways to deploy our latest code on cloud environments like Ansible, Puppet and there are also tools like Jenkins, Travis to make that more easy.

But when it comes Shared hosting our options are very limited and most of the time you don’t have any option but to manually deploy the code and deal with down time along with all type of deployment issues like:
– The files didn’t get uploaded correctly due to bad connection.
– Uploaded file doesn’t have the correct permissions.

So to deal with all these problem i have created deployment bash script. Which will zip the latest code, upload that to the sever and it also creates backup of the existing code on the server. In case of a rollback.

For the to work I need SSH access to my hosting server and I have configured it like this

anuj@mymachine:~$ cat ~/.ssh/config
Host sshHost
  HostName XXX.XXX.XX.XX
  User anujsshuser
  IdentityFile ~/.ssh/my-key.pem

anuj@mymachine:~$ ssh hostgator
Last login: Sat Feb  6 06:58:20 2021 from XX.XXX.XXX.XXX
[email protected] [~]# ls

[email protected] [~]# ls -l .bash*
-rw------- 1 anujsshuser anujsshuser 11549 Feb  6 14:52 .bash_history
-rw-r--r-- 1 anujsshuser anujsshuser    18 Oct 19 18:01 .bash_logout
-rw-r--r-- 1 anujsshuser anujsshuser   193 Oct 19 18:01 .bash_profile
-rw-r--r-- 1 anujsshuser anujsshuser   231 Oct 19 18:01 .bashrc

[email protected] [~]# exit
logout
Connection to XXX.XXX.XX.XX closed.
anuj@mymachine:~$ 

Once I have ssh access then all I need do configure my deployment script.

If everything works fine then I expect following output

anuj@mymachine:~/myGuestBook$ ls -l
total 8
drwxrwxr-x 2 anuj anuj 4096 Feb  4 23:57 config
-rw-rw-r-- 1 anuj anuj 3721 Feb  5 00:15 deploy.sh
anuj@mymachine:~/myGuestBook$ sh deploy.sh 
Generating local codebase tar ball
Codebase tar ball generated
Tar ball generated: myGuestBook-local-20210206202705-codebase.tgz
Uploading code to server backup location
myGuestBook-local-20210206202705-codebase.tgz                       100%   14MB   1.6MB/s   00:08    
Codebase upload complete
SEVER BASH - stats here
Pseudo-terminal will not be allocated because stdin is not a terminal.
Successfully connected to Hostgator server bash
Server codebase backup: ~/backup/myGuestBook-server-20210206202705-codebase.tgz
Deleting files after taking backup
Copied new codebase to document-root
Extracting new codebase starts now ~/public_html
rm: refusing to remove '.' or '..' directory: skipping '/home/myGuestBook/public_html/.'
rm: refusing to remove '.' or '..' directory: skipping '/home/myGuestBook/public_html/..'
New codebase extraction complete
Remove codebase tarball
Creating for softlinks
Disconnecting from the server bash
SEVER BASH - ends here
Uploading config file
.env                                                                100%  979     3.1KB/s   00:00    
DONE