现在公司的每个tomcat项目都有测试和生产两个环境,对于经常需要上线的tomcat项目,如用手工更新就非常耗费时间和人力。现用fabric开发了一个自动发布tomcat项目的脚本,该脚本已经在公司使用的非常稳定。
fabric自动发布脚本流程如下:
#!/usr/bin/python
#coding=utf-8
from fabric.api import *
from fabric.colors import *
from fabric.context_managers import *
from fabric.contrib.console import confirm
env.user='root'
env.hosts=['192.168.1.10']
env.password=''
env.svn_user='userabd'
env.svn_password=''
env.svn_url='svn://192.168.1.20/source/java/project'
env.svn_local_path='/data/svn/'
env.remote_path='/data/company/project/'
@task
def package_project():
print yellow('开始打包文件')
with lcd(env.svn_local_path):
local("svn co %s --username=%s --password=%s" %(env.svn_url,env.svn_user,env.svn_password))
with lcd("%s'project'" %(env.svn_local_path)):
local("mvn clean package -Dmaven.test.skip=true -Ptest -U")
with lcd("%s'project/target'" %(env.svn_local_path)):
result=local('ls |grep project.*war$',capture=True)
print yellow('打包文件成功')
print yellow('打包文件为:%s' %(result))
@task
def put_package():
print yellow('开始上传文件')
with lcd("%s'project/target'" %(env.svn_local_path)):
result=local('ls |grep project.*war$',capture=True)
env.local_war_path=env.svn_local_path + 'project/target/' + result
with cd("env.remote_path"):
put(env.local_war_path,env.remote_path) @task
def check_task():
with lcd("%s'project/target'" %(env.svn_local_path)):
result=local('ls |grep project.*war$',capture=True)
env.local_war_path=env.svn_local_path + 'project/target/' + result
env.remote_war_path=env.remote_path + result
lmd5=local("md5sum %s" %(env.local_war_path),capture=True ).split(' ')[0]
rmd5=run("md5sum %s" %(env.remote_war_path)).split(' ')[0]
if lmd5 == rmd5:
print green('上传文件成功')
else:
print red('上传文件失败') @task
def unpack_project():
print yellow('开始解压war包')
with lcd("%s'project/target'" %(env.svn_local_path)):
result=local('ls |grep project.*war$',capture=True)
with cd(env.remote_path):
run("find . ! -name '*war' -a ! -name .|xargs rm -rf")
run("unzip %s" %(result)) @task
def switch_production():
print yellow('开始切换生产环境配置文件')
with cd(env.remote_path):
run('sed -i s/test/production/g WEB-INF/classes/applicationContext.xml') @task
def restart_tomcat():
print yellow('重启Tomcat进程')
run('/usr/local/tomcat/bin/shutdown.sh')
run('sleep 10')
run('/usr/local/tomcat/bin/startup.sh') @task
def production():
package_project()
put_package()
check_task()
unpack_project()
switch_production()
restart_tomcat()
脚本使用方法:fab -f name.py production