nginx-deny-include.sh 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env bash
  2. # Pull the IRDB blocklist and write an nginx `deny` include file.
  3. # Reload nginx atomically only if the file changed.
  4. #
  5. # Usage (cron):
  6. # IRDB_URL=http://localhost:8081 IRDB_TOKEN=irdb_con_... \
  7. # OUTPUT=/etc/nginx/conf.d/irdb-deny.conf \
  8. # examples/consumers/nginx-deny-include.sh
  9. #
  10. # In your nginx config, include the file inside a `server {}` block:
  11. #
  12. # server {
  13. # ...
  14. # include /etc/nginx/conf.d/irdb-deny.conf;
  15. # }
  16. #
  17. # The script is idempotent: if the new file content matches what's
  18. # already on disk, nginx is left alone.
  19. set -euo pipefail
  20. : "${IRDB_URL:?must be set}"
  21. : "${IRDB_TOKEN:?must be set}"
  22. OUTPUT="${OUTPUT:-/etc/nginx/conf.d/irdb-deny.conf}"
  23. TIMEOUT="${IRDB_TIMEOUT:-30}"
  24. TMP=$(mktemp)
  25. trap 'rm -f "$TMP"' EXIT
  26. # Header makes the include file self-describing.
  27. {
  28. echo "# Generated by examples/consumers/nginx-deny-include.sh"
  29. echo "# Updated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
  30. } > "$TMP"
  31. curl -fsS --max-time "$TIMEOUT" \
  32. -H "Authorization: Bearer $IRDB_TOKEN" \
  33. -H "Accept: text/plain" \
  34. "$IRDB_URL/api/v1/blocklist" \
  35. | while IFS= read -r line; do
  36. [ -z "$line" ] && continue
  37. echo "deny $line;"
  38. done >> "$TMP"
  39. # Only reload nginx if the file actually changed.
  40. if [ -f "$OUTPUT" ] && cmp -s "$OUTPUT" "$TMP"; then
  41. echo "irdb-blocklist unchanged; nginx not reloaded"
  42. exit 0
  43. fi
  44. mv "$TMP" "$OUTPUT"
  45. trap - EXIT
  46. # `nginx -t` first so we never reload onto a syntax error.
  47. nginx -t
  48. nginx -s reload
  49. echo "irdb-blocklist written to $OUTPUT; nginx reloaded"