amazon-web-servicescachingaws-lambdaamazon-cloudfrontcache-invalidation

How to clear the Cache of multiple distributions including listing them?


First I want to say Hello to all, second I am very scared since I just got a new job and one of my tasks is something I have never done before in my life. In this case the task I am assigned to is to find a way to delete the cache from the S3 Cloudfront Distributions. I have tried to see if there is a way to list all of the distributions and then clear the cache from them using a script but I could not find if that is even possible and what the script should look like.

The idea that I have is to have a cli script that will:

A) list all of the distributions in a txt file output; B) Read from that output the distributions ID's and afterwards use that output to clear their current cache.

So that afterwards new cache can be created on the distributions after new files have been uploaded. I have read upon https://docs.aws.amazon.com/cli/latest/reference/cloudfront/list-distributions.html but unfortunately I could not grasp how the script would look like to list all of the distributions ID's > distribution.txt and afterwards read from it to delete their cache.

Any tips or information that I can read upon to create such a script if it's even possible will be very helpful, since I am really nervus and scared of my first task.

Want to say thanks to all that have read the topic even if they did not have any tips to give :).


Solution

  • Okay, I think i understand the requirements fully now. What I would do: Architecturally: Make it a Lambda function, I would use Python 3.7 for this personally. Coding steps to implement:

    1. Read the domain you want invalidated from the Lambda request input.
    2. Save the result of the aws cloudfront list-distributions in a variable
    3. Since it's a JSON Structure you can loop through it as a dictionary, do that and for each of the distributions check if the "Aliases" attribute includes your domain. Save the ID's of these distributions in a list.
    4. Loop through your list and for each of the ids execute: aws cloudfront create-invalidation --distribution-id *id_from_list* --paths *

    Make sure that the Lambda function has permission to list Cloudfront distributions and to create invalidations. Also make sure that everyone who might need to execute this function has rights to do so.