<返回更多

shell脚本请求带json数据

2023-03-30  今日头条  小毛驴的烂笔头
加入收藏

业务爸爸:小毛驴帮我实现一个功能,我在做业务版本更新的时候需要把该主机在clb上权限改为0,要求用shell脚本实现。

小毛驴:安排!

#!/bin/sh
#
#调用腾讯云的clb api,修改指定 clb, 指定 localtion id下指定 targets 主机的权限。
# author 小毛驴
#

clb_modify_target_api_url=${ApiUrl}

function installJq() {
    if [ -f /etc/redhat-release ];then
        _OSFLAG=`cat /etc/redhat-release | awk '{print tolower($1)}'`
        if [[ ${_OSFLAG}x == 'centos'x  ]]  || [[  ${_OSFLAG}x == 'tencent'x ]] ; then
             yum  -y  -q  install jq
        fi
    elif [ -f /etc/lsb-release ];then
        _OSFLAG=`cat /etc/lsb-release | grep "DISTRIB_ID" | awk -F"=" '{print tolower($2)}'` 
        if [ ${_OSFLAG}x == "ubuntu"x ];then
            sudo apt-get -y   -q install jq
        fi
    else
        echo  "This is no CentOS and Ubuntu , 脚本目前不支持此系统 !"
        exit 1
    fi
}

which jq > /dev/null
if [ $? -gt 0 ]; then
    installJq
fi

function modify_clb_targets() {
    local region=$1
    local load_balancer_id=$2
    local listener_id=$3
    local location_id=$4
    local eni_ip=$5
    local port=$6
    local weight=$7
    generate_get_clb_post_data() {
cat <<EOF
{
    "region": "${region}",
    "load_balancer_id": "${load_balancer_id}",
    "listener_id": "${listener_id}",
    "location_id": "${location_id}",
    "targets": [{
        "eni_ip": "${eni_ip}",
        "port": ${port},
        "weight": ${weight}
    }]
}
EOF
}

    respond=$(curl -s -X POST 
        ${clb_modify_target_api_url} 
        -H 'cache-control: no-cache' 
        -H 'content-type: Application/json' 
        -d "$(generate_get_clb_post_data)")
    echo ${respond}
    http_code=$(echo ${respond} | jq '.code')
    if [[ ${http_code} != 200 ]]; then
        echo "$(echo ${respond} | jq '.message')"
        exit  2
    fi
    echo ${respond} | jq '.message'
}

#如果 Port 是 -1 表示该LocationId下EniIp这地址只有一个端口
if [ ${Port} == -1 ];then
    modify_clb_targets ${Region} ${LoadBalancerId} ${ListenerId} ${LocationId} ${EniIp} -1 ${Weight}
else
    modify_clb_targets ${Region} ${LoadBalancerId} ${ListenerId} ${LocationId} ${EniIp} ${Port} ${Weight}
fi

知识点

  1. clb_modify_target_api_url 这个接口是基于腾讯云封装后的接口(golang实现,后面会把该代码分享), 接收json数据能修改对应clb下localtionId的主机权限。
  2. 用jq处理返回的json数据。
声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>