Deployment automation from windows to the linux server

My project is written in java and need to be deployed to a tomcat server on the linux system and each time I must:

  1. build the java project with maven
  2. login onto the linux server with ssh
  3. shutdown the tomcat server with shell script command
  4. upload the config/war/jar files to the server using winscp
  5. startup the tomcat server with command again

It’s cumbersome and will always take some time even the change is tiny. If you made small mistake, sorry, do it gain. So I decide to spend some time to automate the deployment process.

since I am working under the windows os which I can not choose, so I use the windows/dos batch script to implement the automation script.

Firstly I generated the public and private key with ssh-keygen, upload the “id_rsa.pub” to the remote linux server, save the private key “id_rsa” to a local windows folder.

:: configure the deployment
set _pkey=c:\private_key\id_rsa
set _source=\path\of\file_to_deploy
set _backup=\path\of\file_to_backup\%date:/=_%
set _linuxServer=username@ip.address
set _targetSrc=/path/to/deploy
set _remoteSrc=%_linuxServer%:%_targetSrc%

:: backup the files on the remote linux server
if not exist %_backup% mkdir %_backup%
scp -i %_pkey% -r %_remoteSrc% %_backup%

:: check if tomcat is running
ssh -i %_pkey% %_linuxServer% "ps -ef | grep '/path/to/java' --exclude={ps -ef,grep}" > returnInfo.txt

:: check return info size by function call trick
call :getFilesize returnInfo.txt

:: shut down the tomcat
if not %_infoSize%==0 (
ssh -i %_pkey% %_linuxServer% "/path/to/shutdown_tomcat.sh > /dev/null 2>&1 &"
)

:: remove the temp return info
del returnInfo.txt

:: function
:getFilesize
setlocal
set size=%~z1
endlocal & set _infoSize=%size%

:: clean up the old files from the server
ssh -i %_pkey% %_linuxServer% "rm -r %_targetSrc%"

:: copy the new files to the server
scp -i %_pkey% -r %_source% %_remoteSrc%

::start up the linux server
ssh -i %_pkey% %_linuxServer% "/path/to/startup_tomcat.sh > /dev/null 2>&1 &"

if you separate this script in several parts, you could get more flexibility, for instance you can build your own recovery script like following:

set _recover_date=%1
if exist %_backup% (
	:: setup environment/variables
	call setup.bat

	:: shutdown tomcat, upload files, startup tomcat
	call deploy.bat
) else ( 
	echo "can not find backup %_backup%"
)