Force CloudFront distribution/file update
Solution 1
Good news. Amazon finally added an Invalidation Feature. See the API Reference.
This is a sample request from the API Reference:
POST /2010-08-01/distribution/[distribution ID]/invalidation HTTP/1.0
Host: cloudfront.amazonaws.com
Authorization: [AWS authentication string]
Content-Type: text/xml
<InvalidationBatch>
<Path>/image1.jpg</Path>
<Path>/image2.jpg</Path>
<Path>/videos/movie.flv</Path>
<CallerReference>my-batch</CallerReference>
</InvalidationBatch>
Solution 2
As of March 19, Amazon now allows Cloudfront's cache TTL to be 0 seconds, thus you (theoretically) should never see stale objects. So if you have your assets in S3, you could simply go to AWS Web Panel => S3 => Edit Properties => Metadata, then set your "Cache-Control" value to "max-age=0".
This is straight from the API documentation:
To control whether CloudFront caches an object and for how long, we recommend that you use the Cache-Control header with the max-age= directive. CloudFront caches the object for the specified number of seconds. (The minimum value is 0 seconds.)
Solution 3
Automated update setup in 5 mins
OK, guys. The best possible way for now to perform automatic CloudFront update (invalidation) is to create Lambda function that will be triggered every time when any file is uploaded to S3 bucket (a new one or rewritten).
Even if you never used lambda functions before, it is really easy -- just follow my step-by-step instructions and it will take just 5 mins:
Step 1
Go to https://console.aws.amazon.com/lambda/home and click Create a lambda function
Step 2
Click on Blank Function (custom)
Step 3
Click on empty (stroked) box and select S3 from combo
Step 4
Select your Bucket (same as for CloudFront distribution)
Step 5
Set an Event Type to "Object Created (All)"
Step 6
Set Prefix and Suffix or leave it empty if you don't know what it is.
Step 7
Check Enable trigger checkbox and click Next
Step 8
Name your function (something like: YourBucketNameS3ToCloudFrontOnCreateAll)
Step 9
Select Python 2.7 (or later) as Runtime
Step 10
Paste following code instead of default python code:
from __future__ import print_function
import boto3
import time
def lambda_handler(event, context):
for items in event["Records"]:
path = "/" + items["s3"]["object"]["key"]
print(path)
client = boto3.client('cloudfront')
invalidation = client.create_invalidation(DistributionId='_YOUR_DISTRIBUTION_ID_',
InvalidationBatch={
'Paths': {
'Quantity': 1,
'Items': [path]
},
'CallerReference': str(time.time())
})
Step 11
Open https://console.aws.amazon.com/cloudfront/home in a new browser tab and copy your CloudFront distribution ID for use in next step.
Step 12
Return to lambda tab and paste your distribution id instead of _YOUR_DISTRIBUTION_ID_ in the Python code. Keep surrounding quotes.
Step 13
Set handler: lambda_function.lambda_handler
Step 14
Click on the role combobox and select Create a custom role. New tab in browser will be opened.
Step 15
Click view policy document, click edit, click OK and replace role definition with following (as is):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"cloudfront:CreateInvalidation"
],
"Resource": [
"*"
]
}
]
}
Step 16
Click allow. This will return you to a lambda. Double check that role name that you just created is selected in the Existing role combobox.
Step 17
Set Memory (MB) to 128 and Timeout to 5 sec.
Step 18
Click Next, then click Create function
Step 19
You are good to go! Now on, each time you will upload/reupload any file to S3, it will be evaluated in all CloudFront Edge locations.
PS - When you are testing, make sure that your browser is loading images from CloudFront, not from local cache.
PSS - Please note, that only first 1000 files invalidation per month are for free, each invalidation over limit cost $0.005 USD. Also additional charges for Lambda function may apply, but it is extremely cheap.
Solution 4
With the Invalidation API, it does get updated in a few of minutes.
Check out PHP Invalidator.
Solution 5
Bucket Explorer has a UI that makes this pretty easy now. Here's how:
Right click your bucket. Select "Manage Distributions."
Right click your distribution. Select "Get Cloudfront invalidation list"
Then select "Create" to create a new invalidation list.
Select the files to invalidate, and click "Invalidate." Wait 5-15 minutes.
Related videos on Youtube
Martin
Updated on July 08, 2022Comments
-
Martin almost 2 years
I'm using Amazon's CloudFront to serve static files of my web apps.
Is there no way to tell a cloudfront distribution that it needs to refresh it's file or point out a single file that should be refreshed?
Amazon recommend that you version your files like logo_1.gif, logo_2.gif and so on as a workaround for this problem but that seems like a pretty stupid solution. Is there absolutely no other way?
-
Steffen Opel almost 12 yearspossible duplicate of How can I update files on Amazon's CDN (CloudFront)?
-
eis almost 12 yearsas a sidenote, I don't think it's stupid to name static files like that. We've been using it a lot and having automated renaming as per file version in version control has saved us a lot of headaches.
-
Jake Wilson almost 12 years@eis unless the file you need to replace has been linked to 1000 different places online. Good luck getting all those links updated.
-
eis almost 12 years@Jakobud why should the links be updated in that case? they're referring to specific version, which is not the latest, if the file has been changed. If the file has not been changed, it'll work as it did before.
-
Jake Wilson over 11 yearsIn some cases a company may make a mistake in posting the wrong image for something or some other type of item where they receive a takedown notice from a law firm and have to replace the file. Simply uploading a new file with a new name isn't going to fix that kind of problem, which is unfortunately a problem that is more and more common these days.
-
Aidin about 3 yearsI have summarized the possible solutions in this answer on the duplicate question that @SteffenOpel mentioned, at stackoverflow.com/a/66976601.
-
-
cointilt about 13 yearsThis is exactly what I was looking for. I am going to hook this in Beanstalkapp's web-hooks when auto deploying from git! Thanks for the link!
-
Michael Warkentin about 12 yearsPlease note that invalidation will take some time (apparently 5-30 minutes according to some blog posts I've read).
-
j0nes almost 12 yearsIf you do not want to make an API request yourself, you can also log in to the Amazon Console and create an Invalidation request there: docs.amazonwebservices.com/AmazonCloudFront/latest/…
-
ill_always_be_a_warriors over 11 yearsFor those of you using the API to do the invalidation, approximately how long is it taking for the invalidation to take effect?
-
ill_always_be_a_warriors over 11 yearsWhere is this setting in the new AWS Console UI? I can't find it.
-
ill_always_be_a_warriors over 11 yearsI found the setting for an individual file, but is there a setting to make it so that anything uploaded to my bucket has a TTL of 0?
-
Donia about 10 years@ill_always_be_a_warriors About 10-15 minutes per docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/…
-
TimS almost 10 yearsRemember this costs $0.005 per file after your first 1,000 invalidation requests per month aws.amazon.com/cloudfront/pricing
-
Fábio Batista almost 10 yearsYou just saved my life!
-
Two-Bit Alchemist almost 10 yearsWhile I would also definitely be interested in a bucket-wide setting, I found this a quicker/better solution. Invalidation requests (along with the rest of the API) are very confusing and poorly documented, and I spun my wheels for 3 hours before this instantly worked.
-
Mikita Manko over 9 yearsActually cfadmin is a very helpful tool, especially if you need to reset CloudFront cache from the console\bash\travis ci deployment script. BTW here is the post how to reset\invalidate CoudFront cache during the travis deployment to aws
-
d.raev over 9 yearssorry, but even "you say" the credentials not stored or leeked ... one should never give his credential to a 3rd party. May be implement a remote amazon authentication or something ?
-
acidjazz over 8 yearsCall me crazy but setting the TTL to 0 and max-age to 0 is really using CloudFront without caching, wouldn't that forward all requests to the origin constantly checking for updates? Essentially making the CDN useless?
-
Oliver Tynes over 8 yearsYou should put this behind https at the least.
-
RayLuo over 8 yearsOnline tools are generally nice, but providing credentials to 3rd party tool will be a valid security concern. I would suggest to use either official web console or official CLI tool.
-
tim peterson about 8 years@MichaelWarkentin After making an API
createInvalidation
request, i'm still seeing the update take 5-10 minutes or so to invalidate. Notice I write this comment 4 years after yours. -
Moataz Elmasry almost 8 yearsFor the security of others, I'm downvoting this answer. You should never ever ask people for their credentials
-
tkit over 7 yearswhere/how can the AWS auth string be obtained? does it need to be generated from pub/priv keys or?
-
István Ujj-Mészáros over 7 yearsIt takes exactly 10 minutes for me.
-
Phil over 7 yearsJust the last item from each S3 batch?
-
Kainax over 7 years@Phil The code is written that way so only newly uploaded files will be invalidated, not a whole bucket. In case of multi-files upload each of them will be invalidated separately. Works like a charm.
-
Phil over 7 yearsThe only reason this code works as expected is because S3 currently only included one item per notification, ie, the length of the array is happily always 1, and consequently, even if you upload multiple files in one go, you get an entirely new notification per file. You do not get a notification for the whole bucket in any case. None-the-less, this code as written is not ready should AWS change that behaviour. Far safer to write code that handles the whole array, regardless of length, which was my original (sadly missed) point.
-
Kainax over 7 yearsThe only reason why AWS adding events handlers is... well... to handle events. Why would they remove it? No matter how a new file has been added, it should trigger event for API and that is how it works now and will keep working. I'm using AWS for 4 years and they never changed something so previous code stopped working. Even if they changing API, they changing it a new standalone version, but all previous versions are always remain supported. In that particular case I just don't believe that personal file event will ever be removed. It's probably already used by millions projects worldwide.
-
Kainax over 7 yearsIn case if I misunderstand your first comment and you mean that 'Quantity': 1 will add only last item -- there is FOR loop for every item in array.
-
Phil over 7 yearsThe S3 notification from a PUT event includes an ARRAY of Record elements - arrays are of variable length, which is why to process them, one uses a loop, as you have done. But - your code is dependent on the array having exactly 1 element - it is equivalent to simply saying
path = "/" + event["Records"][0]["s3"]["object"]["key"]
(strictly, you will take the last item, not the first, but with an array of length 1, as is currently,, (but need not be), the case, this amounts to the same thing. Also, I never mentioned or suggested AWS removing any notifications. -
Dan G about 6 yearsIf you're just using cloudfront as a mechanism to have a static SSL-enabled S3 site with a custom domain, then caching doesn't matter. Also, these issues we're discussing is that in development phases 0-time caching is good.
-
Herald Smit almost 6 yearsI think you need the asterisk in your 'aws.invalidate' command, change
--paths /
to--paths /*
. mine was also like yours and it did not invalidate the distribution... -
Paul Razvan Berg over 5 years@ill_always_be_a_warriors no, you have to manually do it for all files. I set this but CloudFront didn't refresh my content. I think I'll just give up, CloudFront seems like overkill for a small static website, I'll default to Cloudflare's Flexible SSL 😕
-
Paul Razvan Berg over 5 yearsIn 2018, it's almost instant. Notice I'm deploying a static website via S3.
-
SlyDave over 5 yearsDead link - leads to a 404 :( and I can't update it as version 1.9.12 is missing from the release notes (aws.amazon.com/releasenotes/?tag=releasenotes%23keywords%23cli)
-
RayLuo over 5 yearsDude, thtat was a version released almost 3 years ago. Try the latest version and the feature is likely still there. (Full disclosure: I do not work on AWS CLI anymore.)
-
SlyDave over 5 yearsoh I know, just found it odd that of all the releasenotes, only 1.9.12 doesn't exist :D (which is what I was getting at about not being able to update the link). The comment was more of a hint to anyone that found there way here, like I did and needed to find the releasenotes for AWS CLI. no harm, no foul.
-
Wesley Gonçalves over 3 yearsAs of 2020, the cost is $0.005 per path, not file anymore. So if you invalidate a path like
/*
- all files - you only pay for one invalidation regardless the number of files/URLs. Also AWS provides 1000 Invalidation paths per month for free. See Invalidation requests in the docs -
Aidin about 3 yearsApril 2021 Updates: 1) First 1000 invalidations are free. 2) it's $0.005 per path after that (not per file.) 3) It takes around one minute for ~100 files. 4) You can do it in AWS CLI via
aws cloudfront create-invalidation --distribution-id E1234567890 --paths "/*"
in one line in terminal, 5) To deal with how to also update the path to point to a different version/path in S3, see my answer at stackoverflow.com/a/66976601.