How to Mock CloudFront Invalidation Paths in Python

Build a sorted, deduplicated list of CloudFront invalidation paths from a set of file paths, adding implicit index.html entries.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 15 views 0 copies

Python code

32 lines
Python 3.9+
import argparse

def build_invalidation_paths(files, include_index=True):
    """
    Create CloudFront invalidation paths from a list of files.
    Converts file names to root-relative paths and optionally adds /index.html.
    """
    paths = []
    for f in files:
        f = f.strip()
        if not f:
            continue
        # Normalize: remove leading slash, make path start with /
        normalized = f if f.startswith("/") else f"/{f}"
        # Avoid duplicate index paths
        if include_index and normalized.endswith(".html"):
            paths.append(f"{normalized}")
            if normalized.endswith("index.html"):
                paths.append(normalized[:-len("index.html")] or "/")
            else:
                # Add implicit index fragment for directories
                paths.append(f"{normalized.replace('.html', '')}/")
        else:
            paths.append(normalized)
    return sorted(set(paths))

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("files", nargs="+", help="List of file paths")
    args = parser.parse_args()
    for path in build_invalidation_paths(args.files):
        print(path)

Output

stdout
$ python build_paths.py /index.html about.html contacts.html
/about/
/about/index.html
/contacts/
/contacts/index.html
/index.html

How it works

The function processes each input file path, normalizes it to start with a slash, and then handles HTML files specially to include both the explicit file and the directory index path. index.html is handled by adding the root or directory path. Sorting and using set ensures paths are unique and listed in a predictable order, which is helpful when generating invalidation batches. This approach mirrors how CloudFront treats directory defaults when you request a path without a file. The command-line interface prints each path on its own line, making it easy to pipe into other tools or use in scripts.

Common mistakes

  • Forgetting to normalize paths that don't start with `/`
  • Not handling duplicate paths when both `index.html` and the directory are listed
  • Including the implicit index for `index.html` incorrectly (e.g., adding `root/` instead of `/`)

Variations

  1. Use `pathlib.Path` for path manipulation instead of string slicing
  2. Accept file patterns (like glob) to expand before building paths

Real-world use cases

  • Automating AWS CloudFront cache invalidation after deploying static assets like React builds.
  • Generating invalidation batches for a CMS that maps URLs to files without extensions.
  • Testing invalidation logic locally before executing the AWS CLI command.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.