continuous deployment with jenkins

user1338413 picture user1338413 · Dec 20, 2012 · Viewed 34k times · Source

I want to deploy with jenkins to the test environment and to the production environment. To do so I need to connect to the server of the wanted environment, something like ssh/scp.

I would like to know what the best way is.

I found some plugins to do this, like the Jenkins-Deploy-Plug-in or Jenkins Publish over SSH Plugin. The first has lots of issues, which is not really trustworthy to deploy to production and for the second you need to change the global configuration, which is manual work for every deploy.

Any ideas how to solve this? Maybe with some scripts or plugins?

The only current idea I have is: to connect with jenkins to a server (maybe with the SSH Plugin) and to execute there a script that connects to the wished environment. But that are two connections. Is that really neccessary? I hope for a more straightforward way for this.

thanks for any hint.

Answer

ben75 picture ben75 · Dec 20, 2012

I suggest the following procedure:

one single shell script (stored somewhere on the jenkins server) does everything. Basically, the script does scp of the build artifact and then connects to the server (ssh) and does all the necessary tasks to deploy (setup maintenance page, backup the current app, deploy the new app, ...).

On the jenkins server, there are at least 2 jobs:

  • the first one simply does the build (using maven, or any other build script)
  • the second job does the deploy : so this job only runs the shell script. (I suggest one deploy job for each target environment : testing, production, ...)

It does not require any "special" jenkins plugin to achieve this "one click deployment". It only requires that the jenkins user has ssh access to the target server.

EDIT

Here is a sample shell script to illustrate my post

#This script will copy the last artifact build by the job "MyApp" to test.myserver.com
#and remotely execute the deployment script.

#copy the war to the server
#(the job "MyApp" is using maven, that's why the war can be found at this location)
scp -i <HOME_DIR>/.ssh/id_dsa $HUDSON_HOME/jobs/MyApp_Build/workspace/myapp/target/myapp.war     [email protected]:/tmp/

#connect to the server and execute the deployment script
ssh -i <HOME_DIR>/.ssh/id_dsa [email protected] 
#The following is just an example of what a deployment script can be.
#of course you must adapt it to your needs and environment
"cd <TOMCAT_DIR>;
#first copy the current war to a backup directory (additionaly, I have a cron task deleting old undeployed apps)
cp -rf myapp-apps/myapp* undeployed/myapp-apps/; 
#execute a script (stored on the server) to properly stop the app
sh bin/myapp.sh stop; 
#delete current app
rm -rf myapp-apps/myapp; 
rm -rf myapp-apps/myapp.war;
#copy the uploaded war in tomcat app directory 
cp /tmp/myapp.war myapp-apps/; 
#execute a script (stored on the server) to start the app
sh bin/myapp.sh start"