Skip to main content

Advanced Use Cases

Production-ready patterns for DNS automation, failover, deployment strategies, and security configurations.

Dynamic DNS with Failover

Automatically update DNS when servers go down.

Health Check and Failover

import requests
import time

class DNSFailover:
def __init__(self, api_key, zone_id, record_id):
self.api_key = api_key
self.zone_id = zone_id
self.record_id = record_id
self.base_url = 'https://api.wayscloud.services/v1/dns'

def check_server_health(self, url):
"""Check if server is responding"""
try:
response = requests.get(url, timeout=5)
return response.status_code == 200
except:
return False

def update_dns(self, ip_address, ttl=60):
"""Update DNS record"""
url = f'{self.base_url}/zones/{self.zone_id}/records/{self.record_id}'
headers = {
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json'
}
data = {'value': ip_address, 'ttl': ttl}

response = requests.put(url, json=data, headers=headers)
response.raise_for_status()
return response.json()

def monitor(self, primary_ip, backup_ip, check_interval=30):
"""Monitor and failover between primary and backup"""
current_ip = primary_ip

while True:
if self.check_server_health(f'http://{primary_ip}'):
# Primary is healthy
if current_ip != primary_ip:
print(f"Switching back to primary: {primary_ip}")
self.update_dns(primary_ip, ttl=60)
current_ip = primary_ip
else:
# Primary is down, switch to backup
print(f"Primary down, switching to backup: {backup_ip}")
self.update_dns(backup_ip, ttl=60)
current_ip = backup_ip

time.sleep(check_interval)

# Usage
failover = DNSFailover(
api_key='wayscloud_dns_prod_YOUR_API_KEY',
zone_id='zone_abc123',
record_id='rec_001'
)

failover.monitor(
primary_ip='192.0.2.1',
backup_ip='192.0.2.2',
check_interval=30
)

Blue-Green Deployment

Switch traffic between two application versions using DNS.

Deployment Strategy

import time

def blue_green_deploy(api, zone_id, record_id, blue_ip, green_ip):
"""
Blue-green deployment workflow:
1. Deploy to green environment
2. Test green environment
3. Switch DNS from blue to green
4. Keep blue as fallback
"""

print("Step 1: Deploying to green environment...")
deploy_to_green(green_ip) # Your deployment logic

print("Step 2: Testing green environment...")
if not test_environment(f'http://{green_ip}'):
print("✗ Green deployment failed, staying on blue")
return False

print("Step 3: Lowering TTL before switch...")
api.update_record(zone_id, record_id, ttl=60)
time.sleep(60) # Wait for TTL to expire

print(f"Step 4: Switching traffic to green: {green_ip}")
api.update_record(zone_id, record_id, value=green_ip, ttl=60)

print("Step 5: Monitoring green environment for 10 minutes...")
time.sleep(600)

if test_environment(f'http://{green_ip}'):
print("✓ Green deployment successful, increasing TTL")
api.update_record(zone_id, record_id, ttl=3600)
return True
else:
print("✗ Issues detected, rolling back to blue")
api.update_record(zone_id, record_id, value=blue_ip, ttl=3600)
return False

# Usage
success = blue_green_deploy(
api=dns_api,
zone_id='zone_abc123',
record_id='rec_001',
blue_ip='192.0.2.1',
green_ip='192.0.2.100'
)

Email Authentication

Complete email configuration with SPF, DKIM, and DMARC.

Email Setup Function

def setup_email_authentication(api, zone_id, domain, mail_provider="google"):
"""
Configure complete email authentication:
- SPF (Sender Policy Framework)
- DKIM (DomainKeys Identified Mail)
- DMARC (Domain-based Message Authentication, Reporting & Conformance)
"""

records = []

# SPF Record
if mail_provider == "google":
spf_value = "v=spf1 include:_spf.google.com ~all"
elif mail_provider == "microsoft":
spf_value = "v=spf1 include:spf.protection.outlook.com ~all"
elif mail_provider == "sendgrid":
spf_value = "v=spf1 include:sendgrid.net ~all"
else:
spf_value = "v=spf1 mx ~all"

records.append({
'type': 'TXT',
'name': '@',
'value': spf_value,
'ttl': 3600
})
print(f"✓ SPF record: {spf_value}")

# DMARC Record
dmarc_value = f"v=DMARC1; p=quarantine; rua=mailto:dmarc@{domain}; pct=100"
records.append({
'type': 'TXT',
'name': '_dmarc',
'value': dmarc_value,
'ttl': 3600
})
print(f"✓ DMARC record: {dmarc_value}")

# DKIM Record (get from email provider)
print("⚠ Don't forget to add DKIM record from your email provider")
print(" Google Workspace: Admin Console → Apps → Google Workspace → Gmail → Authenticate email")
print(" Microsoft 365: Admin Center → Setup → Domains → Select domain → DNS settings")

# Create records
api.batch_create_records(zone_id, records)

return records

# Usage
setup_email_authentication(
api=dns_api,
zone_id='zone_abc123',
domain='example.com',
mail_provider='google'
)

DKIM Configuration

def add_dkim_record(api, zone_id, selector, public_key):
"""
Add DKIM record for email authentication

Args:
selector: DKIM selector (e.g., 'default', 'google', 'k1')
public_key: Public key from email provider
"""

dkim_name = f'{selector}._domainkey'
dkim_value = f'v=DKIM1; k=rsa; p={public_key}'

record = api.create_record(
zone_id=zone_id,
record_type='TXT',
name=dkim_name,
value=dkim_value,
ttl=3600
)

print(f"✓ DKIM record created: {dkim_name}")
return record

# Usage
add_dkim_record(
api=dns_api,
zone_id='zone_abc123',
selector='google',
public_key='MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC...'
)

CAA Records for Certificate Security

Restrict which certificate authorities can issue certificates.

CAA Configuration

def setup_caa_records(api, zone_id, allowed_cas=None):
"""
Configure CAA records to restrict certificate issuance

Args:
allowed_cas: List of CAs (e.g., ['letsencrypt.org', 'digicert.com'])
"""

if allowed_cas is None:
allowed_cas = ['letsencrypt.org'] # Default to Let's Encrypt

records = []

# Allow certificate issuance
for ca in allowed_cas:
records.append({
'type': 'CAA',
'name': '@',
'value': f'0 issue "{ca}"',
'ttl': 3600
})
print(f"✓ CAA record for: {ca}")

# Allow wildcard certificates
for ca in allowed_cas:
records.append({
'type': 'CAA',
'name': '@',
'value': f'0 issuewild "{ca}"',
'ttl': 3600
})
print(f"✓ CAA wildcard record for: {ca}")

# Incident reporting
records.append({
'type': 'CAA',
'name': '@',
'value': '0 iodef "mailto:security@example.com"',
'ttl': 3600
})
print("✓ CAA incident reporting configured")

# Create all records
api.batch_create_records(zone_id, records)

return records

# Usage
setup_caa_records(
api=dns_api,
zone_id='zone_abc123',
allowed_cas=['letsencrypt.org', 'digicert.com']
)

Geographic Load Balancing

Distribute traffic based on geographic location (using multiple A records).

Round-Robin DNS

def setup_geo_load_balancing(api, zone_id, servers):
"""
Setup round-robin DNS for load balancing

Args:
servers: List of server IPs
"""

records = []

for ip in servers:
records.append({
'type': 'A',
'name': 'www',
'value': ip,
'ttl': 300 # Lower TTL for faster failover
})
print(f"✓ Added server: {ip}")

api.batch_create_records(zone_id, records)

print(f"✓ Round-robin DNS configured with {len(servers)} servers")
return records

# Usage
setup_geo_load_balancing(
api=dns_api,
zone_id='zone_abc123',
servers=[
'192.0.2.1', # Server 1
'192.0.2.2', # Server 2
'192.0.2.3' # Server 3
]
)

Automated DNS Management

Infrastructure as Code

class DNSZoneManager:
"""Manage DNS zone configuration as code"""

def __init__(self, api_key, zone_id):
self.api_key = api_key
self.zone_id = zone_id
self.api = DNSClient(api_key)

def apply_configuration(self, config):
"""
Apply DNS configuration from dict

config = {
'records': [
{'type': 'A', 'name': 'www', 'value': '192.0.2.1'},
...
]
}
"""

# Get existing records
existing = self.api.list_records(self.zone_id)
existing_map = {f"{r['type']}:{r['name']}": r for r in existing['records']}

# Determine changes
to_create = []
to_update = []
to_delete = []

# Check each desired record
for desired in config['records']:
key = f"{desired['type']}:{desired['name']}"

if key in existing_map:
# Record exists, check if update needed
existing_record = existing_map[key]
if (existing_record['value'] != desired['value'] or
existing_record.get('ttl') != desired.get('ttl', 3600)):
to_update.append((existing_record['record_id'], desired))
else:
# New record
to_create.append(desired)

# Find records to delete
desired_keys = {f"{r['type']}:{r['name']}" for r in config['records']}
for key, record in existing_map.items():
if key not in desired_keys:
to_delete.append(record['record_id'])

# Apply changes
print(f"Changes: {len(to_create)} create, {len(to_update)} update, {len(to_delete)} delete")

if to_create:
self.api.batch_create_records(self.zone_id, to_create)

if to_update:
for record_id, updates in to_update:
self.api.update_record(self.zone_id, record_id, **updates)

if to_delete:
self.api.batch_delete_records(self.zone_id, to_delete)

print("✓ Configuration applied")

# Usage
manager = DNSZoneManager(
api_key='wayscloud_dns_prod_YOUR_API_KEY',
zone_id='zone_abc123'
)

config = {
'records': [
{'type': 'A', 'name': 'www', 'value': '192.0.2.1', 'ttl': 3600},
{'type': 'A', 'name': 'api', 'value': '192.0.2.2', 'ttl': 3600},
{'type': 'MX', 'name': '@', 'value': 'mail.example.com', 'priority': 10},
]
}

manager.apply_configuration(config)

Terraform Integration

Manage DNS with Terraform:

terraform {
required_providers {
restapi = {
source = "Mastercard/restapi"
version = "1.18.0"
}
}
}

provider "restapi" {
uri = "https://api.wayscloud.services/v1/dns"
headers = {
Authorization = "Bearer ${var.wayscloud_api_key}"
Content-Type = "application/json"
}
}

# Create DNS zone
resource "restapi_object" "dns_zone" {
path = "/zones"
data = jsonencode({
domain = "example.com"
dnssec_enabled = true
default_ttl = 3600
})
}

# A Record
resource "restapi_object" "www_record" {
path = "/zones/${restapi_object.dns_zone.id}/records"
data = jsonencode({
type = "A"
name = "www"
value = var.web_server_ip
ttl = 3600
})
}

# MX Record
resource "restapi_object" "mx_record" {
path = "/zones/${restapi_object.dns_zone.id}/records"
data = jsonencode({
type = "MX"
name = "@"
value = "mail.example.com"
priority = 10
ttl = 3600
})
}

# Output nameservers
output "nameservers" {
value = jsondecode(restapi_object.dns_zone.api_response).nameservers
}

Best Practices Summary

1. Lower TTL Before Changes

# Before making changes
record.update(ttl=300)
time.sleep(3600) # Wait for old TTL to expire

# Make changes
record.update(value='192.0.2.100')

# Monitor
time.sleep(600)

# Restore TTL
record.update(ttl=3600)

2. Implement Health Checks

def health_check(url, timeout=5, retries=3):
"""Robust health checking with retries"""
for attempt in range(retries):
try:
response = requests.get(url, timeout=timeout)
if response.status_code == 200:
return True
except:
pass
time.sleep(1)
return False

3. Log All Changes

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def update_dns_with_logging(api, zone_id, record_id, **kwargs):
"""Update DNS record with logging"""
logger.info(f"Updating record {record_id}: {kwargs}")

try:
result = api.update_record(zone_id, record_id, **kwargs)
logger.info(f"✓ Update successful: {result}")
return result
except Exception as e:
logger.error(f"✗ Update failed: {e}")
raise

4. Test Before Production

# Test on staging domain first
test_result = deploy_to_dns('staging.example.com')
if test_result:
# Deploy to production
deploy_to_dns('example.com')

Next Steps