Last active
January 27, 2019 09:31
-
-
Save imvaskii/25416e0741ddadee97b7c99852bf4d56 to your computer and use it in GitHub Desktop.
Dynamically bulid nginx.conf #jq #nginx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
upstream_json="upstream-servers.json" | |
if [ ! -f $upstream_json ]; then | |
echo "$upstream_json does not exists" | |
return | |
exit "$@" | |
fi | |
json=$(jq -c '.[]' $upstream_json) | |
for line in $json | |
do | |
name=$(echo "$line" | jq -r .'upstream.name') | |
server=$(echo "$line" | jq -r .'upstream.addresses.address | .[].name'); | |
upstream_block=$( | |
printf '%s | |
upstream %s { | |
server %s; | |
} | |
' "$upstream_block" "$name" "$server" | |
) | |
listen=$(echo "$line" | jq -r .'server.listen') | |
server_name=$(echo "$line" | jq -r .'server.name') | |
path=$(echo "$line" | jq -r .'server.location.path ') | |
proxy_pass=$(echo "$line" | jq -r .'server.location.proxy_pass ') | |
proxy_redirect=$(echo "$line" | jq -r .'server.location.proxy_redirect ') | |
server_block=$( | |
printf '%s | |
server { | |
listen %s; | |
server_name %s | |
location %s { | |
proxy_pass %s | |
proxy_redirect %s | |
} | |
} | |
' "$server_block" "$listen" "$server_name" "$path" "$proxy_pass" "$proxy_redirect" | |
) | |
done; | |
http=$( | |
printf ' | |
sendfile on; | |
proxy_set_header Host $host; | |
proxy_set_header X-Real-IP $remote_addr; | |
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; | |
proxy_set_header X-Forwarded-Host $server_name;' | |
) | |
echo "worker_processes 1; | |
events { | |
worker_connections 1024; | |
} | |
http { | |
$http | |
$upstream_block | |
$server_block | |
}" > nginx.conf |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"upstream": { | |
"name": "site_a", | |
"addresses": { | |
"address": [ | |
{ | |
"name": "site_a", | |
"args": {} | |
} | |
] | |
} | |
}, | |
"server": { | |
"name": "my-site-a", | |
"listen": 80, | |
"location": { | |
"path": "/", | |
"proxy_pass": "http://site_a;", | |
"proxy_redirect": "off" | |
} | |
} | |
}, | |
{ | |
"upstream": { | |
"name": "site_b", | |
"addresses": { | |
"address": [ | |
{ | |
"name": "site_b", | |
"args": {} | |
} | |
] | |
} | |
}, | |
"server": { | |
"name": "my-site-a", | |
"listen": 80, | |
"location": { | |
"path": "/", | |
"proxy_pass": "http://site_b;", | |
"proxy_redirect": "off" | |
} | |
} | |
} | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment