I am trying to dynamically create a upstream.nginx.conf file which only holds the content of upstream block in nginx which I will include in the main nginx.conf. I am trying to write a shell script to create this based on the environment variables provided in to the docker container (nginx:stable-alpine) using wildcard fetch.
The environment variables are $STABLESERVER1=sss1.int.com $STABLESERVER2=sss2.int.com
The shell script should write the file with the content by fetching the environment variables starting with STABLES*
upstream WebPool {
server sss1.int.com;
server sss2.int.com;
}
With no knowledge of shell scripting, I have written so far
#! /bin/sh
printenv | grep "^STABLES" | while read line; do
echo "server ${line#*=};"
done > upstream.nginx.conf
I am not sure how to add "upstream {" at the top and "}" at the bottom
CodePudding user response:
Assuming I have printenv with:
$STABLESERVER1=sss1.int.com
$STABLESERVER2=sss2.int.com
I would do something like:
#!/bin/sh
# ! replace this line with your command !
readonly SERVERS=$(cat ./printEnvResult | grep "STABLES*")
# ! replace this with output file name !
readonly FILENAME="output.file"
echo -e "upstream WebPool {" > ${FILENAME}
for i in ${SERVERS};
do
echo -e "\tserver $(echo ${i} | cut -d'=' -f2);" >> ${FILENAME}
done
echo -e "}" >> ${FILENAME}
Output will be:
upstream WebPool {
server sss1.int.com;
server sss2.int.com;
}
I tested this with a file instead of printenv output.