Skip to content

Instantly share code, notes, and snippets.

@dvinciguerra
Last active December 10, 2021 19:08
Show Gist options
  • Save dvinciguerra/f28407764559e6a63a35ba4c1b2e5ca6 to your computer and use it in GitHub Desktop.
Save dvinciguerra/f28407764559e6a63a35ba4c1b2e5ca6 to your computer and use it in GitHub Desktop.
Ruby script to update Cloudflare IP address
#!ruby
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'dotenv', require: 'dotenv/load'
gem 'cloudflare'
gem 'faraday'
end
# check required env variables
Dotenv.require_keys(
"CLOUDFLARE_TOKEN",
"CLOUDFLARE_ZONE_NAME",
"CLOUDFLARE_DNS_RECORD_NAME",
)
# Class to provide your network ip
module NetworkIp
NETWORK_IP_PROVIDER = ENV.fetch('NETWORK_IP_PROVIDER', 'https://api.ipify.org')
extend self
# Returns network IP address
def get
response = Faraday.get(NETWORK_IP_PROVIDER)
raise Faraday::Error, response unless response.success?
response.body
end
end
# Class to provide a simple cloudflare configurations interface
module Cloudflare
module Configurations
CLOUDFLARE_TOKEN = ENV['CLOUDFLARE_TOKEN']
CLOUDFLARE_ZONE_NAME = ENV['CLOUDFLARE_ZONE_NAME']
CLOUDFLARE_DNS_RECORD_NAME = ENV['CLOUDFLARE_DNS_RECORD_NAME']
extend self
# Returns the configured Cloudflare API token
def token
CLOUDFLARE_TOKEN
end
# Returns the configured Cloudflare DNS Zone name
def zone_name
CLOUDFLARE_ZONE_NAME
end
# Returns the configured Cloudflare DNS Record name
def dns_record_name
CLOUDFLARE_DNS_RECORD_NAME
end
end
end
network_ip = NetworkIp.get
Cloudflare.connect(token: Cloudflare::Configurations.token) do |cloudflare|
zone = cloudflare.zones.find_by_name(Cloudflare::Configurations.zone_name)
dns_record = zone.dns_records.find_by_name(Cloudflare::Configurations.dns_record_name)
dns_record.update_content(network_ip, proxied: true)
end
__END__
# Criar um token API
https://dash.cloudflare.com/profile/api-tokens
# Testando Token
curl -X GET "https://api.cloudflare.com/client/v4/user/tokens/verify" \
-H "Authorization: Bearer [CLOUDFLARE_TOKEN]" \
-H "Content-Type:application/json"
# Listando Zonas DNS
curl -X GET "https://api.cloudflare.com/client/v4/zones" \
-H "Authorization: Bearer [CLOUDFLARE_TOKEN]" \
-H "Content-Type:application/json"
# Listando Records do DNS
curl -X GET "https://api.cloudflare.com/client/v4/zones/[CLOUDFLARE_ZONE_ID]/dns_records" \
-H "Authorization: Bearer [CLOUDFLARE_TOKEN]" \
-H "Content-Type:application/json"
# Obtendo o IP atual
https://api.ipify.org
# Atualizando o IP do Record do DNS
curl -X PUT "https://api.cloudflare.com/client/v4/zones/[CLOUDFLARE_ZONE_ID]/dns_records/[CLOUDFLARE_DNS_RECORD_ID]" \
-H "Authorization: Bearer [CLOUDFLARE_TOKEN]" \
-H "Content-Type: application/json" \
--data '{"type":"A","name":"foo.example.com","content":"127.0.0.1","ttl":1,"proxied":true}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment