06/08/2015

Working with CloudFlare API - Python

If you ask me, I will say that CloudFlare is one of the best companies appeared in last few years! CloudFlare came to fill a real need in the market! Whether as CDN (Content Delivery Network) or as security layer.

And especially from security perspective, before CloudFlare to deal with a DDoS attack, you have to make your cloud, you're going to setup number of VPSs -with right configuration- as cloud in front of your network or server, but with CloudFlare you can enable DDoS protection with just one click! (Actually, for economic reasons, a lot of clients still ask for this handmade cloud rather than CloudFlare).

Anyway, I used to use Bash when I working with CloudFlare API. Previously, I made a bash script to monitor group of active load-balancers, and if one of those active load-balancers is down, the script will remove it form CloudFlare and add another one from passive load-balancers group.

Recently I needed to make Dynamic DNS Client (DDclient) works with CloudFlare. In other words, makes CloudFlare to point to local machine every time IP of this machine is changed. This useful when you need to access your home machine from outside the network.

In fact, there are a lot of python libraries and scripts to work with CloudFlare like pyflare and python-cloudflare, but I think it was a good chance to play with Python.

Actually I didn't put a lot of effort in it, all variables are hard-coded, I kept it simple as possible, and all other options can be added with small modifications based on CloudFlare documentation. I ended up with this:
#! /bin/python
#
#Edit/update CloudFlare record with machine IP, this script working like ddclient.
#More info at CloudFlare Client API Documentation: https://www.cloudflare.com/docs/client-api.html
#

import json
import urllib

#==============================
##Main variables.
#Your CloudFlare key:
#https://support.cloudflare.com/hc/en-us/articles/200167836-Where-do-I-find-my-CloudFlare-API-key-
key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
cloudflare_api="https://www.cloudflare.com/api_json.html"
main_domain="example.com"
sub_domain="sub.example.com"
email="youremail@domain.com"
record_type = "A"

#==============================
##Functions.
#Get record ID based on domain name and record type.
def get_record_id(record_name, record_type):
    decoded_records = json.loads(all_domain_info)
    for record in decoded_records['response']['recs']['objs']:
        if record['name'] == record_name and record['type'] == record_type:
            record_id = record['rec_id']
    return record_id

#Send request to Cloudflare API with specific parameters.
def connect_cloudflare(parameters):
    url_parameters = urllib.urlencode(parameters)
    request_output = urllib.urlopen(cloudflare_api, url_parameters)
    return request_output

#==============================
##Rest of script.
#All domain information parameters.
get_all_domain = {
    'a': 'rec_load_all',
    'tkn': key,
    'email': email,
    'z': main_domain
}

#Get all info about the main domain.
all_domain_info = connect_cloudflare(get_all_domain).read()

#Get ID of subdomain record.
record_id = get_record_id(sub_domain, record_type)

#Get current machine IP.
current_machine_ip = urllib.urlopen("http://ifconfig.me/ip").read().strip()

#Edit domain parameters.
edit_domain = {
    'a': 'rec_edit',
    'tkn': key,
    'id': record_id,
    'email': email,
    'z': main_domain,
    'type': record_type,
    'name': sub_domain,
    'content': current_machine_ip,
    'service_mode': 0,
    'ttl': 1 
}

#Send post request to Cloudflare API to edit domin IP.
connect_cloudflare(edit_domain)
Powered by Blogger.

Hello, my name is Ahmed AbouZaid, I'm a passionate Tech Lead DevOps Engineer. 👋

I specialize in Cloud-Native and Kubernetes. I'm also a Free/Open source geek and book author. My favorite topics are DevOps transformation, DevSecOps, automation, data, and metrics.

More about me ➡️

Contact Me

Name

Email *

Message *

Start Your DevOps Engineer Journey!

Start Your DevOps Engineer Journey!
Start your DevOps career for free the Agile way in 2024 with the Dynamic DevOps Roadmap ⭐

Latest Post

Bootstrap Cloud-Native bootstrappers like Crossplane with K3d - Automation

I created a logo for the Crossplane Bootstrapper because all good projects deserve a logo. 😁 TL;DR ...

Popular Posts

Blog Archive