脚本来源的需求saas批量升级,需求将stg(stg环境:近似1:1的生产环境)的war包全量部署到online,先刷sql后部署war包,差不多10分钟部署完成。
脚本存放于跳板机上,跳板机和stg/online做了秘钥登录:
env.sh的内容就是war和ip对应的列表如下:
env.sh文件:
#10.10.15.15=owms-api.war;
操作前先备份,防止回滚:
$ cat backup_env_war.sh #!/bin/bash backup_time=`date +"%Y-%m-%d-%H-%M-%S"` for ip in `cat ../env.sh | grep -v "^$" | awk -F ‘#‘ ‘{print $2}‘ | awk -F ‘=‘ ‘{print $1}‘ | sort | uniq` do ssh ${ip} "cd /data/ && cp -r env{,-${backup_time}}"#备份env目录,开发pool自定义的变量 ssh ${ip} "cd /data/tomcat && cp -r webapps{,-${backup_time}}"#备份生产tomcat 部署路径,防止回滚 done
备份完做个确认,是否正确:
脚本内容如下:
$ cat copy_stgwar_prodwar.sh #!/bin/bash time_stamp=`date +"%Y-%m-%d-%H-%M-%S"`#备份时间 prod_war_home=/data/ksyun-saas/package/wars#从stg拉去war包存放本地的目录 stg_env=/data/stg-saas/package#stg env.sh文件路径 prod_env=/data/ksyun-saas/package#online env.sh文件对应路径 tomcat_dir=/data/tomcat/webapps#tomcat 部署路径 function shutdown_tomcat() {#stop tomcat函数 tomcatId=`ssh $ip ps -ef | grep java | grep -v "grep" | awk ‘{print $2}‘` if [ ! $tomcatId ];then echo "tomcat process in ${ip} is not exist." else echo "shutdown tomcat in ${ip}" ssh $ip "/bin/kill -9 $tomcatId" if [ $? == 0 ];then echo "shutdown $ip tomcat process is success." else echo "shutdown $ip tomcat process is false." exit 2 fi fi } function start_tomcat() {#启动tomcat函数 echo "start tomcat in ${ip}." ssh $ip "JAVA_HOME=`which java | awk -F ‘/bin/‘ ‘{print $1}‘`;export JAVA_HOME;/bin/sh /data/tomcat/bin/startup.sh" ssh $ip "/usr/local/java/jdk1.7.0_80/bin/jps" } read -p "输入你需要发布的war包:" stg_war#read 变量 if [ "${stg_war}" != " " ];then#强制输入参数,避免空参数 stg_war_ip=`cat ${stg_env}/env.sh | egrep "${stg_war}[^-]" | awk -F ‘#‘ ‘{print $2}‘ | awk -F ‘=‘ ‘{print $1}‘` #过滤pool对应的stg环境部署机器 echo $stg_war_ip echo -n "正在从stg环境${stg_war_ip} 复制 ${stg_war}到${prod_war_home}下" scp ${stg_war_ip}:/${tomcat_dir}/${stg_war}.war ${prod_war_home}#scp war到本地目录 echo -n "确认${stg_war}.war存在" ls -lh ${prod_war_home} | grep ${stg_war}.war sleep 2 echo -n "开始部署到online环境" for ip in `cat ${prod_env}/env.sh | grep "${stg_war}[^-]" | awk -F ‘#‘ ‘{print $2}‘ | awk -F ‘=‘ ‘{print $1}‘`;do#通过pool过滤生产ip shutdown_tomcat $ip ssh ${ip} "cd ${tomcat_dir} && cp ${stg_war}.war ${stg_war}.war-${time_stamp}"#下面备份部署重启tomcat ssh ${ip} "cd ${tomcat_dir} && /bin/rm -rf ${stg_war}" scp ${prod_war_home}/${stg_war}.war ${ip}:/${tomcat_dir} start_tomcat $ip done fi
运行的效果图:
本文出自 “蚂蚁” 博客,请务必保留此出处http://215687833.blog.51cto.com/6724358/1916039
原文地址:http://215687833.blog.51cto.com/6724358/1916039