Borislav Hadzhiev
Thu Sep 16 2021·2 min read
Photo by Darya Skuratovich
To invalidate a CloudFront distribution's cache, we have to run the
create-invalidation
command. The command requires that we pass the
distribution's ID as a parameter, so let's first grab the ID, by running the
list-distributions
command:
aws cloudfront list-distributions --query "DistributionList.Items[*].{id:Id,origin:Origins.Items[0].Id}"
The command returns a list of objects containing the id of the cloudfront distribution and the name of the S3 bucket associated with it:
Grab the cloudfront distribution ID because we'll need it for clearing the cache.
To invalidate the cache for an entire CloudFront distribution, run the
create-invalidation
command with a wildcard path /*
.
aws cloudfront create-invalidation --distribution-id YOUR_CLOUDFRONT_ID --paths "/*"
The cache invalidation might take a few minutes. The create-invalidation
command returns an Id
, which we can use to check the result of the
invalidation:
To make sure the cache for your distribution has been invalidated, grab the
Invalidation ID and run the get-invalidation
command.
aws cloudfront get-invalidation --id INVALIDATION_ID --distribution-id DISTRIBUTION_ID
The output will show the status of the cache invalidation:
To clear the CloudFront cache for a directory, e.g. images
, run the
create-invalidation
command with the /images/*
wildcard path.
aws cloudfront create-invalidation --distribution-id YOUR_CLOUDFRONT_ID --paths "/images/*"
Completed
.To clear the CloudFront cache for specific files, run the
create-invalidation
command passing in the paths to the files you want to
invalidate, separated by space characters.
aws cloudfront create-invalidation --distribution-id YOUR_CLOUDFRONT_ID --paths "/images/dog.png" "/js/bundle.js"
1,000
paths you invalidate each month, are free. Each path after the first 1,000
costs $0.005
per invalidation request.Invalidating a wildcard path, e.g. /images/*
, counts as 1
invalidation request.
Cache invalidation of individual files can get costly after a while.