### Install UltraDNS REST Client using pip Source: https://github.com/ultradns/python_rest_api_client/blob/master/README.md Command to install the ultra_rest_client package and its dependencies (requests library) using pip package manager. ```bash pip install ultra_rest_client ``` -------------------------------- ### Complete DNS Management Workflow with Python Source: https://context7.com/ultradns/python_rest_api_client/llms.txt An end-to-end example showcasing a full DNS management workflow using the `ultra-rest-client` library. It covers initialization, creating zones and various record types, batch operations, snapshots, exports, health checks, and cleanup. ```python #!/usr/bin/env python3 from ultra_rest_client import RestApiClient, TaskHandler import os import sys def main(): # Initialize client username = os.getenv('USERNAME') password = os.getenv('PASSWORD') if not username or not password: print("Error: USERNAME and PASSWORD must be set") sys.exit(1) client = RestApiClient(username, password) domain = "automation-test.com." try: # Get account details print("=== Getting account information ===") account_details = client.get_account_details() account_name = account_details['accounts'][0]['accountName'] print(f"Account: {account_name}") # Create zone print(f"\n=== Creating zone {domain} ===") zone_response = client.create_primary_zone(account_name, domain) print(f"Zone created: {zone_response}") # Create DNS records print("\n=== Creating DNS records ===") # Apex A record client.create_rrset(domain, "A", domain, 300, "192.0.2.1") print("Created apex A record") # WWW CNAME client.create_rrset(domain, "CNAME", f"www.{domain}", 300, [domain]) print("Created www CNAME") # MX records client.create_rrset(domain, "MX", domain, 300, ["10 mail1." + domain, "20 mail2." + domain]) print("Created MX records") # SPF TXT record client.create_rrset(domain, "TXT", domain, 300, ['"v=spf1 mx -all"']) print("Created SPF record") # Create load balancing pool print("\n=== Creating RD pool ===") pool_response = client.create_rd_pool( domain, "pool", 300, ["192.0.2.10", "192.0.2.11", "192.0.2.12"], order="ROUND_ROBIN", description="Application server pool" ) print(f"Pool created: {pool_response}") # Batch create multiple records print("\n=== Batch creating API endpoints ===") batch_response = client.batch([ {'method': 'POST', 'uri': f'/v1/zones/{domain}/rrsets/A/api1', 'body': {'ttl': 300, 'rdata': ['192.0.2.20']}}, {'method': 'POST', 'uri': f'/v1/zones/{domain}/rrsets/A/api2', 'body': {'ttl': 300, 'rdata': ['192.0.2.21']}}, {'method': 'POST', 'uri': f'/v1/zones/{domain}/rrsets/A/api3', 'body': {'ttl': 300, 'rdata': ['192.0.2.22']}} ]) print(f"Batch create result: {batch_response}") # Create snapshot before making changes print("\n=== Creating zone snapshot ===") snapshot_response = client.create_snapshot(domain) snapshot_result = TaskHandler(snapshot_response, client) print(f"Snapshot created: {snapshot_result}") # Export zone print("\n=== Exporting zone ===") zone_data = client.export_zone(domain) print(f"Zone exported ({len(zone_data)} bytes)") # List all records print("\n=== Listing all records ===") all_records = client.get_rrsets(domain) print(f"Total RRSets: {len(all_records.get('rrSets', []))}") # Create health check print("\n=== Running health check ===") health_response = client.create_health_check(domain) health_result = TaskHandler(health_response, client, poll_interval=2) print(f"Health check result: {health_result}") # Cleanup print(f"\n=== Cleaning up (deleting {domain}) ===") delete_response = client.delete_zone(domain) print(f"Zone deleted: {delete_response}") print("\n=== Workflow completed successfully ===") except Exception as e: print(f"\nError: {e}") # Cleanup on error try: client.delete_zone(domain) print(f"Cleaned up zone {domain}") except: pass sys.exit(1) if __name__ == "__main__": main() ``` -------------------------------- ### Create Secondary Zone Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Illustrates the creation of a secondary zone that synchronizes its data from a specified master nameserver. Includes examples for both standard and TSIG-authenticated secondary zone creation. ```python from ultra_rest_client import RestApiClient import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) account_details = client.get_account_details() account_name = account_details['accounts'][0]['accountName'] # Create secondary zone without TSIG response = client.create_secondary_zone( account_name, "secondary.example.com.", master="203.0.113.20" ) print(f"Secondary zone created: {response}") # Create secondary zone with TSIG response = client.create_secondary_zone( account_name, "secure-secondary.example.com.", master="203.0.113.20", tsig_key="transferkey", key_value="SecretKeyValue==" ) print(f"Secure secondary zone created: {response}") ``` -------------------------------- ### Set Environment Variables for UltraDNS Client Source: https://github.com/ultradns/python_rest_api_client/blob/master/README.md This example shows how to set the necessary environment variables for username and password, which are required for authenticating with the UltraDNS REST API client. These variables should be set in your terminal before running the Python script. ```shell export USERNAME='your_username' export PASSWORD='your_password' ``` -------------------------------- ### Initialize Client with Custom Headers and Proxy (Python) Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Shows how to configure the REST API client with custom HTTP headers and proxy settings, suitable for corporate network environments. It includes examples of setting proxy dictionaries and custom headers during initialization, as well as updating them after the client has been created. Dependencies: 'ultra_rest_client'. ```python from ultra_rest_client import RestApiClient # Define proxy configuration proxy_dict = { "http": "http://proxy.example.com:8080", "https": "http://proxy.example.com:8080" } # Initialize with custom headers and proxy client = RestApiClient( "username", "password", custom_headers={"foo": "bar", "user-agent": "MyApp/1.0"}, proxy=proxy_dict, verify_https=False # Disable TLS verification if needed ) # Update headers after initialization client.rest_api_connection.set_custom_headers({"boo": "far"}) # Update proxy after initialization new_proxy = { "http": "http://newproxy.example.com:9090", "https": "http://newproxy.example.com:9090" } client.rest_api_connection.set_proxy(new_proxy) # Make API calls with custom configuration response = client.get_zones() ``` -------------------------------- ### Zone Management Operations Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Provides examples for common zone management tasks, including retrieving zone metadata (v1 and v3), forcing AXFR transfers, converting secondary zones to primary, resigning zones for DNSSEC, and deleting zones. ```python from ultra_rest_client import RestApiClient import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) # Get zone metadata (v1) metadata = client.get_zone_metadata("example.com.") print(f"Zone metadata: {metadata}") # Get zone metadata (v3) metadata_v3 = client.get_zone_metadata_v3("example.com.") print(f"Zone metadata v3: {metadata_v3}") # Force AXFR transfer (for secondary zones) response = client.force_axfr("secondary.example.com.") print(f"AXFR forced: {response}") # Convert secondary zone to primary response = client.convert_zone("secondary.example.com.") print(f"Zone converted: {response}") # Resign zone (DNSSEC) response = client.resign_zone("example.com.") print(f"Zone resigned: {response}") # Delete zone response = client.delete_zone("example.com.") print(f"Zone deleted: {response}") ``` -------------------------------- ### Generate Query Volume Reports with Python Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Provides examples for generating DNS query volume reports for capacity planning and traffic analysis. This includes creating projected query volume reports for an account and zone-specific query volume reports for a given time period. The ReportHandler can be used for automatic polling of report results. Requires RestApiClient and optionally ReportHandler. ```python from ultra_rest_client import RestApiClient, ReportHandler import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) # Get account name account_details = client.get_account_details() account_name = account_details['accounts'][0]['accountName'] # Create projected query volume report response = client.create_projected_query_volume_report( accountName=account_name, sortFields=['zoneName', 'queryCount'] ) result = ReportHandler(response, client, poll_interval=2, max_retries=30) print(f"Projected query volumes: {result}") # Output: {'zones': [ # {'zoneName': 'example.com', 'projectedQueries': 1000000, 'trend': 'UP'}, # {'zoneName': 'example.org', 'projectedQueries': 500000, 'trend': 'STABLE'} # ]} # Create zone query volume report for specific time period response = client.create_zone_query_volume_report( startDate='2024-01-01', endDate='2024-01-31', zoneQueryVolume=[ {'zoneName': 'example.com'}, {'zoneName': 'example.org'} ], sortFields=['timestamp'], offset=0, limit=1000 ) result = ReportHandler(response, client, poll_interval=2, max_retries=30) print(f"Zone query volumes: {result}") # Output: {'queryData': [ # {'zoneName': 'example.com', 'timestamp': '2024-01-01T00:00:00Z', # 'queryCount': 35000}, # {'zoneName': 'example.com', 'timestamp': '2024-01-01T01:00:00Z', # 'queryCount': 32000} # ]} ``` -------------------------------- ### Manage Tasks with Python REST API Client Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Illustrates how to monitor and manage background tasks for long-running operations using the UltraDNS Python REST API client. Examples include retrieving all tasks and checking the status of a specific task by its ID. Requires an initialized RestApiClient. ```python from ultra_rest_client import RestApiClient import os import time client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) # Get all tasks all_tasks = client.get_all_tasks() print(f"All tasks: {all_tasks}") # Output: {'tasks': [ # {'taskId': 'task-123', 'code': 'IN_PROCESS', 'message': 'Importing zone'}, # {'taskId': 'task-456', 'code': 'COMPLETE', 'message': 'Zone created'} # ]} # Get specific task status task_id = 'task-123' task_status = client.get_task(task_id) print(f"Task status: {task_status}") ``` -------------------------------- ### Create and Get Dangling CNAME Checks with Python Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Demonstrates how to create and retrieve dangling CNAME checks using the UltraDNS Python REST API client. This helps identify misconfigurations where a CNAME record points to a non-existent target. It requires an initialized RestApiClient instance. ```python from ultra_rest_client import RestApiClient, TaskHandler import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) zone = "example.com." # Create dangling CNAME check response = client.create_dangling_cname_check(zone) result = TaskHandler(response, client, poll_interval=2) print(f"Dangling CNAME check results: {result}") # Output: {'danglingCnames': [ # {'owner': 'broken.example.com.', 'target': 'nonexistent.example.net.'} # ]} # Get dangling CNAME check results dangling_results = client.get_dangling_cname_check(zone) print(f"Dangling CNAMEs: {dangling_results}") ``` -------------------------------- ### Initialize Client with Username/Password Auth (Python) Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Initializes the REST API client using username and password credentials. It demonstrates how to load credentials from environment variables, connect to the API, and retrieve basic account information. Dependencies include the 'ultra_rest_client' and 'os' libraries. ```python from ultra_rest_client import RestApiClient import os # Load credentials from environment username = os.getenv('USERNAME') password = os.getenv('PASSWORD') # Initialize client client = RestApiClient(username, password) # Verify connectivity print(client.version()) # Returns API version print(client.status()) # Returns API status # Get account information account_details = client.get_account_details() account_name = account_details['accounts'][0]['accountName'] print(f"Account: {account_name}") ``` -------------------------------- ### Manage Zone Snapshots with Python Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Shows how to create, retrieve, and restore zone snapshots for backup and rollback using the UltraDNS Python client. Utilizes TaskHandler for asynchronous operations. ```python from ultra_rest_client import RestApiClient, TaskHandler import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) zone = "example.com." # Create snapshot (returns task_id) response = client.create_snapshot(zone) print(f"Snapshot task initiated: {response}") # Output: {'task_id': '...', 'message': 'Pending'} # Use TaskHandler for automatic polling result = TaskHandler(response, client, poll_interval=1) print(f"Snapshot created: {result}") # Get snapshot information snapshot_info = client.get_snapshot(zone) print(f"Snapshot info: {snapshot_info}") # Output: {'snapshotId': '...', 'timestamp': '2024-01-15T10:30:00Z', # 'recordCount': 150} # Make changes to zone client.create_rrset(zone, "A", "test", 300, "192.0.2.99") print("Made changes to zone") # Restore from snapshot (rollback changes) response = client.restore_snapshot(zone) result = TaskHandler(response, client, poll_interval=1) print(f"Snapshot restored: {result}") # Verify restoration try: client.get_rrsets_by_type_owner(zone, "A", "test") print("Record still exists") except: print("Record was rolled back successfully") ``` -------------------------------- ### Export Zone in BIND Format Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Demonstrates how to export a zone's data into the BIND configuration file format. This operation is asynchronous and involves task handling, similar to zone creation. ```python from ultra_rest_client import RestApiClient import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) # Assume account_name is already defined and client is authenticated # response = client.export_zone_to_bind(account_name, 'example.com.') # print(f"Export initiated: {response}") # Further task handling would be required here similar to zone creation. ``` -------------------------------- ### List and Query Zones (v1 and v3 APIs) Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Demonstrates how to retrieve zone information using both the v1 and v3 versions of the API. Covers filtering by various parameters, sorting, and implementing pagination using offsets/limits and cursors. ```python from ultra_rest_client import RestApiClient import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) # Get all zones for specific account account_details = client.get_account_details() account_name = account_details['accounts'][0]['accountName'] zones = client.get_zones_of_account(account_name) print(f"Account zones: {zones}") # Query with filtering and pagination (v1 API) zones = client.get_zones( offset=0, limit=5, sort="NAME", reverse=False, q={"name": "example", "zone_type": "PRIMARY"} ) print(f"Filtered zones: {zones}") # V3 API with cursor-based pagination first_page = client.get_zones_v3( limit=20, sort="NAME", q={"zone_status": "ALL"} ) print(f"First page: {first_page}") # Get next page using cursor from first_page response if 'cursor' in first_page: next_page = client.get_zones_v3( limit=20, cursor=first_page['cursor'], q={"zone_status": "ALL"} ) print(f"Next page: {next_page}") # Filter by zone type primary_zones = client.get_zones_v3( limit=5, q={"name": "example", "zone_type": "PRIMARY"} ) print(f"Primary zones: {primary_zones}") secondary_zones = client.get_zones_v3( limit=5, q={"zone_type": "SECONDARY"} ) print(f"Secondary zones: {secondary_zones}") ``` -------------------------------- ### Create Primary Zone - New Empty Zone (Python) Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Demonstrates the creation of a new, empty primary DNS zone with default SOA and NS records using the UltraDNS REST API client. It involves initializing the client, retrieving the account name, and then calling the 'create_primary_zone' method. Dependencies: 'ultra_rest_client', 'os'. ```python from ultra_rest_client import RestApiClient import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) # Get account name account_details = client.get_account_details() account_name = account_details['accounts'][0]['accountName'] # Create primary zone response = client.create_primary_zone(account_name, "example.com.") print(f"Zone created: {response}") # Verify zone creation zone_metadata = client.get_zone_metadata("example.com.") print(f"Zone metadata: {zone_metadata}") # Output: {'properties': {'name': 'example.com.', 'type': 'PRIMARY', ...}} ``` -------------------------------- ### Configure Secondary Zone Nameservers with Python Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Demonstrates how to configure primary, backup, and second backup nameservers for secondary DNS zones using the UltraDNS Python REST API client. The `edit_secondary_name_server` function allows updating one, multiple, or all nameserver configurations for a given zone. Requires an initialized RestApiClient. ```python from ultra_rest_client import RestApiClient import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) zone = "secondary.example.com." # Edit secondary zone nameserver configuration response = client.edit_secondary_name_server( zone, primary="203.0.113.10", backup="203.0.113.11", second_backup="203.0.113.12" ) print(f"Nameservers updated: {response}") # Update only primary nameserver response = client.edit_secondary_name_server( zone, primary="203.0.113.20" ) print(f"Primary nameserver updated: {response}") # Update all three nameservers response = client.edit_secondary_name_server( zone, primary="203.0.113.30", backup="203.0.113.31", second_backup="203.0.113.32" ) print(f"All nameservers updated: {response}") ``` -------------------------------- ### Create Primary Zone - Upload BIND File (Python) Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Explains how to create a primary DNS zone by uploading an existing BIND zone file. This method initiates an asynchronous task for processing the file upload, returning a task ID for monitoring. Dependencies: 'ultra_rest_client', 'os'. ```python from ultra_rest_client import RestApiClient, TaskHandler import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) # Get account name account_details = client.get_account_details() account_name = account_details['accounts'][0]['accountName'] # Upload BIND zone file (returns task_id for async processing) response = client.create_primary_zone_by_upload( account_name, 'example.com.', './zone.txt' ) print(f"Task initiated: {response}") ``` -------------------------------- ### Initialize Client with Bearer Token Auth (Python) Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Demonstrates client initialization using bearer token and refresh token for token-based authentication. It highlights the automatic token refresh mechanism upon encountering specific errors (e.g., error 60001) and the behavior when only a bearer token without a refresh token is provided. Requires 'ultra_rest_client' and 'os' libraries. ```python from ultra_rest_client import RestApiClient import os # Load tokens from environment access_token = os.getenv('ACCESS_TOKEN') refresh_token = os.getenv('REFRESH_TOKEN') # Initialize with tokens (use_token=True) client = RestApiClient(access_token, refresh_token, use_token=True) # Token will automatically refresh when expired (error 60001) zone_metadata = client.get_zone_metadata("example.com.") print(zone_metadata) # Bearer token without refresh token (expires in 1 hour) client_no_refresh = RestApiClient(access_token, use_token=True) # Warning: "Passing a Bearer token with no refresh token means # the client state will expire after an hour." ``` -------------------------------- ### Create Primary Zone via AXFR Transfer Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Shows how to create a primary zone by transferring zone data from a master DNS server using the AXFR protocol. Supports both basic AXFR and AXFR with TSIG authentication. ```python from ultra_rest_client import RestApiClient import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) account_details = client.get_account_details() account_name = account_details['accounts'][0]['accountName'] # Basic AXFR without TSIG response = client.create_primary_zone_by_axfr( account_name, "example.com.", master="203.0.113.10" ) print(f"AXFR initiated: {response}") # AXFR with TSIG authentication response = client.create_primary_zone_by_axfr( account_name, "secure.example.com.", master="203.0.113.10", tsig_key="mykey", key_value="Base64EncodedSecretKey==" ) print(f"Secure AXFR initiated: {response}") ``` -------------------------------- ### Create SiteBacker Pool with health monitoring in Python Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Create a SiteBacker (failover) pool with HTTP health monitoring, automatic failover, and backup records. Configures probe type, interval, monitoring agents, and failover thresholds. Supports prioritized active/backup record management. ```python pool_info = { "poolDescription": "Failover pool with health monitoring", "poolStatus": "NORMAL", "runProbes": True, "actOnProbes": True, "maxActive": 1, "maxServed": 1, "rdataInfo": [] } rdata_info = [ { "priority": 1, "state": "NORMAL", "runProbes": True, "threshold": 1, "probeInfo": { "type": "HTTP", "interval": "HALF_MINUTE", "agents": ["NEW_YORK", "DALLAS"], "details": { "path": "/health", "expectedResponse": "OK" } } } ] backup_record_list = [ {"rdata": "192.0.2.100", "failoverDelay": 0}, {"rdata": "192.0.2.101", "failoverDelay": 30} ] response = client.create_sb_pool( zone, "api", 300, pool_info, ["192.0.2.10", "192.0.2.11"], backup_record_list ) print(f"SiteBacker pool created: {response}") ``` -------------------------------- ### Import and Initialize RestApiClient in Python Source: https://github.com/ultradns/python_rest_api_client/blob/master/README.md Basic import and instantiation of the RestApiClient module for use in Python scripts. ```python from ultra_rest_client import RestApiClient client = RestApiClient(args) ``` -------------------------------- ### Create Primary Zone by Upload and Poll Task Status Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Demonstrates creating a primary zone by uploading a zone file and then manually or automatically polling the task status. It uses a `TaskHandler` utility for simplified polling. ```python import time from ultra_rest_client import RestApiClient, TaskHandler import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) response = client.create_primary_zone_by_upload(account_name, 'example2.com.', './zone.txt') # Manual polling approach while True: task_status = client.get_task(response['task_id']) print(f"Task status: {task_status['code']}") if task_status['code'] != 'IN_PROCESS': print(f"Task completed: {task_status}") break time.sleep(1) # Clean up task record client.clear_task(response['task_id']) # Automatic polling with TaskHandler utility response = client.create_primary_zone_by_upload(account_name, 'example2.com.', './zone.txt') result = TaskHandler(response, client, poll_interval=1) print(f"Final result: {result}") ``` -------------------------------- ### Create RD Pool with RANDOM distribution in Python Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Create a Resource Distribution Pool with RANDOM distribution order, where records are served in random sequence for load distribution. Returns created pool with random distribution configuration. ```python response = client.create_rd_pool( zone, "randompool", 300, ["192.0.2.20", "192.0.2.21", "192.0.2.22"], order="RANDOM", description="Random distribution pool" ) print(f"Random pool created: {response}") ``` -------------------------------- ### Export DNS Zone with Async Polling - Python Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Exports a complete DNS zone in BIND format and automatically handles async task polling. Returns zone file content with SOA, NS, and other resource records. Supports saving the exported zone data to a local file. ```python # Export zone (automatically handles async task polling) zone_data = client.export_zone('example.com.') print(zone_data) # Output: zone file content in BIND format # $ORIGIN example.com. # $TTL 86400 # @ IN SOA ns1.example.com. admin.example.com. ( # 2024010101 ; serial # 3600 ; refresh # 1800 ; retry # 604800 ; expire # 86400 ) ; minimum # ... # Save to file with open('exported_zone.txt', 'w') as f: f.write(zone_data) ``` -------------------------------- ### Create and Edit TC Pool with Python Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Defines and creates a Traffic Controller (TC) pool with specified pool information, IP addresses, and backup records. It also demonstrates how to update an existing TC pool. ```python from ultra_rest_client import RestApiClient import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) zone = "example.com." # Define TC pool configuration pool_info = { "description": "Geo-distributed traffic controller", "poolStatus": "NORMAL", "runProbes": True, "actOnProbes": True, "maxToLB": 2, "ttl": 300 } # Define weighted IP addresses rdata_info = [ { "weight": 50, "state": "NORMAL", "runProbes": True, "priority": 1, "probeInfo": { "type": "HTTP", "interval": "ONE_MINUTE", "agents": ["CHICAGO"] } }, { "weight": 30, "state": "NORMAL", "runProbes": True, "priority": 2, "probeInfo": { "type": "PING", "interval": "HALF_MINUTE", "agents": ["DALLAS"] } }, { "weight": 20, "state": "NORMAL", "runProbes": False, "priority": 3 } ] # Define backup record backup_record = { "rdata": "192.0.2.200", "failoverDelay": 60 } # Create TC Pool response = client.create_tc_pool( zone, "www", 300, pool_info, ["192.0.2.50", "192.0.2.51", "192.0.2.52"], backup_record ) print(f"Traffic Controller pool created: {response}") # Update TC Pool pool_info["description"] = "Updated geo-distributed pool" response = client.edit_tc_pool( zone, "www", 600, pool_info, ["192.0.2.50", "192.0.2.51", "192.0.2.52", "192.0.2.53"], backup_record ) print(f"Traffic Controller pool updated: {response}") ``` -------------------------------- ### Create Primary Zone in UltraDNS using Python Source: https://github.com/ultradns/python_rest_api_client/blob/master/README.md This Python script demonstrates how to create a primary DNS zone in UltraDNS using the RestApiClient. It retrieves account details to obtain the account name, which is a prerequisite for zone creation. The function requires an initialized RestApiClient instance and the desired domain name as input. ```python #!/usr/bin/env python3 from ultra_rest_client import RestApiClient import os def create_zone(client, domain): """Create a zone in UltraDNS. This function will create a zone with the name specified in the domain argument. It uses the accounts API to get the account name. This is required to create a zone. Args: - client (RestApiClient): An instance of the RestApiClient class. - domain (str): The domain name to be created. Returns: - dict: The response body. """ account_details = client.get_account_details() account_name = account_details['accounts'][0]['accountName'] return client.create_primary_zone(account_name, domain) def create_a_record(client, domain): """Create an A record in UltraDNS. This function will create an A record with the name specified in the domain Args: - client (RestApiClient): An instance of the RestApiClient class. - domain (str): The domain name. """ return client.create_rrset(domain, "A", domain, 300, "192.0.2.1") def create_cname_record(client, domain): """Create a CNAME record in UltraDNS. This function will create a CNAME record with the name specified in the domain Args: - client (RestApiClient): An instance of the RestApiClient class. - domain (str): The domain name. Returns: - dict: The response body. """ return client.create_rrset(domain, "CNAME", f"www.{domain}", 300, [domain]) def create_rd_pool(client, domain): """Create a pool of A records in UltraDNS. This function will create an RD pool within the specified domain. Args: - client (RestApiClient): An instance of the RestApiClient class. - domain (str): The domain name. Returns: - dict: The response body. """ return client.create_rd_pool( domain, "pool", 300, [ "192.0.2.2", "192.0.2.3" ] ) def delete_zone(client, domain): """Delete the zone from UltraDNS. Args: - client (RestApiClient): An instance of the RestApiClient class. - domain (str): The domain name. """ client.delete_zone(domain) return "Zone deleted Successfully" def main(): """The main function. This is the entry point for the script. It parses the command line arguments and calls the create_zone, create_a_record, and create_cname_record functions.""" # Fetch credentials from environment variables username = os.getenv('USERNAME') password = os.getenv('PASSWORD') domain = "ultra-rest-client-test.com." # Check if credentials are available if not username or not password: raise ValueError("Username and password must be set in environment variables.") # Create an instance of your client client = RestApiClient(username, password) # Create the domain print(f"Creating zone {domain}: {create_zone(client, domain)}") # Create an A record for the domain print(f"Creating an A record pointing to 192.0.2.1: {create_a_record(client, domain)}") # Create a CNAME record for the domain print(f"Creating a 'www' CNAME pointing to {domain}: {create_cname_record(client, domain)}") # Delete the domain print(f"Deleting zone {domain}: {delete_zone(client, domain)}") if __name__ == "__main__": main() ``` -------------------------------- ### Manage Web Forwards with Python Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Demonstrates creating, listing, and deleting HTTP/HTTPS redirects (web forwards) using the UltraDNS Python client. Supports 301, 302, and framed redirects. ```python from ultra_rest_client import RestApiClient import os client = RestApiClient(os.getenv('USERNAME'), os.getenv('PASSWORD')) zone = "example.com." # Create 301 permanent redirect response = client.create_web_forward( zone, "old.example.com.", # request_to "https://new.example.com", # redirect_to "HTTP_301_REDIRECT" # forward_type ) print(f"301 redirect created: {response}") # Output: {'guid': 'ABC123...', 'message': 'Successful'} # Create 302 temporary redirect response = client.create_web_forward( zone, "promo.example.com.", "https://example.com/promo", "HTTP_302_REDIRECT" ) print(f"302 redirect created: {response}") # Create framed redirect response = client.create_web_forward( zone, "frame.example.com.", "https://external-site.com", "FRAMED" ) print(f"Framed redirect created: {response}") # List all web forwards in zone web_forwards = client.get_web_forwards(zone) print(f"All web forwards: {web_forwards}") # Output: {'webForwards': [{'guid': '...', 'requestTo': 'old.example.com.', ...}]} # Delete web forward guid = response['guid'] response = client.delete_web_forward(zone, guid) print(f"Web forward deleted: {response}") ``` -------------------------------- ### Create RD Pool with FIXED order distribution in Python Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Create a Resource Distribution Pool with FIXED order distribution, where records are served in the specified sequence without rotation. Returns created pool with fixed order configuration. ```python response = client.create_rd_pool( zone, "fixedpool", 300, ["192.0.2.10", "192.0.2.11"], order="FIXED", description="Fixed order pool" ) print(f"Fixed pool created: {response}") ``` -------------------------------- ### Query and List Resource Records Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Retrieves DNS records with various filtering and pagination options. ```APIDOC ## Query and List Resource Records ### Description Retrieves DNS records with various filtering and pagination options. ### Method GET ### Endpoint `/v1/zones/{zone_name}/rrsets` ### Parameters #### Path Parameters - **zone_name** (string) - Required - The name of the zone (e.g., 'example.com.'). #### Query Parameters - **rrtype** (string) - Optional - Filter records by type (e.g., 'A'). - **owner** (string) - Optional - Filter records by owner name. Supports wildcards (e.g., 'www*'). - **ttl** (string) - Optional - Filter records by TTL. - **offset** (integer) - Optional - For pagination, the starting index. - **limit** (integer) - Optional - For pagination, the maximum number of records to return. ### Request Example ```python # Get all RRSets in zone all_records = client.get_rrsets(zone) # Get all A records in zone a_records = client.get_rrsets_by_type(zone, "A") # Get specific record by type and owner specific_record = client.get_rrsets_by_type_owner(zone, "A", "www") # Query with filtering filtered_records = client.get_rrsets( zone, q={"ttl": "300", "owner": "www*"} ) # Pagination paginated = client.get_rrsets(zone, offset=0, limit=10) ``` ### Response #### Success Response (200) - **rrSets** (array of objects) - A list of DNS resource record sets. - **ownerName** (string) - The owner name of the record. - **rrtype** (string) - The type of the record. - **ttl** (integer) - The Time To Live for the record. - **rdata** (array of strings) - The data associated with the record. #### Response Example ```json { "rrSets": [ { "ownerName": "www.example.com.", "rrtype": "A", "ttl": 300, "rdata": ["192.0.2.1"] }, { "ownerName": "mail1.example.com.", "rrtype": "MX", "ttl": 300, "rdata": ["10 mail1.example.com."] } ] } ``` ``` -------------------------------- ### Create DNS Resource Records (RRSets) Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Creates various types of DNS records including A, AAAA, CNAME, MX, and TXT records within a specified zone. ```APIDOC ## Create DNS Resource Records (RRSets) ### Description Creates various types of DNS records including A, AAAA, CNAME, MX, and TXT records within a specified zone. ### Method POST ### Endpoint `/v1/zones/{zone_name}/rrsets/{rrtype}/{owner_name}` ### Parameters #### Path Parameters - **zone_name** (string) - Required - The name of the zone (e.g., 'example.com.'). - **rrtype** (string) - Required - The type of DNS record (e.g., 'A', 'AAAA', 'CNAME', 'MX', 'TXT'). - **owner_name** (string) - Required - The owner name for the record (e.g., 'www', '@'). #### Request Body - **ttl** (integer) - Required - The Time To Live for the record in seconds. - **rdata** (array of strings or string) - Required - The data for the record. Can be a single IP, multiple IPs for round-robin, or specific format for other record types. - **profile** (object) - Optional - Profile information, used for specific record types like pools. ### Request Example ```python # Create A record (single IP) response = client.create_rrset(zone, "A", "www", 300, "192.0.2.1") # Create A record (multiple IPs for round-robin) response = client.create_rrset( zone, "A", "server", 300, ["192.0.2.1", "192.0.2.2", "192.0.2.3"] ) # Create AAAA record (IPv6) response = client.create_rrset( zone, "AAAA", "www", 300, ["2001:db8::1", "2001:db8::2"] ) # Create CNAME record response = client.create_rrset( zone, "CNAME", "ftp", 300, ["www.example.com."] ) # Create MX record response = client.create_rrset( zone, "MX", zone, # apex record 300, ["10 mail1.example.com.", "20 mail2.example.com."] ) # Create TXT record response = client.create_rrset( zone, "TXT", zone, 300, ['"v=spf1 include:_spf.example.com ~all"'] ) ``` ### Response #### Success Response (200 or 201) - **message** (string) - Confirmation of record creation. - **rrSet** (object) - Details of the created RRSet. #### Response Example ```json { "message": "RRSet created successfully.", "rrSet": { "ownerName": "www.example.com.", "rrtype": "A", "ttl": 300, "rdata": ["192.0.2.1"] } } ``` ``` -------------------------------- ### Create RD Pool with round-robin distribution in Python Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Create a Resource Distribution (RD) Pool with round-robin load balancing for IPv4 addresses. Accepts TTL, list of IP addresses, distribution order, and optional description. Supports ROUND_ROBIN, FIXED, and RANDOM distribution methods. ```python response = client.create_rd_pool( zone, "pool", 300, # TTL ["192.0.2.1", "192.0.2.2", "192.0.2.3"], # IP addresses order="ROUND_ROBIN", ipv6=False, description="Load balancing pool for web servers" ) print(f"RD Pool created: {response}") ``` -------------------------------- ### Configure Proxy Settings for RestApiClient Source: https://github.com/ultradns/python_rest_api_client/blob/master/README.md Initialize the RestApiClient with proxy configuration for requests sent through an HTTP/HTTPS proxy server. Uses the format required by the requests library. ```python # Define proxy settings using the format required by the `requests` library proxy_dict = { "http": "http://proxy.example.com:8080", "https": "http://proxy.example.com:8080" } # Initialize the client with a proxy client = RestApiClient( "username", "password", proxy=proxy_dict ) # Make an API request with the proxy enabled response = client.create_primary_zone("my_account", "example.com") # Update the proxy dynamically if needed client.rest_api_connection.set_proxy({ "http": "http://newproxy.example.com:8080", "https": "http://newproxy.example.com:8080" }) ``` -------------------------------- ### SiteBacker Pool (Failover) API Source: https://context7.com/ultradns/python_rest_api_client/llms.txt Manages SiteBacker pools, which provide health monitoring and automatic failover capabilities for DNS records. ```APIDOC ## SiteBacker Pool (Failover) API This API enables the creation and management of SiteBacker pools, designed for failover scenarios with integrated health checks. ### Create SiteBacker Pool Creates a SiteBacker pool with specified health monitoring and failover configurations. #### Endpoint `/v1/zones/{zone}/sbpools` #### Method `POST` #### Request Body Example (for `client.create_sb_pool`) ```json { "poolDescription": "Failover pool with health monitoring", "poolStatus": "NORMAL", "runProbes": true, "actOnProbes": true, "maxActive": 1, "maxServed": 1, "ttl": 300, "rdataInfo": [ { "priority": 1, "state": "NORMAL", "runProbes": true, "threshold": 1, "probeInfo": { "type": "HTTP", "interval": "HALF_MINUTE", "agents": ["NEW_YORK", "DALLAS"], "details": { "path": "/health", "expectedResponse": "OK" } }, "rdata": "192.0.2.10" }, { "priority": 2, "state": "BACKUP", "runProbes": false, "threshold": 1, "rdata": "192.0.2.100", "failoverDelay": 0 }, { "priority": 3, "state": "BACKUP", "runProbes": false, "threshold": 1, "rdata": "192.0.2.101", "failoverDelay": 30 } ] } ``` ### Update SiteBacker Pool Modifies an existing SiteBacker pool, including its description, TTL, and associated records. #### Endpoint `/v1/zones/{zone}/sbpools/{poolName}` #### Method `PUT` #### Request Body Example (for `client.edit_sb_pool`) ```json { "poolDescription": "Updated failover pool", "poolStatus": "NORMAL", "runProbes": true, "actOnProbes": true, "maxActive": 1, "maxServed": 1, "ttl": 600, "rdataInfo": [ { "priority": 1, "state": "NORMAL", "runProbes": true, "threshold": 1, "probeInfo": { "type": "HTTP", "interval": "HALF_MINUTE", "agents": ["NEW_YORK", "DALLAS"], "details": { "path": "/health", "expectedResponse": "OK" } }, "rdata": "192.0.2.10" }, { "priority": 2, "state": "NORMAL", "runProbes": true, "threshold": 1, "rdata": "192.0.2.11" }, { "priority": 3, "state": "NORMAL", "runProbes": true, "threshold": 1, "rdata": "192.0.2.12" }, { "priority": 4, "state": "BACKUP", "runProbes": false, "threshold": 1, "rdata": "192.0.2.100", "failoverDelay": 0 }, { "priority": 5, "state": "BACKUP", "runProbes": false, "threshold": 1, "rdata": "192.0.2.101", "failoverDelay": 30 } ] } ``` **Note**: The `rdataInfo` structure can be complex, defining primary and backup records with detailed probe configurations. ```