Nginx自切换upstream脚本,可配合Jenkins实现自动切换部署

Image description 三网大流量卡(正规、非野路子、非物联网卡) – 运营商App可查,点击办理

没找到类似解决方案,自己写了个脚本切换。

#!/bin/bash
#By: 不浮不躁 2021-04-07

#传参提示
if [ ! -n "$1" ] || [ ! -n "$2" ] || [ ! -n "$3" ] || [ ! -n "$4" ];then
    echo "错误:"
    echo "样例使用:sh $0 "nginx文件绝对路径" "upstream名字" "server的ip" "起/停" "
    echo "样例使用:sh $0 "/etc/nginx/conf.d/test.conf" "dapp" "192.168.92.181" "up" "
    exit 1
fi

Conf=$1
Upstream=$2
Ip=$3
Cmd=$4

Tmp=`cat -n $Conf`
#获取upstream段开头
Str=`echo "$Tmp" | grep $Upstream |grep upstream` 
#获取upstream段,”}“结尾
Tmp=`echo "$Tmp" | sed -n "/$Str/,/}/p"`
#echo "$Tmp"
#获取ip所在行
Line=`echo "$Tmp" | grep $Ip | awk '{print $1}'`
#echo $Line
if [ -z "$Line" ]; then
    echo "未获取到指定代理IP"
    exit 1
fi

#判断是否注释
Status=`echo "$Tmp" | grep $Ip | awk '{print $2}' | grep ^# `
#echo $Status
if [ -z "$Status" ]; then
    Status="未注释"
    echo $Status
    echo "$Tmp"
    #sed -i "$Line,$Line s/^/#/g" $Conf
else
    Status="已注释"
    echo $Status
    echo "$Tmp"
fi

#取消注释
if [ "$Cmd" == "up" ] && [ $Status == "已注释" ]; then
    sed -i "$Line,$Line s/#//g" $Conf

    Tmp=`cat -n $Conf`
    #获取upstream段开头
    Str=`echo "$Tmp" | grep $Upstream |grep upstream`
    #获取upstream段,”}“结尾
    Tmp=`echo "$Tmp" | sed -n "/$Str/,/}/p"`
    echo "$Tmp"
fi

#注释
if [ "$Cmd" == "down" ] && [ $Status == "未注释" ]; then
    sed -i "$Line,$Line s/^/#/g" $Conf
    
    Tmp=`cat -n $Conf`
    #获取upstream段开头
    Str=`echo "$Tmp" | grep $Upstream |grep upstream`
    #获取upstream段,”}“结尾
    Tmp=`echo "$Tmp" | sed -n "/$Str/,/}/p"`
    echo "$Tmp"
fi

使用方式:sh 脚本名 "配置文件绝对路径" "upstream名" "服务ip" "up或down"
使用方式:sh $0 "/etc/nginx/conf.d/test.conf" "dapp" "192.168.92.181" "up"

可做自动切换部署方案

Image description 三网大流量卡(正规、非野路子、非物联网卡) – 运营商App可查,点击办理

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容