Skip to content

Instantly share code, notes, and snippets.

@iurisilvio
Created June 15, 2020 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iurisilvio/bf752364883028856b63d1817600c095 to your computer and use it in GitHub Desktop.
Save iurisilvio/bf752364883028856b63d1817600c095 to your computer and use it in GitHub Desktop.
aws ips to nginx
TMP_CONF=/tmp/awsips.conf
NGINX_CONF=/etc/nginx/conf.d/awsips.conf
AWS_REGION=$(curl http://169.254.169.254/latest/dynamic/instance-identity/document | jq .region | tr -d \")
if ! sudo nginx -t; then
echo CURRENT NGINX CONFIG IS BROKEN
exit 1
fi
curl https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r ".prefixes[] | select(.region==\"$AWS_REGION\" and .service==\"AMAZON\").ip_prefix" | xargs -i echo set_real_ip_from {}\; | sort > $TMP_CONF
if [[ $(wc -l <$TMP_CONF) -le 10 ]]; then
cat $TMP_CONF
echo AWS IPS TOO SHORT
rm $TMP_CONF
exit 1
fi
if cmp $TMP_CONF $NGINX_CONF; then
echo AWS IPS NOT CHANGED
rm $TMP_CONF
exit 0
fi
sudo cp $NGINX_CONF $NGINX_CONF.last
sudo mv $TMP_CONF $NGINX_CONF
if ! sudo nginx -t; then
cat $NGINX_CONF
echo NEW NGINX CONFIG WAS BROKEN, REVERTED TO CURRENT CONFIG
sudo cp $NGINX_CONF $NGINX_CONF.broken
sudo cp $NGINX_CONF.last $NGINX_CONF
exit 1
fi
sudo service nginx reload && echo 'NGINX RELOADED'
echo AWS IPS UPDATED
# /etc/nginx/conf.d/realip.conf
real_ip_header X-Forwarded-For;
real_ip_recursive on;
# change to your VPC mask
set_real_ip_from 172.31.0.0/16;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment