Shell脚本创建Nginx的upstream及location配置文件

#!/bin/sh
#####################################################
#    Name:                create_nginx_conf.sh
#    Version:            V1.0
#    Author:            运维菜鸟
#    Description:        创建nginx相关配置文件    
#    Create Date:        2017-07-04
#    Email:            
#####################################################

#env.sh文件内容格式:10.10.2.6=basics-price-service;

#function_name:要调用的方法
function_name=$1
#ns_type:项目环境名称
ns_type=$2
#env_file:env.sh文件具体路径
env_file_path=$3

#判断env.sh是否存在
function check_env_file() {
    if [ -f ${env_file_path} ];then
        echo "the ${env_file_path} is exist."
        echo -e "

"
    else
        echo "the ${env_file_path} is not exist."
        exit 1
    fi
}

#生成nginx的location段的配置文件
function create_location(){
    for pool in `cat ${env_file_path} | cut -d "=" -f2 | cut -d ";" -f1 | sort | uniq`;do
        echo -e "location /${pool} {
	proxy_pass http://${ns_type}-${pool}/${pool};
	proxy_set_header Host $host;
	proxy_set_header X-Real-IP $remote_addr;
	proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
	break;
}" 
    done
}

#生成nginx的upstream配置文件
function create_upstream_conf() {
    for pool in `cat ${env_file_path} | cut -d "=" -f2 | cut -d ";" -f1 | sort | uniq`;do
        ip_list=`cat ${env_file_path} | egrep "${pool};" | cut -d "=" -f1  | sort |uniq`
        #pool_port=`cat env.sh | egrep "${pool}=" | cut -d "=" -f3 | cut -d ";" -f1| sort | uniq`
        echo -e "upstream ${ns_type}-${pool} {"
        for ip in ${ip_list[*]};do
            echo -e "	server ${ip}:8080;"
        done
        echo  "}"
    done
}

if [ $# -eq 3 ];then
    case $1 in
        location)
            check_env_file;
            create_location;
            ;;
        upstream)
            check_env_file;
            create_upstream_conf;
            ;;
        *)
            $"Usage: {sh create_nginx_conf.sh location hh-prod /data/env.sh|sh create_nginx_conf.sh upstream hh-prod /data/env.sh}"
            exit 3
    esac
else
    echo "variables count not eq 5.please check the usage."
    echo "Usage: {sh create_nginx_conf.sh location hh-prod /data/env.sh|sh create_nginx_conf.sh upstream hh-prod /data/env.sh}."
fi