现在公司的每个tomcat项目都有测试和生产两个环境,对于经常需要上线的tomcat项目,如用手工更新就非常耗费时间和人力。现用fabric开发了一个自动发布tomcat项目的脚本,该脚本已经在公司使用的非常稳定。
fabric自动发布脚本流程如下:
1 #!/usr/bin/python 2 #coding=utf-8 3 from fabric.api import * 4 from fabric.colors import * 5 from fabric.context_managers import * 6 from fabric.contrib.console import confirm 7 env.user='root' 8 env.hosts=['192.168.1.10'] 9 env.password='123456789' 10 env.svn_user='userabd' 11 env.svn_password='123456' 12 env.svn_url='svn://192.168.1.20/source/java/project' 13 env.svn_local_path='/data/svn/' 14 env.remote_path='/data/company/project/' 15 @task 16 def package_project(): 17 print yellow('开始打包文件') 18 with lcd(env.svn_local_path): 19 local("svn co %s --username=%s --password=%s" %(env.svn_url,env.svn_user,env.svn_password)) 20 with lcd("%s'project'" %(env.svn_local_path)): 21 local("mvn clean package -Dmaven.test.skip=true -Ptest -U") 22 with lcd("%s'project/target'" %(env.svn_local_path)): 23 result=local('ls |grep project.*war$',capture=True) 24 print yellow('打包文件成功') 25 print yellow('打包文件为:%s' %(result)) 26 @task 27 def put_package(): 28 print yellow('开始上传文件') 29 with lcd("%s'project/target'" %(env.svn_local_path)): 30 result=local('ls |grep project.*war$',capture=True) 31 env.local_war_path=env.svn_local_path + 'project/target/' + result 32 with cd("env.remote_path"): 33 put(env.local_war_path,env.remote_path) 34 35 @task 36 def check_task(): 37 with lcd("%s'project/target'" %(env.svn_local_path)): 38 result=local('ls |grep project.*war$',capture=True) 39 env.local_war_path=env.svn_local_path + 'project/target/' + result 40 env.remote_war_path=env.remote_path + result 41 lmd5=local("md5sum %s" %(env.local_war_path),capture=True ).split(' ')[0] 42 rmd5=run("md5sum %s" %(env.remote_war_path)).split(' ')[0] 43 if lmd5 == rmd5: 44 print green('上传文件成功') 45 else: 46 print red('上传文件失败') 47 48 @task 49 def unpack_project(): 50 print yellow('开始解压war包') 51 with lcd("%s'project/target'" %(env.svn_local_path)): 52 result=local('ls |grep project.*war$',capture=True) 53 with cd(env.remote_path): 54 run("find . ! -name '*war' -a ! -name .|xargs rm -rf") 55 run("unzip %s" %(result)) 56 57 58 @task 59 def switch_production(): 60 print yellow('开始切换生产环境配置文件') 61 with cd(env.remote_path): 62 run('sed -i s/test/production/g WEB-INF/classes/applicationContext.xml') 63 64 65 @task 66 def restart_tomcat(): 67 print yellow('重启Tomcat进程') 68 run('/usr/local/tomcat/bin/shutdown.sh') 69 run('sleep 10') 70 run('/usr/local/tomcat/bin/startup.sh') 71 72 73 @task 74 def production(): 75 package_project() 76 put_package() 77 check_task() 78 unpack_project() 79 switch_production() 80 restart_tomcat()
脚本使用方法:fab -f name.py production