Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 492
orome Avatar asked Feb 24 '17 19:02

orome


People also ask

How do I find my hosted zone?

Sign in to the AWS Management Console and open the Route 53 console at https://console.aws.amazon.com/route53/ . In the navigation pane, choose Hosted Zones. On the Hosted Zones page, choose the name of a hosted zone. The console displays the list of records for that hosted zone.

What is a Hosted zone name?

A hosted zone is a container for records, and records contain information about how you want to route traffic for a specific domain, such as example.com, and its subdomains (acme.example.com, zenith.example.com). A hosted zone and the corresponding domain have the same name.

What is Privated hosted zone?

A private hosted zone is a container that holds information about how you want to route traffic for a domain and its subdomains within one or more Amazon Virtual Private Clouds (Amazon VPCs). To begin, you create a private hosted zone and specify the Amazon VPCs that you want to associate with the hosted zone.


1 Answers

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))
like image 94
peter n Avatar answered Oct 31 '22 17:10

peter n