-1

I need to delete all those hosted zones in Route53 using boto3

I created the zones in AWS console and trying to delete all those zones using boto3 using lamda function. I used the below codes however it throws error

import boto3

def lambda_handler(event, context):

    # Iterate over regions
    for region in regions:

        # Running following for a particular region
        print ("*************** Checking region  --   %s " % region['RegionName'])
        reg=region['RegionName']


        ########### cleaning Route53 zones ################

        client = boto3.client('route53',region_name=reg)
        response = client.list_hosted_zones_by_name()
        for zone in response ['hosted-zones']:
            print ("About to delete %s | in %s" % (zone['HostedZone'], region['RegionName']))
            result = client.delete_hosted_zone(HostedZone=zone['HostedZone'])

Getting the following error message:

'hosted-zones': KeyError
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 22, in lambda_handler
    for zone in response ['hosted-zones']:
KeyError: 'hosted-zones'
skytaker
  • 4,159
  • 1
  • 21
  • 31

1 Answers1

1

Your python KeyError is giving you the information: there is no key hosted-zones on the client response object; the key you are looking for is HostedZones. See the boto3 Route53 documentation which contains the response syntax. The key HostedZone also does not exist at that level of the response object, you need to use Id. The documentation for boto3 is pretty good for this kind of thing!

for zone in response['HostedZones']:
    client.delete_hosted_zone(Id=zone['Id'])
danimal
  • 1,567
  • 13
  • 16
  • It would be great If you give me the valid syntax..since I am new to boto3 I am not much aware of it. – Muneesh DuRaipandi Aug 28 '19 at 12:18
  • `Response: { "errorMessage": "An error occurred (AccessDenied) when calling the DeleteHostedZone operation: The resource hostedzone/Z22MQQMFU2EPN9 can only be managed through servicediscovery.amazonaws.com (arn:aws:servicediscovery:us-east-1:695121473358:namespace/ns-vax34g7lbqxcsuyp)", "errorType": "ClientError"` .---getting new error – Muneesh DuRaipandi Aug 28 '19 at 12:47
  • yeah you can run into problems with private hosted zones with servicediscovery, see for example https://forums.aws.amazon.com/thread.jspa?threadID=279241 but you'll probably need to ask a new SO question – danimal Aug 28 '19 at 12:50
  • https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/servicediscovery.html#ServiceDiscovery.Client.delete_service is how you can do it with `boto` – danimal Aug 28 '19 at 12:51