Created
June 6, 2024 13:29
-
-
Save godismyjudge95/fbcc13fbe63aceca8fc2371473e66741 to your computer and use it in GitHub Desktop.
Update Cloudflare IPs for NGINX
This file contains 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 | |
# Install deps | |
apt install jq -y | |
# Define the URL of the Cloudflare IPs API | |
api_url="https://api.cloudflare.com/client/v4/ips" | |
# Define the output file | |
output_file="/etc/nginx/snippets/cloudflare.conf" | |
# Fetch the JSON data from the Cloudflare IPs API | |
json_data=$(curl -s $api_url) | |
# Check if the curl command was successful | |
if [ $? -ne 0 ]; then | |
echo "Could not GET cloudflare IPs" | |
exit 1 | |
fi | |
# Extract the etag, IPv4, and IPv6 CIDRs using jq | |
etag=$(echo $json_data | jq -r '.result.etag') | |
ipv4_cidrs=$(echo $json_data | jq -r '.result.ipv4_cidrs[]') | |
ipv6_cidrs=$(echo $json_data | jq -r '.result.ipv6_cidrs[]') | |
# Get the current time | |
time=$(date) | |
# Initialize the configuration strings | |
ipv4_conf="" | |
ipv6_conf="" | |
# Loop over each IPv4 CIDR and append it to the configuration string | |
for ipv4 in $ipv4_cidrs; do | |
ipv4_conf+="set_real_ip_from $ipv4;\n" | |
done | |
# Loop over each IPv6 CIDR and append it to the configuration string | |
for ipv6 in $ipv6_cidrs; do | |
ipv6_conf+="set_real_ip_from $ipv6;\n" | |
done | |
# Write the configuration to the output file | |
{ | |
echo "# Cloudflare IPs ($api_url etag: $etag)" | |
echo "# Auto Generated" | |
echo "# by $(realpath "$0")" | |
echo "# at $time" | |
echo "" | |
echo "# IPv4:" | |
echo -e "$ipv4_conf" | |
echo "# IPv6:" | |
echo -e "$ipv6_conf" | |
echo "real_ip_header CF-Connecting-IP;" | |
} > $output_file | |
# Close the file and print a success message | |
echo "Updated $output_file OK" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment