Atif
Atif

Reputation: 1537

Deleting a CloudFront Distribution with boto3

I'm working on a teardown script that needs to delete the cloudfront distribution for a website. Looks like you have to do to following

  1. Disable the distribution
  2. Wait for the distribution to be disabled (deployed)
  3. Delete the distribution

However it looks like the waiter fails on step 2, and the delete_distribution fails unless the distribution has beed disabled.

result = client.update_distribution(
    DistributionConfig=disabledConf, 
    Id=dist_id, 
    IfMatch=matchid)
waiter = client.get_waiter('distribution_deployed')
print("Waiting for disabling the distribution")
waiter.wait(Id=dist_id)  # Throws here
client.delete_distribution(Id=dist_id, IfMatch=result['ETag'])

Anyone know how to get this to work with boto3?

Upvotes: 1

Views: 1833

Answers (1)

Jonathan Russo
Jonathan Russo

Reputation: 56

I just ran into this exact issue. The problem lies in the fact that Boto3 does not have a wait function for Disabling Distributions. From the docs on the "distribution_deployed" wait function:

Polls CloudFront.Client.get_distribution() every 60 seconds until a successful state is reached. An error is returned after 25 failed checks.

That means it won't work for disabling a distribution. To solve this problem I used datetime and the time.sleep function to implement my own waiter.

import time
from datetime import datetime,timedelta
import sys

#disable distribution
result = client.update_distribution(
    DistributionConfig=disabledConf, 
    Id=dist_id, 
    IfMatch=matchid)

#wait for distribution to disable....
print("Waiting for disabling the distribution...This may take a while....")
timeout_mins=60 
wait_until = datetime.now() + timedelta(minutes=timeout_mins)
notFinished=True
eTag=""
while(notFinished):
    #check for timeout
    if wait_until < datetime.now():
        #timeout
        print("Distribution took too long to disable. Exiting")
        sys.exit(1)

    status=client.get_distribution(Id=dist_id)
    if(status['Distribution']['DistributionConfig']['Enabled']==False and status['Distribution']['Status']=='Deployed'):
        eTag=status['ETag']
        notFinished=False

    print("Not completed yet. Sleeping 60 seconds....")
    time.sleep(60) 

#delete distribution
client.delete_distribution(Id=dist_id, IfMatch=eTag)   

So in addition to checking if it is disabled, you need to see if the changes have taken effect. You do this by ensuring that the "Status" has changed to 'Deployed'(It will be In-Progress during the change)

Upvotes: 4

Related Questions