ChatGPT解决这个技术问题 Extra ChatGPT

Force CloudFront distribution/file update

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?

as 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.
@eis unless the file you need to replace has been linked to 1000 different places online. Good luck getting all those links updated.
@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.
In 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.

J
James Lawruk

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>

Please note that invalidation will take some time (apparently 5-30 minutes according to some blog posts I've read).
If 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/…
Remember this costs $0.005 per file after your first 1,000 invalidation requests per month aws.amazon.com/cloudfront/pricing
@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.
As 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
J
John K. Chow

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.)


Where is this setting in the new AWS Console UI? I can't find it.
I 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?
While 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.
Call 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?
If 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.
a
anjanesh

With the Invalidation API, it does get updated in a few of minutes.
Check out PHP Invalidator.


This 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!
J
Josue Alexander Ibarra

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.


Just the last item from each S3 batch?
@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.
The 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.
The 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.
In 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.
L
Leopd

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.


s
samuraisam

If you have boto installed (which is not just for python, but also installs a bunch of useful command line utilities), it offers a command line util specifically called cfadmin or 'cloud front admin' which offers the following functionality:

Usage: cfadmin [command]
cmd - Print help message, optionally about a specific function
help - Print help message, optionally about a specific function
invalidate - Create a cloudfront invalidation request
ls - List all distributions and streaming distributions

You invaliate things by running:

$sam# cfadmin invalidate <distribution> <path>

Actually 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
M
MarcoP

one very easy way to do it is FOLDER versioning.

So if your static files are hundreds for example, simply put all of them into a folder called by year+versioning.

for example i use a folder called 2014_v1 where inside i have all my static files...

So inside my HTML i always put the reference to the folder. ( of course i have a PHP include where i have set the name of the folder. ) So by changing in 1 file it actually change in all my PHP files..

If i want a complete refresh, i simply rename the folder to 2014_v2 into my source and change inside the php include to 2014_v2

all HTML automatically change and ask the new path, cloudfront MISS cache and request it to the source.

Example: SOURCE.mydomain.com is my source, cloudfront.mydomain.com is CNAME to cloudfront distribution.

So the PHP called this file cloudfront.mydomain.com/2014_v1/javascript.js and when i want a full refresh, simply i rename folder into the source to "2014_v2" and i change the PHP include by setting the folder to "2014_v2".

Like this there is no delay for invalidation and NO COST !

This is my first post in stackoverflow, hope i did it well !


F
Fábio Batista

In ruby, using the fog gem

AWS_ACCESS_KEY = ENV['AWS_ACCESS_KEY_ID']
AWS_SECRET_KEY = ENV['AWS_SECRET_ACCESS_KEY']
AWS_DISTRIBUTION_ID = ENV['AWS_DISTRIBUTION_ID']

conn = Fog::CDN.new(
    :provider => 'AWS',
    :aws_access_key_id => AWS_ACCESS_KEY,
    :aws_secret_access_key => AWS_SECRET_KEY
)

images = ['/path/to/image1.jpg', '/path/to/another/image2.jpg']

conn.post_invalidation AWS_DISTRIBUTION_ID, images

even on invalidation, it still takes 5-10 minutes for the invalidation to process and refresh on all amazon edge servers


You just saved my life!
D
Dmitry Efimenko

current AWS CLI support invalidation in preview mode. Run the following in your console once:

aws configure set preview.cloudfront true

I deploy my web project using npm. I have the following scripts in my package.json:

{
    "build.prod": "ng build --prod --aot",
    "aws.deploy": "aws s3 sync dist/ s3://www.mywebsite.com --delete --region us-east-1",
    "aws.invalidate": "aws cloudfront create-invalidation --distribution-id [MY_DISTRIBUTION_ID] --paths /*",
    "deploy": "npm run build.prod && npm run aws.deploy && npm run aws.invalidate"
}

Having the scripts above in place you can deploy your site with:

npm run deploy

I 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...
D
DisgruntledGoat

Just posting to inform anyone visiting this page (first result on 'Cloudfront File Refresh') that there is an easy-to-use+access online invalidator available at swook.net

This new invalidator is:

Fully online (no installation)

Available 24x7 (hosted by Google) and does not require any memberships.

There is history support, and path checking to let you invalidate your files with ease. (Often with just a few clicks after invalidating for the first time!)

It's also very secure, as you'll find out when reading its release post.

Full disclosure: I made this. Have fun!


sorry, 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 ?
You should put this behind https at the least.
Online 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.
For the security of others, I'm downvoting this answer. You should never ever ask people for their credentials
R
RayLuo

If you are using AWS, you probably also use its official CLI tool (sooner or later). AWS CLI version 1.9.12 or above supports invalidating a list of file names.

Full disclosure: I made this. Have fun!


Dead 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)
Dude, 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.)
oh 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.
J
Jay

Go to CloudFront.

Click on your ID/Distributions.

Click on Invalidations.

Click create Invalidation.

In the giant example box type * and click invalidate

Done

https://i.stack.imgur.com/DgWVA.png