Google Cloud DNS Client Library
The Google Cloud DNS API client library provides a Pythonic interface for managing DNS records and managed zones within Google Cloud DNS. It is part of the broader `google-cloud-python` monorepo, benefiting from its active development and frequent updates across Google Cloud services.
Warnings
- breaking Python 2.7 support was dropped in `google-cloud-python` 2.0.0. Current versions require Python 3.9 or newer.
- gotcha Ensure the Cloud DNS API is enabled in your Google Cloud project. Attempting operations without enabling the API will result in 'attempted action failed' or similar permission errors.
- gotcha When creating DNS records, be aware of DNS specifications and Cloud DNS limitations, particularly regarding CNAME records. A CNAME record cannot exist at the zone apex (root domain) and cannot coexist with other record types for the same DNS name.
- gotcha Authentication for Google Cloud client libraries, including `google-cloud-dns`, typically relies on Application Default Credentials (ADC). For local development, `gcloud auth application-default login` generates user credentials for client libraries, distinct from `gcloud auth login` which authenticates the CLI itself.
Install
-
pip install google-cloud-dns
Imports
- Client
from google.cloud import dns
Quickstart
import os
from google.cloud import dns
# Your Google Cloud project ID
project_id = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-project-id')
if not project_id or project_id == 'your-project-id':
print("Please set the 'GOOGLE_CLOUD_PROJECT' environment variable or replace 'your-project-id' in the code.")
exit(1)
# Initialize the DNS client
# The client automatically handles authentication using Application Default Credentials (ADC)
# For local development, ensure you've run 'gcloud auth application-default login'
client = dns.Client(project=project_id)
try:
# List managed zones
print(f"Listing managed zones for project: {project_id}")
zones = client.list_zones()
if not zones:
print("No managed zones found.")
else:
for zone in zones:
print(f" Zone Name: {zone.name}, DNS Name: {zone.dns_name}")
except Exception as e:
print(f"An error occurred: {e}")