如何使用环境变量集自动调用脚本

How to automatically call script with environment variable set

我希望能够使用 ./script.sh -e "${env}" -a "${app}" 调用此脚本。 -e(环境),而-a(应用程序)。基本上,通过将环境设置为 stage 或 prod,它会自动获取 IP 地址。注意:我为此使用 Jenkins 并从 GIT 中提取代码。目标不是在脚本中对 IP 进行硬编码以实现代码的重复使用。

有什么想法吗?

#!/bin/bash

while [[ $# > 1 ]]
do
OPTIONS=""

case $OPTIONS in
    -a|--application)
    APPLICATION=""
    shift # past argument
    ;;
    -s|--ip)
    HOSTS_STAGE=""
    shift # past argument
    ;;
    -p|--ip)
    HOSTS_PROD=""
    shift # past argument
    ;;
    --default)
    DEFAULT=YES
    ;;
    *)
            # unknown option
    ;;
esac
shift # past argument or value
done

echo "########################################"
echo "##  OS Updates on ${APPLICATION}  ##"
echo "########################################"


if [[ "${ENVIRONMENT}" == 'stage' ]]; then
IPS="${HOSTS_STAGE}"

elif [[ "${ENVIRONMENT}" == 'prod' ]]; then
IPS="${HOSTS_PROD}"

fi


echo "---------------------------------------"
echo "##  Performing update in ${ENVIRONMENT}"
echo "---------------------------------------"

for ip in $IPS; do

    echo "---------------------------------------"
    echo "##  Running yum update on ${ip}"
    echo "---------------------------------------"

    ssh -i "${id_rsa}" -o StrictHostKeyChecking=no dvopsadmin@${ip} "df -h"
    done

   if [[ ${REBOOT} == y ]]; then
   for ip in $IPS; do
       echo "---------------------------------------"
       echo "## Rebooting server on ${ip}"
       echo "---------------------------------------"

       ssh -i "${id_rsa}" -o StrictHostKeyChecking=no dvopsadmin@${ip} "uname -a"
       done
   else
      echo "------------------------------------------"
      echo "##  Updates alredy performed withot reboot"
      echo "------------------------------------------"

   fi

我推荐你使用EnvInject Plugin。您可以使用此插件在 Git 项目的顶部设置环境变量。查看 link 以获取说明。您可以创建两个环境变量,例如应用程序和环境

然后在你的 "Execute shell" 部分你可以使用环境变量。

./script.sh -e "${ENV}" -a "${APP}"

编辑:

if [ "${ENVIRONMENT}" == 'stage' ]; then 
    IP="${IP_S[@]}" 
elif [ "${ENVIRONMENT}" == 'prod' ]; then 
    IP="${IP_P}" 
fi 

for host in ${IP}; do 

    echo "---------------------------------------" 
    echo "## Running yum update on ${host}" 
    echo "---------------------------------------" 


    if [ "${REBOOT}" == 'y' ]; then 
        ssh -i "${id_rsa}" -o StrictHostKeyChecking=no dvopsadmin@${host} "uname -a; df -h" 
    elif [ "${REBOOT}" == 'n' ]; then 
        ssh -i "${id_rsa}" -o StrictHostKeyChecking=no user@${host} "uname -a" 
    fi 
done