How to invalidate cloudfront distribution with python and bash
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
- 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:
...