Certainly! To automate the process of configuring Cloudflare subdomains to point to a DigitalOcean droplet, you can use Cloudflare’s API along with the DigitalOcean API. Below is a high-level outline of the steps involved:
- DigitalOcean: Obtain the IP address of your droplet using the DigitalOcean API.
- Cloudflare: Use the Cloudflare API to add or update DNS records for your subdomain.
Here’s an example using Python with the requests
library to interact with both APIs:
import requests
# DigitalOcean API credentials
do_token = "YOUR_DIGITALOCEAN_API_TOKEN"
droplet_id = "YOUR_DROPLET_ID"
# Cloudflare API credentials
cf_email = "YOUR_CLOUDFLARE_EMAIL"
cf_token = "YOUR_CLOUDFLARE_API_TOKEN"
cf_zone_id = "YOUR_CLOUDFLARE_ZONE_ID"
subdomain = "sub.example.com"
# Get Droplet's IP address from DigitalOcean
def get_droplet_ip():
url = f"https://api.digitalocean.com/v2/droplets/{droplet_id}"
headers = {'Authorization': f'Bearer {do_token}'}
response = requests.get(url, headers=headers)
data = response.json()
if response.status_code == 200:
return data['droplet']['networks']['v4'][0]['ip_address']
else:
print("Failed to get droplet IP:", data)
return None
# Update DNS record on Cloudflare
def update_dns_record(ip_address):
url = f"https://api.cloudflare.com/client/v4/zones/{cf_zone_id}/dns_records"
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {cf_token}'
}
payload = {
'type': 'A',
'name': subdomain,
'content': ip_address,
'ttl': 1,
'proxied': True # Set to True if you want Cloudflare proxy
}
response = requests.post(url, headers=headers, json=payload)
data = response.json()
if response.status_code == 200:
print("DNS record updated successfully:", data)
else:
print("Failed to update DNS record:", data)
# Main function
def main():
droplet_ip = get_droplet_ip()
if droplet_ip:
update_dns_record(droplet_ip)
if __name__ == "__main__":
main()
Remember to replace placeholders like YOUR_DIGITALOCEAN_API_TOKEN
, YOUR_DROPLET_ID
, YOUR_CLOUDFLARE_EMAIL
, YOUR_CLOUDFLARE_API_TOKEN
, and YOUR_CLOUDFLARE_ZONE_ID
with your actual credentials. Also, adjust the subdomain
variable to match your desired subdomain.
This script will fetch the IP address of your DigitalOcean droplet and then update the DNS record for the specified subdomain on Cloudflare to point to that IP address. Make sure you have appropriate permissions and API tokens set up for both DigitalOcean and Cloudflare.