How to invalidate cloudfront distribution with python and bash

Nic Wanavit
Published in
2 min readMay 19, 2021

Cloudfront is a great content distribution network which speeds up your websites/ api significantly, however one of the hurdle is you need to invalidate cache when your endpoint is updated

Setting up IAM permission

This is pretty easy

  1. set up your policy

Go to IAM console, and select policies

2. Create policy, select json and put this in

"Version": "2012-10-17",
"Statement": [
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "cloudfront:CreateInvalidation",
"Resource": "arn:aws:cloudfront::<accountId>:distribution/<distributionId>"

3. click on the policy and copy the policyARN

Using command line

aws cloudfront create-invalidation --distribution-id <distributionId> --paths "/*"

replace paths/distributionId with the actual values


from nicHelper.cloudfront import invalidate
invalidate('E1I41NH6AGDJM8', path='/public/imagenames/*')

make sure you install nicHelper pip install nicHelper

put it in your SAM template

Type: AWS::Serverless::Function
CodeUri: ....
Handler: ...
- <iam permission arn from above>