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.
Python code
32 linesimport 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
$ 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
- Use `pathlib.Path` for path manipulation instead of string slicing
- 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
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.