天天看點

小毛驢問答之shell腳本請求帶json資料

作者:小毛驢的爛筆頭

業務爸爸:小毛驢幫我實作一個功能,我在做業務版本更新的時候需要把該主機在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資料。