orome
orome

Reputation: 48446

How do I get the Hosted Zone for a domain using Boto 3?

In Boto 2, I can get a Hosted Zone associated with a domain domain with

r53_2 = boto.route53.connection.Route53Connection()
hz = r53_2.get_zone(domain)

but in Boto 3, the corresponding API requires an ID rather than a domain name

r53_3 = boto3.client('route53')
hz = r53_3.get_hosted_zone(id)

and I don't see any way to get the ID from the domain name, which is all I have access to.

How do I get the Hosted Zone for a domain using Boto 3?

Upvotes: 6

Views: 8021

Answers (3)

peter n
peter n

Reputation: 1280

The list_hosted_zones_by_name is a bit misleading: it still returns a list, but the record which has the DNSName is listed first. CAUTION: if the record doesn't exist, it'll return the next record in some alphabetical order (I think), so grabbing the first on the list won't guarantee it's the one you want. Here's what worked for me:

import boto3, json

client = boto3.client('route53')
dnsName = 'example.com' 
response = client.list_hosted_zones_by_name(
    DNSName=dnsName, 
    MaxItems='1'
)
print(json.dumps(response, indent=4)) # inspect output
if ('HostedZones' in response.keys()
    and len(response['HostedZones']) > 0
    and response['HostedZones'][0]['Name'].startswith(dnsName)):
    hostedZoneId = response['HostedZones'][0]['Id'].split('/')[2] # response comes back with /hostedzone/{HostedZoneId}
    print('HostedZone {} found with Id {}'.format(dnsName, hostedZoneId))
else:
    print('HostedZone not found: {}'.format(dnsName))

Upvotes: 6

rossigee
rossigee

Reputation: 51

Maybe this example will help...

    r53 = boto3.client('route53')
    zones = r53.list_hosted_zones_by_name(DNSName=domain)
    if not zones or len(zones['HostedZones']) == 0:
        raise Exception("Could not find DNS zone to update")
    zone_id = zones['HostedZones'][0]['Id']

Upvotes: 2

Polymath
Polymath

Reputation: 125

I am not in a position to test this right now, but can you use .list_hosted_zones()

You need to parse the result, but it is a start.

RL

Upvotes: 3

Related Questions