How to invalidate cloudfront distribution with python and bash

Nic Wanavit
TenXor
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

Python

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

make sure you install nicHelper pip install nicHelper

put it in your SAM template

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

--

--